blob: bf7c690ac2bcb9d20d104943f71d0c7af3ba8c51 [file] [log] [blame]
Chris Lattner697e5d62006-11-09 06:32:27 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner697e5d62006-11-09 06:32:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnere168f762006-11-10 05:29:30 +000014#include "Sema.h"
Anders Carlsson7a241ba2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner622c1932008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner5c5fbcc2006-12-03 08:41:30 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner2c6fcf52008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner591a6752006-11-19 23:16:18 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbarc74b5cc2008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner9561a0b2007-01-28 08:20:04 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroffe101f952008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner622c1932008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroffe101f952008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Chris Lattner38047f92007-01-27 06:24:01 +000027#include "llvm/ADT/SmallSet.h"
Chris Lattner697e5d62006-11-09 06:32:27 +000028using namespace clang;
29
Argyrios Kyrtzidis25d05e82008-08-01 10:35:27 +000030Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
Steve Naroff2fc93f52008-04-02 14:35:35 +000031 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
32
Douglas Gregor83a586e2008-04-13 21:07:44 +000033 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
34 isa<ObjCInterfaceDecl>(IIDecl) ||
35 isa<TagDecl>(IIDecl)))
Fariborz Jahaniand52cd412007-10-12 16:34:10 +000036 return IIDecl;
Steve Naroff09bf8152007-09-06 21:24:23 +000037 return 0;
Chris Lattnere168f762006-11-10 05:29:30 +000038}
39
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000040DeclContext *Sema::getDCParent(DeclContext *DC) {
41 // If CurContext is a ObjC method, getParent() will return NULL.
42 if (isa<ObjCMethodDecl>(DC))
43 return Context.getTranslationUnitDecl();
44
45 // A C++ inline method is parsed *after* the topmost class it was declared in
46 // is fully parsed (it's "complete").
47 // The parsing of a C++ inline method happens at the declaration context of
48 // the topmost (non-nested) class it is declared in.
49 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
50 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
51 DC = MD->getParent();
52 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
53 DC = RD;
54
55 // Return the declaration context of the topmost class the inline method is
56 // declared in.
57 return DC;
58 }
59
60 return DC->getParent();
61}
62
Chris Lattnerbec41342008-04-22 18:39:57 +000063void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000064 assert(getDCParent(DC) == CurContext &&
65 "The next DeclContext should be directly contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +000066 CurContext = DC;
Chris Lattnerc5ffed42008-04-04 06:12:32 +000067}
68
Chris Lattner0a5ff0d2008-04-06 04:47:34 +000069void Sema::PopDeclContext() {
70 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000071 CurContext = getDCParent(CurContext);
Chris Lattnerc5ffed42008-04-04 06:12:32 +000072}
73
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +000074/// Add this decl to the scope shadowed decl chains.
75void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +000076 S->AddDecl(D);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +000077
78 // C++ [basic.scope]p4:
79 // -- exactly one declaration shall declare a class name or
80 // enumeration name that is not a typedef name and the other
81 // declarations shall all refer to the same object or
82 // enumerator, or all refer to functions and function templates;
83 // in this case the class name or enumeration name is hidden.
84 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
85 // We are pushing the name of a tag (enum or class).
Argyrios Kyrtzidisef34aed2008-07-17 17:49:50 +000086 IdentifierResolver::iterator
87 I = IdResolver.begin(TD->getIdentifier(),
88 TD->getDeclContext(), false/*LookInParentCtx*/);
89 if (I != IdResolver.end() &&
90 IdResolver.isDeclInScope(*I, TD->getDeclContext(), S)) {
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +000091 // There is already a declaration with the same name in the same
92 // scope. It must be found before we find the new declaration,
93 // so swap the order on the shadowed declaration chain.
94
Argyrios Kyrtzidisef34aed2008-07-17 17:49:50 +000095 IdResolver.AddShadowedDecl(TD, *I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +000096 return;
97 }
98 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +000099 IdResolver.AddDecl(D);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000100}
101
Steve Naroffc62adb62007-10-09 22:01:59 +0000102void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000103 if (S->decl_empty()) return;
104 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000105
Chris Lattner302b4be2006-11-19 02:31:38 +0000106 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
107 I != E; ++I) {
Steve Naroff9324db12007-09-13 18:10:37 +0000108 Decl *TmpD = static_cast<Decl*>(*I);
109 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +0000110
111 if (isa<CXXFieldDecl>(TmpD)) continue;
112
113 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
114 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroff9324db12007-09-13 18:10:37 +0000115
Chris Lattnerff65b6b2007-01-23 01:33:16 +0000116 IdentifierInfo *II = D->getIdentifier();
117 if (!II) continue;
Chris Lattner302b4be2006-11-19 02:31:38 +0000118
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +0000119 // We only want to remove the decls from the identifier decl chains for local
120 // scopes, when inside a function/method.
121 if (S->getFnParent() != 0)
122 IdResolver.RemoveDecl(D);
Chris Lattnerc5c95b52008-04-11 07:00:53 +0000123
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +0000124 // Chain this decl to the containing DeclContext.
125 D->setNext(CurContext->getDeclChain());
126 CurContext->setDeclChain(D);
Chris Lattner302b4be2006-11-19 02:31:38 +0000127 }
128}
129
Steve Naroff257520b2008-04-01 23:04:06 +0000130/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
131/// return 0 if one not found.
Steve Naroff257520b2008-04-01 23:04:06 +0000132ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff77892752008-04-02 18:30:49 +0000133 // The third "scope" argument is 0 since we aren't enabling lazy built-in
134 // creation from this context.
135 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +0000136
Steve Naroff2fc93f52008-04-02 14:35:35 +0000137 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +0000138}
139
Steve Naroff257520b2008-04-01 23:04:06 +0000140/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner18b19622007-01-22 07:39:13 +0000141/// namespace.
Steve Naroff2fc93f52008-04-02 14:35:35 +0000142Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
143 Scope *S, bool enableLazyBuiltinCreation) {
Chris Lattner18b19622007-01-22 07:39:13 +0000144 if (II == 0) return 0;
Douglas Gregor83a586e2008-04-13 21:07:44 +0000145 unsigned NS = NSI;
146 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
147 NS |= Decl::IDNS_Tag;
Chris Lattnerc5c95b52008-04-11 07:00:53 +0000148
Chris Lattner18b19622007-01-22 07:39:13 +0000149 // Scan up the scope chain looking for a decl that matches this identifier
150 // that is in the appropriate namespace. This search should not take long, as
151 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000152 for (IdentifierResolver::iterator
Argyrios Kyrtzidisef34aed2008-07-17 17:49:50 +0000153 I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I)
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000154 if ((*I)->getIdentifierNamespace() & NS)
155 return *I;
Chris Lattnerc5c95b52008-04-11 07:00:53 +0000156
Chris Lattner9561a0b2007-01-28 08:20:04 +0000157 // If we didn't find a use of this identifier, and if the identifier
158 // corresponds to a compiler builtin, create the decl object for the builtin
159 // now, injecting it into translation unit scope, and return it.
Douglas Gregor83a586e2008-04-13 21:07:44 +0000160 if (NS & Decl::IDNS_Ordinary) {
Steve Naroff2fc93f52008-04-02 14:35:35 +0000161 if (enableLazyBuiltinCreation) {
162 // If this is a builtin on this (or all) targets, create the decl.
163 if (unsigned BuiltinID = II->getBuiltinID())
164 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
165 }
Steve Naroff257520b2008-04-01 23:04:06 +0000166 if (getLangOptions().ObjC1) {
167 // @interface and @compatibility_alias introduce typedef-like names.
168 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff9b94b172008-04-02 00:39:51 +0000169 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroff257520b2008-04-01 23:04:06 +0000170 // other names in IDNS_Ordinary.
Steve Naroff77892752008-04-02 18:30:49 +0000171 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
172 if (IDI != ObjCInterfaceDecls.end())
173 return IDI->second;
Steve Naroff257520b2008-04-01 23:04:06 +0000174 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
175 if (I != ObjCAliasDecls.end())
176 return I->second->getClassInterface();
177 }
Chris Lattner9561a0b2007-01-28 08:20:04 +0000178 }
Chris Lattner18b19622007-01-22 07:39:13 +0000179 return 0;
180}
181
Chris Lattner4dd27102008-05-05 22:18:14 +0000182void Sema::InitBuiltinVaListType() {
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000183 if (!Context.getBuiltinVaListType().isNull())
184 return;
185
186 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff2fc93f52008-04-02 14:35:35 +0000187 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffeee59eb2007-10-18 22:17:45 +0000188 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000189 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
190}
191
Chris Lattner9561a0b2007-01-28 08:20:04 +0000192/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
193/// lazily create a decl for it.
Chris Lattner9c7a0362007-10-10 23:42:28 +0000194ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
195 Scope *S) {
Chris Lattner9561a0b2007-01-28 08:20:04 +0000196 Builtin::ID BID = (Builtin::ID)bid;
197
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000198 if (BID == Builtin::BI__builtin_va_start ||
Chris Lattner4dd27102008-05-05 22:18:14 +0000199 BID == Builtin::BI__builtin_va_copy ||
Chris Lattnerb2182722008-07-09 17:26:36 +0000200 BID == Builtin::BI__builtin_va_end ||
201 BID == Builtin::BI__builtin_stdarg_start)
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000202 InitBuiltinVaListType();
203
Anders Carlsson87c149b2007-10-11 01:00:40 +0000204 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +0000205 FunctionDecl *New = FunctionDecl::Create(Context,
206 Context.getTranslationUnitDecl(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000207 SourceLocation(), II, R,
Chris Lattner5072bae2008-03-15 21:24:04 +0000208 FunctionDecl::Extern, false, 0);
Chris Lattner9561a0b2007-01-28 08:20:04 +0000209
Chris Lattner4dd27102008-05-05 22:18:14 +0000210 // Create Decl objects for each parameter, adding them to the
211 // FunctionDecl.
212 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
213 llvm::SmallVector<ParmVarDecl*, 16> Params;
214 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
215 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
216 FT->getArgType(i), VarDecl::None, 0,
217 0));
218 New->setParams(&Params[0], Params.size());
219 }
220
221
222
Chris Lattnerc5c95b52008-04-11 07:00:53 +0000223 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000224 PushOnScopeChains(New, TUScope);
Chris Lattner9561a0b2007-01-28 08:20:04 +0000225 return New;
226}
227
Chris Lattner01564d92007-01-27 19:27:06 +0000228/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
229/// and scope as a previous declaration 'Old'. Figure out how to resolve this
230/// situation, merging decls or emitting diagnostics as appropriate.
231///
Steve Naroff257520b2008-04-01 23:04:06 +0000232TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000233 // Verify the old decl was also a typedef.
234 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
235 if (!Old) {
236 Diag(New->getLocation(), diag::err_redefinition_different_kind,
237 New->getName());
238 Diag(OldD->getLocation(), diag::err_previous_definition);
239 return New;
240 }
241
Chris Lattnerf9c49e52008-07-25 18:44:27 +0000242 // If the typedef types are not identical, reject them in all languages and
243 // with any extensions enabled.
244 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
245 Context.getCanonicalType(Old->getUnderlyingType()) !=
246 Context.getCanonicalType(New->getUnderlyingType())) {
247 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
248 New->getUnderlyingType().getAsString(),
249 Old->getUnderlyingType().getAsString());
250 Diag(Old->getLocation(), diag::err_previous_definition);
251 return Old;
252 }
253
Steve Naroff6d40db02007-10-31 18:42:27 +0000254 // Allow multiple definitions for ObjC built-in typedefs.
255 // FIXME: Verify the underlying types are equivalent!
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000256 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff6d40db02007-10-31 18:42:27 +0000257 return Old;
Eli Friedman61b529f2008-06-11 06:20:39 +0000258
259 if (getLangOptions().Microsoft) return New;
260
Steve Naroffe101f952008-01-30 23:46:05 +0000261 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
262 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
263 // *either* declaration is in a system header. The code below implements
264 // this adhoc compatibility rule. FIXME: The following code will not
265 // work properly when compiling ".i" files (containing preprocessed output).
266 SourceManager &SrcMgr = Context.getSourceManager();
Nico Weberfa5856a2008-08-29 17:02:23 +0000267 if (SrcMgr.isInSystemHeader(Old->getLocation()))
268 return New;
269 if (SrcMgr.isInSystemHeader(New->getLocation()))
270 return New;
Eli Friedman61b529f2008-06-11 06:20:39 +0000271
Ted Kremenek20ccc4c2008-05-23 21:28:18 +0000272 Diag(New->getLocation(), diag::err_redefinition, New->getName());
273 Diag(Old->getLocation(), diag::err_previous_definition);
Chris Lattner01564d92007-01-27 19:27:06 +0000274 return New;
275}
276
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000277/// DeclhasAttr - returns true if decl Declaration already has the target
278/// attribute.
Chris Lattner84966392008-03-03 03:28:21 +0000279static bool DeclHasAttr(const Decl *decl, const Attr *target) {
280 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
281 if (attr->getKind() == target->getKind())
282 return true;
283
284 return false;
285}
286
287/// MergeAttributes - append attributes from the Old decl to the New one.
288static void MergeAttributes(Decl *New, Decl *Old) {
289 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
290
Chris Lattner84966392008-03-03 03:28:21 +0000291 while (attr) {
292 tmp = attr;
293 attr = attr->getNext();
294
295 if (!DeclHasAttr(New, tmp)) {
296 New->addAttr(tmp);
297 } else {
298 tmp->setNext(0);
299 delete(tmp);
300 }
301 }
Nuno Lopes3fe46512008-06-01 22:53:53 +0000302
303 Old->invalidateAttrs();
Chris Lattner84966392008-03-03 03:28:21 +0000304}
305
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000306/// MergeFunctionDecl - We just parsed a function 'New' from
307/// declarator D which has the same name and scope as a previous
308/// declaration 'Old'. Figure out how to resolve this situation,
309/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor89f238c2008-04-21 02:02:58 +0000310/// Redeclaration will be set true if thisNew is a redeclaration OldD.
311FunctionDecl *
312Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
313 Redeclaration = false;
Chris Lattnerc511efb2007-01-27 19:32:14 +0000314 // Verify the old decl was also a function.
315 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
316 if (!Old) {
317 Diag(New->getLocation(), diag::err_redefinition_different_kind,
318 New->getName());
319 Diag(OldD->getLocation(), diag::err_previous_definition);
320 return New;
321 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000322
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000323 QualType OldQType = Context.getCanonicalType(Old->getType());
324 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner5c3f1542007-11-20 19:04:50 +0000325
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000326 // C++ [dcl.fct]p3:
327 // All declarations for a function shall agree exactly in both the
328 // return type and the parameter-type-list.
Douglas Gregor89f238c2008-04-21 02:02:58 +0000329 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
330 MergeAttributes(New, Old);
331 Redeclaration = true;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000332 return MergeCXXFunctionDecl(New, Old);
Douglas Gregor89f238c2008-04-21 02:02:58 +0000333 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000334
335 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +0000336 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000337 if (!getLangOptions().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +0000338 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor89f238c2008-04-21 02:02:58 +0000339 MergeAttributes(New, Old);
340 Redeclaration = true;
Steve Naroff012484d2008-01-14 20:51:29 +0000341 return New;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000342 }
Chris Lattner45d561a2007-11-06 06:07:26 +0000343
Steve Naroff17832a42008-01-16 15:01:34 +0000344 // A function that has already been declared has been redeclared or defined
345 // with a different type- show appropriate diagnostic
Steve Naroff3913ea42008-04-04 14:32:09 +0000346 diag::kind PrevDiag;
Douglas Gregor89f238c2008-04-21 02:02:58 +0000347 if (Old->isThisDeclarationADefinition())
Steve Naroff3913ea42008-04-04 14:32:09 +0000348 PrevDiag = diag::err_previous_definition;
349 else if (Old->isImplicit())
350 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000351 else
Steve Naroff3913ea42008-04-04 14:32:09 +0000352 PrevDiag = diag::err_previous_declaration;
Steve Naroff17832a42008-01-16 15:01:34 +0000353
Chris Lattner01564d92007-01-27 19:27:06 +0000354 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
355 // TODO: This is totally simplistic. It should handle merging functions
356 // together etc, merging extern int X; int X; ...
Steve Naroff17832a42008-01-16 15:01:34 +0000357 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
358 Diag(Old->getLocation(), PrevDiag);
Chris Lattner01564d92007-01-27 19:27:06 +0000359 return New;
360}
361
Steve Naroff5bb8f222008-08-08 17:50:35 +0000362/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroff63ebb3c2008-08-10 15:28:06 +0000363static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroff5bb8f222008-08-08 17:50:35 +0000364 if (VD->isFileVarDecl())
365 return (!VD->getInit() &&
366 (VD->getStorageClass() == VarDecl::None ||
367 VD->getStorageClass() == VarDecl::Static));
368 return false;
369}
370
371/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
372/// when dealing with C "tentative" external object definitions (C99 6.9.2).
373void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
374 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff84e37352008-08-10 15:20:13 +0000375 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroff5bb8f222008-08-08 17:50:35 +0000376
377 for (IdentifierResolver::iterator
378 I = IdResolver.begin(VD->getIdentifier(),
379 VD->getDeclContext(), false/*LookInParentCtx*/),
380 E = IdResolver.end(); I != E; ++I) {
381 if (*I != VD && IdResolver.isDeclInScope(*I, VD->getDeclContext(), S)) {
382 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
383
Steve Naroff84e37352008-08-10 15:20:13 +0000384 // Handle the following case:
385 // int a[10];
386 // int a[]; - the code below makes sure we set the correct type.
387 // int a[11]; - this is an error, size isn't 10.
388 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
389 OldDecl->getType()->isConstantArrayType())
390 VD->setType(OldDecl->getType());
391
Steve Naroff5bb8f222008-08-08 17:50:35 +0000392 // Check for "tentative" definitions. We can't accomplish this in
393 // MergeVarDecl since the initializer hasn't been attached.
394 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
395 continue;
396
397 // Handle __private_extern__ just like extern.
398 if (OldDecl->getStorageClass() != VarDecl::Extern &&
399 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
400 VD->getStorageClass() != VarDecl::Extern &&
401 VD->getStorageClass() != VarDecl::PrivateExtern) {
402 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
403 Diag(OldDecl->getLocation(), diag::err_previous_definition);
404 }
405 }
406 }
407}
408
Chris Lattner01564d92007-01-27 19:27:06 +0000409/// MergeVarDecl - We just parsed a variable 'New' which has the same name
410/// and scope as a previous declaration 'Old'. Figure out how to resolve this
411/// situation, merging decls or emitting diagnostics as appropriate.
412///
Steve Naroff5bb8f222008-08-08 17:50:35 +0000413/// Tentative definition rules (C99 6.9.2p2) are checked by
414/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
415/// definitions here, since the initializer hasn't been attached.
Steve Narofffc49d672007-04-01 21:27:45 +0000416///
Steve Naroff257520b2008-04-01 23:04:06 +0000417VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000418 // Verify the old decl was also a variable.
419 VarDecl *Old = dyn_cast<VarDecl>(OldD);
420 if (!Old) {
421 Diag(New->getLocation(), diag::err_redefinition_different_kind,
422 New->getName());
423 Diag(OldD->getLocation(), diag::err_previous_definition);
424 return New;
425 }
Chris Lattner84966392008-03-03 03:28:21 +0000426
427 MergeAttributes(New, Old);
428
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000429 // Verify the types match.
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000430 QualType OldCType = Context.getCanonicalType(Old->getType());
431 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff239255d2008-08-09 16:04:40 +0000432 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000433 Diag(New->getLocation(), diag::err_redefinition, New->getName());
434 Diag(Old->getLocation(), diag::err_previous_definition);
435 return New;
436 }
Steve Naroff1e787362008-01-30 00:44:01 +0000437 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
438 if (New->getStorageClass() == VarDecl::Static &&
439 (Old->getStorageClass() == VarDecl::None ||
440 Old->getStorageClass() == VarDecl::Extern)) {
441 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
442 Diag(Old->getLocation(), diag::err_previous_definition);
443 return New;
444 }
445 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
446 if (New->getStorageClass() != VarDecl::Static &&
447 Old->getStorageClass() == VarDecl::Static) {
448 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
449 Diag(Old->getLocation(), diag::err_previous_definition);
450 return New;
451 }
Steve Naroff5bb8f222008-08-08 17:50:35 +0000452 // File scoped variables are analyzed in FinalizeDeclaratorGroup.
453 if (!New->isFileVarDecl()) {
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000454 Diag(New->getLocation(), diag::err_redefinition, New->getName());
455 Diag(Old->getLocation(), diag::err_previous_definition);
456 }
Chris Lattner01564d92007-01-27 19:27:06 +0000457 return New;
458}
459
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000460/// CheckParmsForFunctionDef - Check that the parameters of the given
461/// function are appropriate for the definition of a function. This
462/// takes care of any checks that cannot be performed on the
463/// declaration itself, e.g., that the types of each of the function
464/// parameters are complete.
465bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
466 bool HasInvalidParm = false;
467 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
468 ParmVarDecl *Param = FD->getParamDecl(p);
469
470 // C99 6.7.5.3p4: the parameters in a parameter type list in a
471 // function declarator that is part of a function definition of
472 // that function shall not have incomplete type.
473 if (Param->getType()->isIncompleteType() &&
474 !Param->isInvalidDecl()) {
475 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
476 Param->getType().getAsString());
477 Param->setInvalidDecl();
478 HasInvalidParm = true;
479 }
480 }
481
482 return HasInvalidParm;
483}
484
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000485/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
486/// no declarator (e.g. "struct foo;") is parsed.
487Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
488 // TODO: emit error on 'int;' or 'const enum foo;'.
489 // TODO: emit error on 'typedef int;'
490 // if (!DS.isMissingDeclaratorOk()) Diag(...);
491
Steve Naroff14f5f792007-11-17 21:37:36 +0000492 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000493}
494
Steve Naroff98f72032008-01-10 22:15:12 +0000495bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroff2fea1392007-09-02 02:04:30 +0000496 // Get the type before calling CheckSingleAssignmentConstraints(), since
497 // it can promote the expression.
Chris Lattner9bad62c2008-01-04 18:04:52 +0000498 QualType InitType = Init->getType();
Steve Naroff2fea1392007-09-02 02:04:30 +0000499
Chris Lattner9bad62c2008-01-04 18:04:52 +0000500 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
501 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
502 InitType, Init, "initializing");
Steve Naroff2fea1392007-09-02 02:04:30 +0000503}
504
Steve Naroffaf2a0222008-01-22 00:55:40 +0000505bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattner7adf0762008-08-04 07:31:14 +0000506 const ArrayType *AT = Context.getAsArrayType(DeclT);
507
508 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffaf2a0222008-01-22 00:55:40 +0000509 // C99 6.7.8p14. We have an array of character type with unknown size
510 // being initialized to a string literal.
511 llvm::APSInt ConstVal(32);
512 ConstVal = strLiteral->getByteLength() + 1;
513 // Return a new array type (C99 6.7.8p22).
Eli Friedmanbd258282008-02-15 18:16:39 +0000514 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffaf2a0222008-01-22 00:55:40 +0000515 ArrayType::Normal, 0);
Chris Lattner7adf0762008-08-04 07:31:14 +0000516 } else {
517 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffaf2a0222008-01-22 00:55:40 +0000518 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattner7adf0762008-08-04 07:31:14 +0000519 // FIXME: Avoid truncation for 64-bit length strings.
520 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffaf2a0222008-01-22 00:55:40 +0000521 Diag(strLiteral->getSourceRange().getBegin(),
522 diag::warn_initializer_string_for_char_array_too_long,
523 strLiteral->getSourceRange());
Steve Naroffaf2a0222008-01-22 00:55:40 +0000524 }
525 // Set type from "char *" to "constant array of char".
526 strLiteral->setType(DeclT);
527 // For now, we always return false (meaning success).
528 return false;
529}
530
531StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattner7adf0762008-08-04 07:31:14 +0000532 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000533 if (AT && AT->getElementType()->isCharType()) {
534 return dyn_cast<StringLiteral>(Init);
535 }
Steve Naroffaf2a0222008-01-22 00:55:40 +0000536 return 0;
537}
538
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000539bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Narofff9eb5982008-01-21 23:53:58 +0000540 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
541 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattner7adf0762008-08-04 07:31:14 +0000542 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Steve Narofff9eb5982008-01-21 23:53:58 +0000543 return Diag(VAT->getSizeExpr()->getLocStart(),
544 diag::err_variable_object_no_init,
545 VAT->getSizeExpr()->getSourceRange());
546
Steve Naroff91f78082007-12-10 22:44:33 +0000547 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
548 if (!InitList) {
Steve Naroffaf2a0222008-01-22 00:55:40 +0000549 // FIXME: Handle wide strings
550 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
551 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman42978262008-02-08 00:48:24 +0000552
553 if (DeclType->isArrayType())
554 return Diag(Init->getLocStart(),
555 diag::err_array_init_list_required,
556 Init->getSourceRange());
557
Steve Naroff98f72032008-01-10 22:15:12 +0000558 return CheckSingleInitializer(Init, DeclType);
Steve Naroff91f78082007-12-10 22:44:33 +0000559 }
Eli Friedman01321c32008-06-06 19:40:52 +0000560
Steve Narofff8ecff22008-05-01 22:18:59 +0000561 InitListChecker CheckInitList(this, InitList, DeclType);
562 return CheckInitList.HadError();
Steve Naroff2fea1392007-09-02 02:04:30 +0000563}
564
Fariborz Jahanian56ff1462007-11-08 23:49:49 +0000565Sema::DeclTy *
Daniel Dunbar1ff1d1f2008-08-05 16:28:08 +0000566Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroffa23cc792007-09-13 23:52:58 +0000567 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattnere168f762006-11-10 05:29:30 +0000568 IdentifierInfo *II = D.getIdentifier();
Chris Lattner302b4be2006-11-19 02:31:38 +0000569
Chris Lattner02c04392007-07-25 00:24:17 +0000570 // All of these full declarators require an identifier. If it doesn't have
571 // one, the ParsedFreeStandingDeclSpec action should be used.
572 if (II == 0) {
Chris Lattnera7c19fe2007-10-16 22:36:42 +0000573 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerc4f6d0c2007-08-28 06:17:15 +0000574 diag::err_declarator_need_ident,
Chris Lattner02c04392007-07-25 00:24:17 +0000575 D.getDeclSpec().getSourceRange(), D.getSourceRange());
576 return 0;
577 }
578
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000579 // The scope passed in may not be a decl scope. Zip up the scope tree until
580 // we find one that is.
581 while ((S->getFlags() & Scope::DeclScope) == 0)
582 S = S->getParent();
583
Chris Lattner01564d92007-01-27 19:27:06 +0000584 // See if this is a redefinition of a variable in the same scope.
Steve Naroff2fc93f52008-04-02 14:35:35 +0000585 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroff9324db12007-09-13 18:10:37 +0000586 ScopedDecl *New;
Steve Narofff93b6722007-08-28 20:14:24 +0000587 bool InvalidDecl = false;
Douglas Gregor83a586e2008-04-13 21:07:44 +0000588
589 // In C++, the previous declaration we find might be a tag type
590 // (class or enum). In this case, the new declaration will hide the
591 // tag type.
592 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
593 PrevDecl = 0;
594
Chris Lattner07b201d2007-11-14 06:34:38 +0000595 QualType R = GetTypeForDeclarator(D, S);
596 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
597
Chris Lattner01a7c532007-01-25 23:09:03 +0000598 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000599 // Check that there are no default arguments (C++ only).
600 if (getLangOptions().CPlusPlus)
601 CheckExtraCXXDefaultArguments(D);
602
Chris Lattner07b201d2007-11-14 06:34:38 +0000603 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner01564d92007-01-27 19:27:06 +0000604 if (!NewTD) return 0;
Steve Naroffa8fd9732007-06-11 00:35:03 +0000605
606 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner2727d1b2008-06-29 00:02:00 +0000607 ProcessDeclAttributes(NewTD, D);
Steve Naroffe6b0ec82008-01-09 23:34:55 +0000608 // Merge the decl with the existing one if appropriate. If the decl is
609 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000610 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner01564d92007-01-27 19:27:06 +0000611 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
612 if (NewTD == 0) return 0;
613 }
614 New = NewTD;
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000615 if (S->getFnParent() == 0) {
Steve Naroff8eeeb132007-05-08 21:09:37 +0000616 // C99 6.7.7p2: If a typedef name specifies a variably modified type
617 // then it shall have block scope.
Eli Friedman9e805b22008-02-15 12:53:51 +0000618 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
619 // FIXME: Diagnostic needs to be fixed.
620 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff096dd942007-08-31 17:20:07 +0000621 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000622 }
623 }
Chris Lattner07b201d2007-11-14 06:34:38 +0000624 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattnercc61bf52007-09-27 15:15:46 +0000625 FunctionDecl::StorageClass SC = FunctionDecl::None;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000626 switch (D.getDeclSpec().getStorageClassSpec()) {
627 default: assert(0 && "Unknown storage class!");
628 case DeclSpec::SCS_auto:
629 case DeclSpec::SCS_register:
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000630 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
631 R.getAsString());
Steve Narofff93b6722007-08-28 20:14:24 +0000632 InvalidDecl = true;
633 break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000634 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
635 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
636 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff1f7f6922008-01-28 21:57:15 +0000637 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000638 }
639
Chris Lattner5072bae2008-03-15 21:24:04 +0000640 bool isInline = D.getDeclSpec().isInlineSpecified();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000641 FunctionDecl *NewFD;
642 if (D.getContext() == Declarator::MemberContext) {
643 // This is a C++ method declaration.
644 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
645 D.getIdentifierLoc(), II, R,
646 (SC == FunctionDecl::Static), isInline,
647 LastDeclarator);
648 } else {
649 NewFD = FunctionDecl::Create(Context, CurContext,
650 D.getIdentifierLoc(),
651 II, R, SC, isInline,
652 LastDeclarator);
653 }
Ted Kremenek49b61ab2008-02-27 22:18:07 +0000654 // Handle attributes.
Chris Lattner2727d1b2008-06-29 00:02:00 +0000655 ProcessDeclAttributes(NewFD, D);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000656
Daniel Dunbar4983df32008-08-05 01:35:17 +0000657 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar1ff1d1f2008-08-05 16:28:08 +0000658 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbar4983df32008-08-05 01:35:17 +0000659 // The parser guarantees this is a string.
660 StringLiteral *SE = cast<StringLiteral>(E);
661 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
662 SE->getByteLength())));
663 }
664
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000665 // Copy the parameter declarations from the declarator D to
666 // the function declaration NewFD, if they are available.
Eli Friedman3d421e12008-08-25 21:31:01 +0000667 if (D.getNumTypeObjects() > 0) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000668 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
669
670 // Create Decl objects for each parameter, adding them to the
671 // FunctionDecl.
672 llvm::SmallVector<ParmVarDecl*, 16> Params;
673
674 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
675 // function that takes no arguments, not a function that takes a
Chris Lattner58258242008-04-10 02:22:51 +0000676 // single void argument.
Eli Friedmanbb5de962008-05-22 08:54:03 +0000677 // We let through "const void" here because Sema::GetTypeForDeclarator
678 // already checks for that case.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000679 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
680 FTI.ArgInfo[0].Param &&
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000681 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
682 // empty arg list, don't push any params.
Chris Lattner58258242008-04-10 02:22:51 +0000683 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
684
Chris Lattner0e91b412008-04-10 02:26:16 +0000685 // In C++, the empty parameter-type-list must be spelled "void"; a
686 // typedef of void is not permitted.
687 if (getLangOptions().CPlusPlus &&
Eli Friedmanbb5de962008-05-22 08:54:03 +0000688 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner58258242008-04-10 02:22:51 +0000689 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
690 }
691
Eli Friedman3d421e12008-08-25 21:31:01 +0000692 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000693 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
694 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
695 }
696
697 NewFD->setParams(&Params[0], Params.size());
698 }
699
Steve Naroffe6b0ec82008-01-09 23:34:55 +0000700 // Merge the decl with the existing one if appropriate. Since C functions
701 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000702 if (PrevDecl &&
703 (!getLangOptions().CPlusPlus ||
704 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregor89f238c2008-04-21 02:02:58 +0000705 bool Redeclaration = false;
706 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Chris Lattner01564d92007-01-27 19:27:06 +0000707 if (NewFD == 0) return 0;
Douglas Gregor89f238c2008-04-21 02:02:58 +0000708 if (Redeclaration) {
Eli Friedmanaee9e542008-05-27 05:07:37 +0000709 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregor89f238c2008-04-21 02:02:58 +0000710 }
Chris Lattner01564d92007-01-27 19:27:06 +0000711 }
712 New = NewFD;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000713
714 // In C++, check default arguments now that we have merged decls.
715 if (getLangOptions().CPlusPlus)
716 CheckCXXDefaultArguments(NewFD);
Chris Lattner01a7c532007-01-25 23:09:03 +0000717 } else {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000718 // Check that there are no default arguments (C++ only).
719 if (getLangOptions().CPlusPlus)
720 CheckExtraCXXDefaultArguments(D);
721
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000722 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +0000723 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
724 D.getIdentifier()->getName());
725 InvalidDecl = true;
726 }
Chris Lattner01564d92007-01-27 19:27:06 +0000727
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000728 VarDecl *NewVD;
729 VarDecl::StorageClass SC;
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000730 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner4b08ca82008-03-15 21:10:16 +0000731 default: assert(0 && "Unknown storage class!");
732 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
733 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
734 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
735 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
736 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
737 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000738 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000739 if (D.getContext() == Declarator::MemberContext) {
740 assert(SC == VarDecl::Static && "Invalid storage class for member!");
741 // This is a static data member for a C++ class.
742 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
743 D.getIdentifierLoc(), II,
744 R, LastDeclarator);
Steve Naroff2fea1392007-09-02 02:04:30 +0000745 } else {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000746 if (S->getFnParent() == 0) {
747 // C99 6.9p2: The storage-class specifiers auto and register shall not
748 // appear in the declaration specifiers in an external declaration.
749 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
750 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
751 R.getAsString());
752 InvalidDecl = true;
753 }
754 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
755 II, R, SC, LastDeclarator);
756 } else {
757 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
758 II, R, SC, LastDeclarator);
759 }
Steve Naroffcf871f52007-08-28 18:45:29 +0000760 }
Steve Naroffa8fd9732007-06-11 00:35:03 +0000761 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner2727d1b2008-06-29 00:02:00 +0000762 ProcessDeclAttributes(NewVD, D);
Nate Begemanb561de72008-03-14 18:07:10 +0000763
Daniel Dunbarffc29be2008-08-06 00:03:29 +0000764 // Handle GNU asm-label extension (encoded as an attribute).
765 if (Expr *E = (Expr*) D.getAsmLabel()) {
766 // The parser guarantees this is a string.
767 StringLiteral *SE = cast<StringLiteral>(E);
768 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
769 SE->getByteLength())));
770 }
771
Nate Begemanb561de72008-03-14 18:07:10 +0000772 // Emit an error if an address space was applied to decl with local storage.
773 // This includes arrays of objects with address space qualifiers, but not
774 // automatic variables that point to other address spaces.
775 // ISO/IEC TR 18037 S5.1.2
Nate Begemanc506c782008-03-25 18:36:32 +0000776 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
777 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
778 InvalidDecl = true;
Nate Begeman144625e2008-03-14 00:22:18 +0000779 }
Steve Naroffe6b0ec82008-01-09 23:34:55 +0000780 // Merge the decl with the existing one if appropriate. If the decl is
781 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000782 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner01564d92007-01-27 19:27:06 +0000783 NewVD = MergeVarDecl(NewVD, PrevDecl);
784 if (NewVD == 0) return 0;
785 }
786 New = NewVD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000787 }
Chris Lattner302b4be2006-11-19 02:31:38 +0000788
Chris Lattnere168f762006-11-10 05:29:30 +0000789 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000790 if (II)
791 PushOnScopeChains(New, S);
Steve Narofff93b6722007-08-28 20:14:24 +0000792 // If any semantic error occurred, mark the decl as invalid.
793 if (D.getInvalidType() || InvalidDecl)
794 New->setInvalidDecl();
Chris Lattnere168f762006-11-10 05:29:30 +0000795
796 return New;
797}
798
Eli Friedmand5a55bd2008-05-20 13:48:25 +0000799bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
800 switch (Init->getStmtClass()) {
801 default:
802 Diag(Init->getExprLoc(),
803 diag::err_init_element_not_constant, Init->getSourceRange());
804 return true;
805 case Expr::ParenExprClass: {
806 const ParenExpr* PE = cast<ParenExpr>(Init);
807 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
808 }
809 case Expr::CompoundLiteralExprClass:
810 return cast<CompoundLiteralExpr>(Init)->isFileScope();
811 case Expr::DeclRefExprClass: {
812 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman86346ed2008-05-21 03:39:11 +0000813 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
814 if (VD->hasGlobalStorage())
815 return false;
816 Diag(Init->getExprLoc(),
817 diag::err_init_element_not_constant, Init->getSourceRange());
818 return true;
819 }
Eli Friedmand5a55bd2008-05-20 13:48:25 +0000820 if (isa<FunctionDecl>(D))
821 return false;
822 Diag(Init->getExprLoc(),
823 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Naroff98f72032008-01-10 22:15:12 +0000824 return true;
825 }
Eli Friedmand5a55bd2008-05-20 13:48:25 +0000826 case Expr::MemberExprClass: {
827 const MemberExpr *M = cast<MemberExpr>(Init);
828 if (M->isArrow())
829 return CheckAddressConstantExpression(M->getBase());
830 return CheckAddressConstantExpressionLValue(M->getBase());
831 }
832 case Expr::ArraySubscriptExprClass: {
833 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
834 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
835 return CheckAddressConstantExpression(ASE->getBase()) ||
836 CheckArithmeticConstantExpression(ASE->getIdx());
837 }
838 case Expr::StringLiteralClass:
Chris Lattner6307f192008-08-10 01:53:14 +0000839 case Expr::PredefinedExprClass:
Eli Friedmand5a55bd2008-05-20 13:48:25 +0000840 return false;
841 case Expr::UnaryOperatorClass: {
842 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
843
844 // C99 6.6p9
845 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman86346ed2008-05-21 03:39:11 +0000846 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmand5a55bd2008-05-20 13:48:25 +0000847
848 Diag(Init->getExprLoc(),
849 diag::err_init_element_not_constant, Init->getSourceRange());
850 return true;
851 }
852 }
853}
854
855bool Sema::CheckAddressConstantExpression(const Expr* Init) {
856 switch (Init->getStmtClass()) {
857 default:
858 Diag(Init->getExprLoc(),
859 diag::err_init_element_not_constant, Init->getSourceRange());
860 return true;
861 case Expr::ParenExprClass: {
862 const ParenExpr* PE = cast<ParenExpr>(Init);
863 return CheckAddressConstantExpression(PE->getSubExpr());
864 }
865 case Expr::StringLiteralClass:
866 case Expr::ObjCStringLiteralClass:
867 return false;
868 case Expr::CallExprClass: {
869 const CallExpr *CE = cast<CallExpr>(Init);
870 if (CE->isBuiltinConstantExpr())
871 return false;
872 Diag(Init->getExprLoc(),
873 diag::err_init_element_not_constant, Init->getSourceRange());
874 return true;
875 }
876 case Expr::UnaryOperatorClass: {
877 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
878
879 // C99 6.6p9
880 if (Exp->getOpcode() == UnaryOperator::AddrOf)
881 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
882
883 if (Exp->getOpcode() == UnaryOperator::Extension)
884 return CheckAddressConstantExpression(Exp->getSubExpr());
885
886 Diag(Init->getExprLoc(),
887 diag::err_init_element_not_constant, Init->getSourceRange());
888 return true;
889 }
890 case Expr::BinaryOperatorClass: {
891 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
892 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
893
894 Expr *PExp = Exp->getLHS();
895 Expr *IExp = Exp->getRHS();
896 if (IExp->getType()->isPointerType())
897 std::swap(PExp, IExp);
898
899 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
900 return CheckAddressConstantExpression(PExp) ||
901 CheckArithmeticConstantExpression(IExp);
902 }
Eli Friedman0a2ba3f2008-08-25 20:46:57 +0000903 case Expr::ImplicitCastExprClass:
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +0000904 case Expr::ExplicitCastExprClass: {
Eli Friedmand5a55bd2008-05-20 13:48:25 +0000905 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman0a2ba3f2008-08-25 20:46:57 +0000906 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
907 // Check for implicit promotion
908 if (SubExpr->getType()->isFunctionType() ||
909 SubExpr->getType()->isArrayType())
910 return CheckAddressConstantExpressionLValue(SubExpr);
911 }
Eli Friedmand5a55bd2008-05-20 13:48:25 +0000912
913 // Check for pointer->pointer cast
914 if (SubExpr->getType()->isPointerType())
915 return CheckAddressConstantExpression(SubExpr);
916
Eli Friedman0a2ba3f2008-08-25 20:46:57 +0000917 if (SubExpr->getType()->isIntegralType()) {
918 // Check for the special-case of a pointer->int->pointer cast;
919 // this isn't standard, but some code requires it. See
920 // PR2720 for an example.
921 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
922 if (SubCast->getSubExpr()->getType()->isPointerType()) {
923 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
924 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
925 if (IntWidth >= PointerWidth) {
926 return CheckAddressConstantExpression(SubCast->getSubExpr());
927 }
928 }
929 }
930 }
931 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmand5a55bd2008-05-20 13:48:25 +0000932 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman0a2ba3f2008-08-25 20:46:57 +0000933 }
Eli Friedmand5a55bd2008-05-20 13:48:25 +0000934
935 Diag(Init->getExprLoc(),
936 diag::err_init_element_not_constant, Init->getSourceRange());
937 return true;
938 }
939 case Expr::ConditionalOperatorClass: {
940 // FIXME: Should we pedwarn here?
941 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
942 if (!Exp->getCond()->getType()->isArithmeticType()) {
943 Diag(Init->getExprLoc(),
944 diag::err_init_element_not_constant, Init->getSourceRange());
945 return true;
946 }
947 if (CheckArithmeticConstantExpression(Exp->getCond()))
948 return true;
949 if (Exp->getLHS() &&
950 CheckAddressConstantExpression(Exp->getLHS()))
951 return true;
952 return CheckAddressConstantExpression(Exp->getRHS());
953 }
954 case Expr::AddrLabelExprClass:
955 return false;
956 }
957}
958
Eli Friedmane6e0f232008-06-09 05:05:07 +0000959static const Expr* FindExpressionBaseAddress(const Expr* E);
960
961static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
962 switch (E->getStmtClass()) {
963 default:
964 return E;
965 case Expr::ParenExprClass: {
966 const ParenExpr* PE = cast<ParenExpr>(E);
967 return FindExpressionBaseAddressLValue(PE->getSubExpr());
968 }
969 case Expr::MemberExprClass: {
970 const MemberExpr *M = cast<MemberExpr>(E);
971 if (M->isArrow())
972 return FindExpressionBaseAddress(M->getBase());
973 return FindExpressionBaseAddressLValue(M->getBase());
974 }
975 case Expr::ArraySubscriptExprClass: {
976 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
977 return FindExpressionBaseAddress(ASE->getBase());
978 }
979 case Expr::UnaryOperatorClass: {
980 const UnaryOperator *Exp = cast<UnaryOperator>(E);
981
982 if (Exp->getOpcode() == UnaryOperator::Deref)
983 return FindExpressionBaseAddress(Exp->getSubExpr());
984
985 return E;
986 }
987 }
988}
989
990static const Expr* FindExpressionBaseAddress(const Expr* E) {
991 switch (E->getStmtClass()) {
992 default:
993 return E;
994 case Expr::ParenExprClass: {
995 const ParenExpr* PE = cast<ParenExpr>(E);
996 return FindExpressionBaseAddress(PE->getSubExpr());
997 }
998 case Expr::UnaryOperatorClass: {
999 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1000
1001 // C99 6.6p9
1002 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1003 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1004
1005 if (Exp->getOpcode() == UnaryOperator::Extension)
1006 return FindExpressionBaseAddress(Exp->getSubExpr());
1007
1008 return E;
1009 }
1010 case Expr::BinaryOperatorClass: {
1011 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1012
1013 Expr *PExp = Exp->getLHS();
1014 Expr *IExp = Exp->getRHS();
1015 if (IExp->getType()->isPointerType())
1016 std::swap(PExp, IExp);
1017
1018 return FindExpressionBaseAddress(PExp);
1019 }
1020 case Expr::ImplicitCastExprClass: {
1021 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1022
1023 // Check for implicit promotion
1024 if (SubExpr->getType()->isFunctionType() ||
1025 SubExpr->getType()->isArrayType())
1026 return FindExpressionBaseAddressLValue(SubExpr);
1027
1028 // Check for pointer->pointer cast
1029 if (SubExpr->getType()->isPointerType())
1030 return FindExpressionBaseAddress(SubExpr);
1031
1032 // We assume that we have an arithmetic expression here;
1033 // if we don't, we'll figure it out later
1034 return 0;
1035 }
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00001036 case Expr::ExplicitCastExprClass: {
Eli Friedmane6e0f232008-06-09 05:05:07 +00001037 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1038
1039 // Check for pointer->pointer cast
1040 if (SubExpr->getType()->isPointerType())
1041 return FindExpressionBaseAddress(SubExpr);
1042
1043 // We assume that we have an arithmetic expression here;
1044 // if we don't, we'll figure it out later
1045 return 0;
1046 }
1047 }
1048}
1049
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001050bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1051 switch (Init->getStmtClass()) {
1052 default:
1053 Diag(Init->getExprLoc(),
1054 diag::err_init_element_not_constant, Init->getSourceRange());
1055 return true;
1056 case Expr::ParenExprClass: {
1057 const ParenExpr* PE = cast<ParenExpr>(Init);
1058 return CheckArithmeticConstantExpression(PE->getSubExpr());
1059 }
1060 case Expr::FloatingLiteralClass:
1061 case Expr::IntegerLiteralClass:
1062 case Expr::CharacterLiteralClass:
1063 case Expr::ImaginaryLiteralClass:
1064 case Expr::TypesCompatibleExprClass:
1065 case Expr::CXXBoolLiteralExprClass:
1066 return false;
1067 case Expr::CallExprClass: {
1068 const CallExpr *CE = cast<CallExpr>(Init);
1069 if (CE->isBuiltinConstantExpr())
1070 return false;
1071 Diag(Init->getExprLoc(),
1072 diag::err_init_element_not_constant, Init->getSourceRange());
1073 return true;
1074 }
1075 case Expr::DeclRefExprClass: {
1076 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1077 if (isa<EnumConstantDecl>(D))
1078 return false;
Nuno Lopesfeac6372008-09-01 14:47:06 +00001079
1080 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1081 QualType Ty = VD->getType();
1082 if (Ty->isPointerLikeType() || Ty->isArrayType())
1083 return false;
1084 }
1085
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001086 Diag(Init->getExprLoc(),
1087 diag::err_init_element_not_constant, Init->getSourceRange());
1088 return true;
1089 }
1090 case Expr::CompoundLiteralExprClass:
1091 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1092 // but vectors are allowed to be magic.
1093 if (Init->getType()->isVectorType())
1094 return false;
1095 Diag(Init->getExprLoc(),
1096 diag::err_init_element_not_constant, Init->getSourceRange());
1097 return true;
1098 case Expr::UnaryOperatorClass: {
1099 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1100
1101 switch (Exp->getOpcode()) {
1102 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1103 // See C99 6.6p3.
1104 default:
1105 Diag(Init->getExprLoc(),
1106 diag::err_init_element_not_constant, Init->getSourceRange());
1107 return true;
Nuno Lopesfeac6372008-09-01 14:47:06 +00001108 case UnaryOperator::AddrOf:
1109 return false;
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001110 case UnaryOperator::SizeOf:
1111 case UnaryOperator::AlignOf:
1112 case UnaryOperator::OffsetOf:
1113 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1114 // See C99 6.5.3.4p2 and 6.6p3.
1115 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1116 return false;
1117 Diag(Init->getExprLoc(),
1118 diag::err_init_element_not_constant, Init->getSourceRange());
1119 return true;
1120 case UnaryOperator::Extension:
1121 case UnaryOperator::LNot:
1122 case UnaryOperator::Plus:
1123 case UnaryOperator::Minus:
1124 case UnaryOperator::Not:
1125 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1126 }
1127 }
1128 case Expr::SizeOfAlignOfTypeExprClass: {
1129 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1130 // Special check for void types, which are allowed as an extension
1131 if (Exp->getArgumentType()->isVoidType())
1132 return false;
1133 // alignof always evaluates to a constant.
1134 // FIXME: is sizeof(int[3.0]) a constant expression?
1135 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1136 Diag(Init->getExprLoc(),
1137 diag::err_init_element_not_constant, Init->getSourceRange());
1138 return true;
1139 }
1140 return false;
1141 }
1142 case Expr::BinaryOperatorClass: {
1143 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1144
1145 if (Exp->getLHS()->getType()->isArithmeticType() &&
1146 Exp->getRHS()->getType()->isArithmeticType()) {
1147 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1148 CheckArithmeticConstantExpression(Exp->getRHS());
1149 }
1150
Eli Friedmane6e0f232008-06-09 05:05:07 +00001151 if (Exp->getLHS()->getType()->isPointerType() &&
1152 Exp->getRHS()->getType()->isPointerType()) {
1153 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1154 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1155
1156 // Only allow a null (constant integer) base; we could
1157 // allow some additional cases if necessary, but this
1158 // is sufficient to cover offsetof-like constructs.
1159 if (!LHSBase && !RHSBase) {
1160 return CheckAddressConstantExpression(Exp->getLHS()) ||
1161 CheckAddressConstantExpression(Exp->getRHS());
1162 }
1163 }
1164
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001165 Diag(Init->getExprLoc(),
1166 diag::err_init_element_not_constant, Init->getSourceRange());
1167 return true;
1168 }
1169 case Expr::ImplicitCastExprClass:
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00001170 case Expr::ExplicitCastExprClass: {
1171 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Nuno Lopesfeac6372008-09-01 14:47:06 +00001172 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001173 }
1174 case Expr::ConditionalOperatorClass: {
1175 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1176 if (CheckArithmeticConstantExpression(Exp->getCond()))
1177 return true;
1178 if (Exp->getLHS() &&
1179 CheckArithmeticConstantExpression(Exp->getLHS()))
1180 return true;
1181 return CheckArithmeticConstantExpression(Exp->getRHS());
1182 }
1183 }
1184}
1185
1186bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopes7bfa1802008-07-07 16:46:50 +00001187 Init = Init->IgnoreParens();
1188
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001189 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1190 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1191 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1192
Nuno Lopes7bfa1802008-07-07 16:46:50 +00001193 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1194 return CheckForConstantInitializer(e->getInitializer(), DclT);
1195
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001196 if (Init->getType()->isReferenceType()) {
1197 // FIXME: Work out how the heck reference types work
1198 return false;
1199#if 0
1200 // A reference is constant if the address of the expression
1201 // is constant
1202 // We look through initlists here to simplify
1203 // CheckAddressConstantExpressionLValue.
1204 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1205 assert(Exp->getNumInits() > 0 &&
1206 "Refernce initializer cannot be empty");
1207 Init = Exp->getInit(0);
1208 }
1209 return CheckAddressConstantExpressionLValue(Init);
1210#endif
1211 }
1212
1213 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1214 unsigned numInits = Exp->getNumInits();
1215 for (unsigned i = 0; i < numInits; i++) {
1216 // FIXME: Need to get the type of the declaration for C++,
1217 // because it could be a reference?
1218 if (CheckForConstantInitializer(Exp->getInit(i),
1219 Exp->getInit(i)->getType()))
1220 return true;
1221 }
1222 return false;
1223 }
1224
1225 if (Init->isNullPointerConstant(Context))
1226 return false;
1227 if (Init->getType()->isArithmeticType()) {
Chris Lattner574dee62008-07-26 22:17:49 +00001228 QualType InitTy = Context.getCanonicalType(Init->getType())
1229 .getUnqualifiedType();
Eli Friedman66572af2008-05-30 18:14:48 +00001230 if (InitTy == Context.BoolTy) {
1231 // Special handling for pointers implicitly cast to bool;
1232 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1233 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1234 Expr* SubE = ICE->getSubExpr();
1235 if (SubE->getType()->isPointerType() ||
1236 SubE->getType()->isArrayType() ||
1237 SubE->getType()->isFunctionType()) {
1238 return CheckAddressConstantExpression(Init);
1239 }
1240 }
1241 } else if (InitTy->isIntegralType()) {
1242 Expr* SubE = 0;
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00001243 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman66572af2008-05-30 18:14:48 +00001244 SubE = CE->getSubExpr();
1245 // Special check for pointer cast to int; we allow as an extension
1246 // an address constant cast to an integer if the integer
1247 // is of an appropriate width (this sort of code is apparently used
1248 // in some places).
1249 // FIXME: Add pedwarn?
1250 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1251 if (SubE && (SubE->getType()->isPointerType() ||
1252 SubE->getType()->isArrayType() ||
1253 SubE->getType()->isFunctionType())) {
1254 unsigned IntWidth = Context.getTypeSize(Init->getType());
1255 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1256 if (IntWidth >= PointerWidth)
1257 return CheckAddressConstantExpression(Init);
1258 }
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001259 }
1260
1261 return CheckArithmeticConstantExpression(Init);
1262 }
1263
1264 if (Init->getType()->isPointerType())
1265 return CheckAddressConstantExpression(Init);
1266
Eli Friedman66572af2008-05-30 18:14:48 +00001267 // An array type at the top level that isn't an init-list must
1268 // be a string literal
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001269 if (Init->getType()->isArrayType())
1270 return false;
1271
1272 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1273 Init->getSourceRange());
1274 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00001275}
1276
Steve Naroff61091402007-09-12 14:07:44 +00001277void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff437b4d82007-09-12 20:13:48 +00001278 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff61091402007-09-12 14:07:44 +00001279 Expr *Init = static_cast<Expr *>(init);
Chris Lattner8beb9de2007-10-19 20:10:30 +00001280 assert(Init && "missing initializer");
Steve Naroff61091402007-09-12 14:07:44 +00001281
Chris Lattner8beb9de2007-10-19 20:10:30 +00001282 // If there is no declaration, there was an error parsing it. Just ignore
1283 // the initializer.
1284 if (RealDecl == 0) {
1285 delete Init;
1286 return;
1287 }
Steve Naroff61091402007-09-12 14:07:44 +00001288
Steve Naroff437b4d82007-09-12 20:13:48 +00001289 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1290 if (!VDecl) {
Steve Naroff9def2b12007-09-13 21:41:19 +00001291 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1292 diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00001293 RealDecl->setInvalidDecl();
1294 return;
1295 }
Steve Naroff61091402007-09-12 14:07:44 +00001296 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00001297 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00001298 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff08899ff2008-04-15 22:42:06 +00001299 if (VDecl->isBlockVarDecl()) {
1300 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff61091402007-09-12 14:07:44 +00001301 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff437b4d82007-09-12 20:13:48 +00001302 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff08899ff2008-04-15 22:42:06 +00001303 VDecl->setInvalidDecl();
1304 } else if (!VDecl->isInvalidDecl()) {
Steve Naroff78c6cdf2008-01-25 00:51:06 +00001305 if (CheckInitializerTypes(Init, DclT))
Steve Naroff08899ff2008-04-15 22:42:06 +00001306 VDecl->setInvalidDecl();
Anders Carlsson41e08812008-08-22 05:00:02 +00001307
1308 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1309 if (!getLangOptions().CPlusPlus) {
1310 if (SC == VarDecl::Static) // C99 6.7.8p4.
1311 CheckForConstantInitializer(Init, DclT);
1312 }
Steve Naroff61091402007-09-12 14:07:44 +00001313 }
Steve Naroff08899ff2008-04-15 22:42:06 +00001314 } else if (VDecl->isFileVarDecl()) {
1315 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff437b4d82007-09-12 20:13:48 +00001316 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff08899ff2008-04-15 22:42:06 +00001317 if (!VDecl->isInvalidDecl())
Steve Naroff78c6cdf2008-01-25 00:51:06 +00001318 if (CheckInitializerTypes(Init, DclT))
Steve Naroff08899ff2008-04-15 22:42:06 +00001319 VDecl->setInvalidDecl();
Steve Naroff98f72032008-01-10 22:15:12 +00001320
Anders Carlsson41e08812008-08-22 05:00:02 +00001321 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1322 if (!getLangOptions().CPlusPlus) {
1323 // C99 6.7.8p4. All file scoped initializers need to be constant.
1324 CheckForConstantInitializer(Init, DclT);
1325 }
Steve Naroff61091402007-09-12 14:07:44 +00001326 }
1327 // If the type changed, it means we had an incomplete type that was
1328 // completed by the initializer. For example:
1329 // int ary[] = { 1, 3, 5 };
1330 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00001331 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff437b4d82007-09-12 20:13:48 +00001332 VDecl->setType(DclT);
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00001333 Init->setType(DclT);
1334 }
Steve Naroff61091402007-09-12 14:07:44 +00001335
1336 // Attach the initializer to the decl.
Steve Naroff437b4d82007-09-12 20:13:48 +00001337 VDecl->setInit(Init);
Steve Naroff61091402007-09-12 14:07:44 +00001338 return;
1339}
1340
Chris Lattner776fac82007-06-09 00:53:06 +00001341/// The declarators are chained together backwards, reverse the list.
1342Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1343 // Often we have single declarators, handle them quickly.
Steve Naroffa23cc792007-09-13 23:52:58 +00001344 Decl *GroupDecl = static_cast<Decl*>(group);
1345 if (GroupDecl == 0)
Steve Naroff61091402007-09-12 14:07:44 +00001346 return 0;
Steve Naroffa23cc792007-09-13 23:52:58 +00001347
1348 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1349 ScopedDecl *NewGroup = 0;
Steve Naroff61091402007-09-12 14:07:44 +00001350 if (Group->getNextDeclarator() == 0)
Chris Lattner776fac82007-06-09 00:53:06 +00001351 NewGroup = Group;
Steve Naroff61091402007-09-12 14:07:44 +00001352 else { // reverse the list.
1353 while (Group) {
Steve Naroffa23cc792007-09-13 23:52:58 +00001354 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff61091402007-09-12 14:07:44 +00001355 Group->setNextDeclarator(NewGroup);
1356 NewGroup = Group;
1357 Group = Next;
1358 }
1359 }
1360 // Perform semantic analysis that depends on having fully processed both
1361 // the declarator and initializer.
Steve Naroffa23cc792007-09-13 23:52:58 +00001362 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff61091402007-09-12 14:07:44 +00001363 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1364 if (!IDecl)
1365 continue;
Steve Naroff61091402007-09-12 14:07:44 +00001366 QualType T = IDecl->getType();
1367
1368 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1369 // static storage duration, it shall not have a variable length array.
Steve Naroff08899ff2008-04-15 22:42:06 +00001370 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1371 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattner7adf0762008-08-04 07:31:14 +00001372 if (T->isVariableArrayType()) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001373 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1374 IDecl->setInvalidDecl();
Steve Naroff61091402007-09-12 14:07:44 +00001375 }
1376 }
1377 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1378 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff08899ff2008-04-15 22:42:06 +00001379 if (IDecl->isBlockVarDecl() &&
1380 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner81cb9e82008-04-02 01:05:10 +00001381 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner310369f2007-12-02 07:50:03 +00001382 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1383 T.getAsString());
Steve Naroff61091402007-09-12 14:07:44 +00001384 IDecl->setInvalidDecl();
1385 }
1386 }
1387 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1388 // object that has file scope without an initializer, and without a
1389 // storage-class specifier or with the storage-class specifier "static",
1390 // constitutes a tentative definition. Note: A tentative definition with
1391 // external linkage is valid (C99 6.2.2p5).
Steve Naroff5bb8f222008-08-08 17:50:35 +00001392 if (isTentativeDefinition(IDecl)) {
Eli Friedman9e805b22008-02-15 12:53:51 +00001393 if (T->isIncompleteArrayType()) {
Steve Naroffacb6fa62008-01-18 20:40:52 +00001394 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1395 // array to be completed. Don't issue a diagnostic.
Chris Lattner81cb9e82008-04-02 01:05:10 +00001396 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroffacb6fa62008-01-18 20:40:52 +00001397 // C99 6.9.2p3: If the declaration of an identifier for an object is
1398 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1399 // declared type shall not be an incomplete type.
Chris Lattner310369f2007-12-02 07:50:03 +00001400 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1401 T.getAsString());
Steve Naroff61091402007-09-12 14:07:44 +00001402 IDecl->setInvalidDecl();
1403 }
1404 }
Steve Naroff5bb8f222008-08-08 17:50:35 +00001405 if (IDecl->isFileVarDecl())
1406 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner776fac82007-06-09 00:53:06 +00001407 }
1408 return NewGroup;
1409}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00001410
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001411/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1412/// to introduce parameters into function prototype scope.
1413Sema::DeclTy *
1414Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00001415 const DeclSpec &DS = D.getDeclSpec();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001416
1417 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1418 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1419 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1420 Diag(DS.getStorageClassSpecLoc(),
1421 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00001422 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001423 }
1424 if (DS.isThreadSpecified()) {
1425 Diag(DS.getThreadSpecLoc(),
1426 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00001427 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001428 }
1429
Douglas Gregorcaa8ace2008-05-07 04:49:29 +00001430 // Check that there are no default arguments inside the type of this
1431 // parameter (C++ only).
1432 if (getLangOptions().CPlusPlus)
1433 CheckExtraCXXDefaultArguments(D);
1434
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001435 // In this context, we *do not* check D.getInvalidType(). If the declarator
1436 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1437 // though it will not reflect the user specified type.
1438 QualType parmDeclType = GetTypeForDeclarator(D, S);
1439
1440 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1441
Chris Lattnerc284e9b2007-01-23 05:14:32 +00001442 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1443 // Can this happen for params? We already checked that they don't conflict
1444 // among each other. Here they can only shadow globals, which is ok.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001445 IdentifierInfo *II = D.getIdentifier();
1446 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1447 if (S->isDeclScope(PrevDecl)) {
1448 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1449 dyn_cast<NamedDecl>(PrevDecl)->getName());
1450
1451 // Recover by removing the name
1452 II = 0;
1453 D.SetIdentifier(0, D.getIdentifierLoc());
1454 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001455 }
Steve Naroff773df5c2007-08-07 22:44:21 +00001456
1457 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1458 // Doing the promotion here has a win and a loss. The win is the type for
1459 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1460 // code generator). The loss is the orginal type isn't preserved. For example:
1461 //
1462 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1463 // int blockvardecl[5];
1464 // sizeof(parmvardecl); // size == 4
1465 // sizeof(blockvardecl); // size == 20
1466 // }
1467 //
1468 // For expressions, all implicit conversions are captured using the
1469 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1470 //
1471 // FIXME: If a source translation tool needs to see the original type, then
1472 // we need to consider storing both types (in ParmVarDecl)...
1473 //
Chris Lattnera21ad802008-04-02 05:18:44 +00001474 if (parmDeclType->isArrayType()) {
Chris Lattner4f203512008-01-02 22:50:48 +00001475 // int x[restrict 4] -> int *restrict
Chris Lattnera21ad802008-04-02 05:18:44 +00001476 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner4f203512008-01-02 22:50:48 +00001477 } else if (parmDeclType->isFunctionType())
Steve Naroff773df5c2007-08-07 22:44:21 +00001478 parmDeclType = Context.getPointerType(parmDeclType);
1479
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001480 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1481 D.getIdentifierLoc(), II,
1482 parmDeclType, VarDecl::None,
1483 0, 0);
Anders Carlsson1a841062008-02-15 07:04:12 +00001484
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001485 if (D.getInvalidType())
Steve Naroffcf871f52007-08-28 18:45:29 +00001486 New->setInvalidDecl();
1487
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001488 if (II)
1489 PushOnScopeChains(New, S);
Nate Begemand8c41562008-02-17 21:20:31 +00001490
Chris Lattner2727d1b2008-06-29 00:02:00 +00001491 ProcessDeclAttributes(New, D);
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001492 return New;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001493
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001494}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00001495
Chris Lattnera55a2cc2007-10-09 17:14:05 +00001496Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001497 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001498 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1499 "Not a function declarator!");
1500 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001501
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001502 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1503 // for a K&R function.
1504 if (!FTI.hasPrototype) {
1505 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001506 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner843c5922007-06-10 23:40:34 +00001507 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001508 FTI.ArgInfo[i].Ident->getName());
1509 // Implicitly declare the argument as type 'int' for lack of a better
1510 // type.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001511 DeclSpec DS;
1512 const char* PrevSpec; // unused
1513 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1514 PrevSpec);
1515 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1516 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1517 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001518 }
1519 }
Chris Lattner2114d5e2006-12-04 07:40:24 +00001520 } else {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001521 // FIXME: Diagnose arguments without names in C.
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001522 }
1523
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001524 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00001525
1526 // See if this is a redefinition.
Steve Naroff257520b2008-04-01 23:04:06 +00001527 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroff2fc93f52008-04-02 14:35:35 +00001528 GlobalScope);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001529 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1530 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1531 const FunctionDecl *Definition;
1532 if (FD->getBody(Definition)) {
1533 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1534 D.getIdentifier()->getName());
1535 Diag(Definition->getLocation(), diag::err_previous_definition);
1536 }
Steve Naroff012484d2008-01-14 20:51:29 +00001537 }
1538 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001539
1540 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar1ff1d1f2008-08-05 16:28:08 +00001541 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001542}
1543
1544Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1545 Decl *decl = static_cast<Decl*>(D);
Chris Lattner27055192008-02-16 01:20:36 +00001546 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattner0a5ff0d2008-04-06 04:47:34 +00001547 PushDeclContext(FD);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001548
1549 // Check the validity of our function parameters
1550 CheckParmsForFunctionDef(FD);
1551
1552 // Introduce our parameters into the function scope
1553 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1554 ParmVarDecl *Param = FD->getParamDecl(p);
1555 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001556 if (Param->getIdentifier())
1557 PushOnScopeChains(Param, FnBodyScope);
Chris Lattnerf61c8a82007-01-21 19:04:43 +00001558 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001559
Chris Lattnere168f762006-11-10 05:29:30 +00001560 return FD;
1561}
1562
Steve Naroffb313fc32007-11-11 23:20:51 +00001563Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1564 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff542cd5d2008-07-25 17:57:26 +00001565 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffb313fc32007-11-11 23:20:51 +00001566 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001567 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00001568 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffb313fc32007-11-11 23:20:51 +00001569 MD->setBody((Stmt*)Body);
Steve Naroff542cd5d2008-07-25 17:57:26 +00001570 } else
1571 return 0;
Chris Lattner0a5ff0d2008-04-06 04:47:34 +00001572 PopDeclContext();
Chris Lattnere2473062007-05-28 06:28:18 +00001573 // Verify and clean out per-function state.
1574
1575 // Check goto/label use.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001576 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1577 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
Chris Lattnere2473062007-05-28 06:28:18 +00001578 // Verify that we have no forward references left. If so, there was a goto
1579 // or address of a label taken, but no definition of it. Label fwd
1580 // definitions are indicated with a null substmt.
1581 if (I->second->getSubStmt() == 0) {
1582 LabelStmt *L = I->second;
1583 // Emit error.
Chris Lattnereefa10e2007-05-28 06:56:27 +00001584 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
Chris Lattnere2473062007-05-28 06:28:18 +00001585
1586 // At this point, we have gotos that use the bogus label. Stitch it into
1587 // the function body so that they aren't leaked and that the AST is well
1588 // formed.
Chris Lattner3efff542008-01-25 00:01:10 +00001589 if (Body) {
1590 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1591 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1592 } else {
1593 // The whole function wasn't parsed correctly, just delete this.
1594 delete L;
1595 }
Chris Lattnere2473062007-05-28 06:28:18 +00001596 }
1597 }
1598 LabelMap.clear();
1599
Steve Naroffb313fc32007-11-11 23:20:51 +00001600 return D;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00001601}
1602
Chris Lattnerac18be92006-11-20 06:49:47 +00001603/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1604/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff2f742082007-09-16 16:16:00 +00001605ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1606 IdentifierInfo &II, Scope *S) {
Chris Lattner00e26072008-05-05 21:18:06 +00001607 // Extension in C99. Legal in C90, but warn about it.
1608 if (getLangOptions().C99)
Chris Lattnerac18be92006-11-20 06:49:47 +00001609 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner00e26072008-05-05 21:18:06 +00001610 else
Chris Lattnerac18be92006-11-20 06:49:47 +00001611 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1612
1613 // FIXME: handle stuff like:
1614 // void foo() { extern float X(); }
1615 // void bar() { X(); } <-- implicit decl for X in another scope.
1616
1617 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00001618 const char *Dummy;
Chris Lattnerac18be92006-11-20 06:49:47 +00001619 DeclSpec DS;
Chris Lattnerb20e8942006-11-28 05:30:29 +00001620 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001621 Error = Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00001622 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +00001623 Declarator D(DS, Declarator::BlockContext);
Chris Lattnercbc426d2006-12-02 06:43:02 +00001624 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
Chris Lattnerac18be92006-11-20 06:49:47 +00001625 D.SetIdentifier(&II, Loc);
1626
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00001627 // Insert this function into translation-unit scope.
1628
1629 DeclContext *PrevDC = CurContext;
1630 CurContext = Context.getTranslationUnitDecl();
1631
Steve Naroff3913ea42008-04-04 14:32:09 +00001632 FunctionDecl *FD =
Daniel Dunbar1ff1d1f2008-08-05 16:28:08 +00001633 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff3913ea42008-04-04 14:32:09 +00001634 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00001635
1636 CurContext = PrevDC;
1637
Steve Naroff3913ea42008-04-04 14:32:09 +00001638 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +00001639}
1640
Chris Lattner302b4be2006-11-19 02:31:38 +00001641
Chris Lattner07b201d2007-11-14 06:34:38 +00001642TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroffa23cc792007-09-13 23:52:58 +00001643 ScopedDecl *LastDeclarator) {
Chris Lattner776fac82007-06-09 00:53:06 +00001644 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00001645 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001646
Chris Lattner18b19622007-01-22 07:39:13 +00001647 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +00001648 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1649 D.getIdentifierLoc(),
Chris Lattnera7b32872008-03-15 06:12:44 +00001650 D.getIdentifier(),
Chris Lattner96c460d2008-03-15 21:32:50 +00001651 T, LastDeclarator);
Steve Narofff93b6722007-08-28 20:14:24 +00001652 if (D.getInvalidType())
1653 NewTD->setInvalidDecl();
1654 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00001655}
1656
Steve Naroff30d242c2007-09-15 18:49:24 +00001657/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00001658/// former case, Name will be non-null. In the later case, Name will be null.
1659/// TagType indicates what kind of tag this is. TK indicates whether this is a
1660/// reference/declaration/definition of a tag.
Steve Naroff30d242c2007-09-15 18:49:24 +00001661Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001662 SourceLocation KWLoc, IdentifierInfo *Name,
Steve Naroffb3096442007-06-09 03:47:53 +00001663 SourceLocation NameLoc, AttributeList *Attr) {
Chris Lattner8799cf22007-01-23 01:57:16 +00001664 // If this is a use of an existing tag, it must have a name.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001665 assert((Name != 0 || TK == TK_Definition) &&
1666 "Nameless record must be a definition!");
Chris Lattner8799cf22007-01-23 01:57:16 +00001667
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001668 TagDecl::TagKind Kind;
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001669 switch (TagType) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001670 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001671 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1672 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1673 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1674 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001675 }
Chris Lattner7e783a12007-01-23 02:05:42 +00001676
Chris Lattner18b19622007-01-22 07:39:13 +00001677 // If this is a named struct, check to see if there was a previous forward
1678 // declaration or definition.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001679 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1680 if (ScopedDecl *PrevDecl =
1681 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Chris Lattner8799cf22007-01-23 01:57:16 +00001682
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001683 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1684 "unexpected Decl type");
1685 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00001686 // If this is a use of a previous tag, or if the tag is already declared
1687 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001688 // rementions the tag), reuse the decl.
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001689 if (TK == TK_Reference ||
1690 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00001691 // Make sure that this wasn't declared as an enum and now used as a
1692 // struct or something similar.
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001693 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001694 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1695 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner9ff58d72008-07-03 03:30:58 +00001696 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001697 Name = 0;
Chris Lattner9ff58d72008-07-03 03:30:58 +00001698 PrevDecl = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001699 } else {
Chris Lattner9ff58d72008-07-03 03:30:58 +00001700 // If this is a use or a forward declaration, we're good.
1701 if (TK != TK_Definition)
1702 return PrevDecl;
1703
1704 // Diagnose attempts to redefine a tag.
1705 if (PrevTagDecl->isDefinition()) {
1706 Diag(NameLoc, diag::err_redefinition, Name->getName());
1707 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1708 // If this is a redefinition, recover by making this struct be
1709 // anonymous, which will make any later references get the previous
1710 // definition.
1711 Name = 0;
1712 } else {
1713 // Okay, this is definition of a previously declared or referenced
1714 // tag. Move the location of the decl to be the definition site.
1715 PrevDecl->setLocation(NameLoc);
1716 return PrevDecl;
1717 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001718 }
Chris Lattner7b9ace62007-01-23 20:11:08 +00001719 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001720 // If we get here, this is a definition of a new struct type in a nested
1721 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1722 // type.
1723 } else {
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00001724 // PrevDecl is a namespace.
1725 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1726 // The tag name clashes with a namespace name, issue an error and recover
1727 // by making this tag be anonymous.
1728 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1729 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1730 Name = 0;
1731 }
Chris Lattner8799cf22007-01-23 01:57:16 +00001732 }
Chris Lattner18b19622007-01-22 07:39:13 +00001733 }
1734
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001735 // If there is an identifier, use the location of the identifier as the
1736 // location of the decl, otherwise use the location of the struct/union
1737 // keyword.
1738 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1739
Chris Lattner18b19622007-01-22 07:39:13 +00001740 // Otherwise, if this is the first time we've seen this tag, create the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001741 TagDecl *New;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001742 if (Kind == TagDecl::TK_enum) {
Chris Lattner776fac82007-06-09 00:53:06 +00001743 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1744 // enum X { A, B, C } D; D should chain to X.
Chris Lattnerc5ffed42008-04-04 06:12:32 +00001745 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Chris Lattner5f521502007-01-25 06:27:24 +00001746 // If this is an undefined enum, warn.
Chris Lattnerc1915e22007-01-25 07:29:02 +00001747 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001748 } else {
1749 // struct/union/class
1750
Chris Lattner776fac82007-06-09 00:53:06 +00001751 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1752 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001753 if (getLangOptions().CPlusPlus)
1754 // FIXME: Look for a way to use RecordDecl for simple structs.
1755 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1756 else
1757 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1758 }
Chris Lattner18b19622007-01-22 07:39:13 +00001759
1760 // If this has an identifier, add it to the scope stack.
1761 if (Name) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001762 // The scope passed in may not be a decl scope. Zip up the scope tree until
1763 // we find one that is.
1764 while ((S->getFlags() & Scope::DeclScope) == 0)
1765 S = S->getParent();
1766
1767 // Add it to the decl chain.
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001768 PushOnScopeChains(New, S);
Chris Lattner18b19622007-01-22 07:39:13 +00001769 }
Chris Lattner622c1932008-02-06 00:51:33 +00001770
Chris Lattnera5741542008-06-28 23:58:55 +00001771 if (Attr)
1772 ProcessDeclAttributeList(New, Attr);
Chris Lattner18b19622007-01-22 07:39:13 +00001773 return New;
1774}
Chris Lattner1300fb92007-01-23 23:42:53 +00001775
Chris Lattner535b8302008-06-21 19:39:06 +00001776/// Collect the instance variables declared in an Objective-C object. Used in
1777/// the creation of structures from objects using the @defs directive.
Ted Kremenek0e857202008-08-20 03:26:33 +00001778static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001779 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner535b8302008-06-21 19:39:06 +00001780 if (Class->getSuperClass())
Ted Kremenek0e857202008-08-20 03:26:33 +00001781 CollectIvars(Class->getSuperClass(), Ctx, ivars);
1782
1783 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
1784 for (ObjCInterfaceDecl::ivar_iterator I=Class->ivar_begin(), E=Class->ivar_end();
1785 I!=E; ++I) {
1786
1787 ObjCIvarDecl* ID = *I;
1788 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
1789 ID->getIdentifier(),
1790 ID->getType(),
1791 ID->getBitWidth()));
1792 }
Chris Lattner535b8302008-06-21 19:39:06 +00001793}
1794
1795/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1796/// instance variables of ClassName into Decls.
1797void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1798 IdentifierInfo *ClassName,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001799 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner535b8302008-06-21 19:39:06 +00001800 // Check that ClassName is a valid class
1801 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1802 if (!Class) {
1803 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1804 return;
1805 }
Chris Lattner535b8302008-06-21 19:39:06 +00001806 // Collect the instance variables
Ted Kremenek0e857202008-08-20 03:26:33 +00001807 CollectIvars(Class, Context, Decls);
Chris Lattner535b8302008-06-21 19:39:06 +00001808}
1809
Eli Friedman149614b2008-06-03 21:01:11 +00001810QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1811 // This method tries to turn a variable array into a constant
1812 // array even when the size isn't an ICE. This is necessary
1813 // for compatibility with code that depends on gcc's buggy
1814 // constant expression folding, like struct {char x[(int)(char*)2];}
1815 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlsson7a241ba2008-07-03 04:20:39 +00001816 APValue Result;
Eli Friedman149614b2008-06-03 21:01:11 +00001817 if (VLATy->getSizeExpr() &&
Chris Lattner2bd2e022008-07-11 19:19:21 +00001818 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
1819 llvm::APSInt &Res = Result.getInt();
1820 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1821 return Context.getConstantArrayType(VLATy->getElementType(),
1822 Res, ArrayType::Normal, 0);
Eli Friedman149614b2008-06-03 21:01:11 +00001823 }
1824 }
1825 return QualType();
1826}
1827
Steve Naroff30d242c2007-09-15 18:49:24 +00001828/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00001829/// to create a FieldDecl object for it.
Fariborz Jahaniande615832008-04-10 23:32:45 +00001830Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner1300fb92007-01-23 23:42:53 +00001831 SourceLocation DeclStart,
1832 Declarator &D, ExprTy *BitfieldWidth) {
1833 IdentifierInfo *II = D.getIdentifier();
1834 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner1300fb92007-01-23 23:42:53 +00001835 SourceLocation Loc = DeclStart;
1836 if (II) Loc = D.getIdentifierLoc();
1837
Chris Lattner62d2e662007-01-28 00:21:37 +00001838 // FIXME: Unnamed fields can be handled in various different ways, for
1839 // example, unnamed unions inject all members into the struct namespace!
1840
1841
Chris Lattner1300fb92007-01-23 23:42:53 +00001842 if (BitWidth) {
1843 // TODO: Validate.
Steve Narofff84d11f2007-05-23 21:48:04 +00001844 //printf("WARNING: BITFIELDS IGNORED!\n");
Chris Lattner1300fb92007-01-23 23:42:53 +00001845
1846 // 6.7.2.1p3
1847 // 6.7.2.1p4
1848
1849 } else {
1850 // Not a bitfield.
1851
1852 // validate II.
1853
1854 }
1855
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001856 QualType T = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +00001857 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1858 bool InvalidDecl = false;
Steve Naroff096dd942007-08-31 17:20:07 +00001859
Steve Naroff8eeeb132007-05-08 21:09:37 +00001860 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1861 // than a variably modified type.
Eli Friedman9e805b22008-02-15 12:53:51 +00001862 if (T->isVariablyModifiedType()) {
Eli Friedman149614b2008-06-03 21:01:11 +00001863 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
1864 if (!FixedTy.isNull()) {
1865 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
1866 T = FixedTy;
1867 } else {
1868 // FIXME: This diagnostic needs work
1869 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1870 InvalidDecl = true;
1871 }
Steve Naroff8eeeb132007-05-08 21:09:37 +00001872 }
Chris Lattner776fac82007-06-09 00:53:06 +00001873 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001874 FieldDecl *NewFD;
1875
1876 if (getLangOptions().CPlusPlus) {
1877 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
1878 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
1879 Loc, II, T, BitWidth);
1880 if (II)
1881 PushOnScopeChains(NewFD, S);
1882 }
1883 else
1884 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001885
Chris Lattner2727d1b2008-06-29 00:02:00 +00001886 ProcessDeclAttributes(NewFD, D);
Anders Carlsson28e71082008-02-16 00:29:18 +00001887
Steve Narofff93b6722007-08-28 20:14:24 +00001888 if (D.getInvalidType() || InvalidDecl)
1889 NewFD->setInvalidDecl();
1890 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00001891}
1892
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001893/// TranslateIvarVisibility - Translate visibility from a token ID to an
1894/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001895static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001896TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00001897 switch (ivarVisibility) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001898 case tok::objc_private: return ObjCIvarDecl::Private;
1899 case tok::objc_public: return ObjCIvarDecl::Public;
1900 case tok::objc_protected: return ObjCIvarDecl::Protected;
1901 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001902 default: assert(false && "Unknown visitibility kind");
Steve Naroff2e688fd2007-09-14 23:09:53 +00001903 }
1904}
1905
Fariborz Jahanian96376742008-04-11 16:55:42 +00001906/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1907/// in order to create an IvarDecl object for it.
Fariborz Jahaniande615832008-04-10 23:32:45 +00001908Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian96376742008-04-11 16:55:42 +00001909 SourceLocation DeclStart,
1910 Declarator &D, ExprTy *BitfieldWidth,
1911 tok::ObjCKeywordKind Visibility) {
Fariborz Jahaniande615832008-04-10 23:32:45 +00001912 IdentifierInfo *II = D.getIdentifier();
1913 Expr *BitWidth = (Expr*)BitfieldWidth;
1914 SourceLocation Loc = DeclStart;
1915 if (II) Loc = D.getIdentifierLoc();
1916
1917 // FIXME: Unnamed fields can be handled in various different ways, for
1918 // example, unnamed unions inject all members into the struct namespace!
1919
1920
1921 if (BitWidth) {
1922 // TODO: Validate.
1923 //printf("WARNING: BITFIELDS IGNORED!\n");
1924
1925 // 6.7.2.1p3
1926 // 6.7.2.1p4
1927
1928 } else {
1929 // Not a bitfield.
1930
1931 // validate II.
1932
1933 }
1934
1935 QualType T = GetTypeForDeclarator(D, S);
1936 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1937 bool InvalidDecl = false;
1938
1939 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1940 // than a variably modified type.
1941 if (T->isVariablyModifiedType()) {
1942 // FIXME: This diagnostic needs work
1943 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1944 InvalidDecl = true;
1945 }
1946
Ted Kremenek73295fa2008-07-23 18:04:17 +00001947 // Get the visibility (access control) for this ivar.
1948 ObjCIvarDecl::AccessControl ac =
1949 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
1950 : ObjCIvarDecl::None;
1951
1952 // Construct the decl.
1953 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffde7d0f62008-07-16 18:22:22 +00001954 (Expr *)BitfieldWidth);
Fariborz Jahaniande615832008-04-10 23:32:45 +00001955
Ted Kremenek73295fa2008-07-23 18:04:17 +00001956 // Process attributes attached to the ivar.
Chris Lattner2727d1b2008-06-29 00:02:00 +00001957 ProcessDeclAttributes(NewID, D);
Fariborz Jahaniande615832008-04-10 23:32:45 +00001958
1959 if (D.getInvalidType() || InvalidDecl)
1960 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +00001961
Fariborz Jahaniande615832008-04-10 23:32:45 +00001962 return NewID;
1963}
1964
Fariborz Jahanian343f7092007-09-29 00:54:24 +00001965void Sema::ActOnFields(Scope* S,
Fariborz Jahanian67341402007-10-04 00:45:27 +00001966 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff30d242c2007-09-15 18:49:24 +00001967 DeclTy **Fields, unsigned NumFields,
Fariborz Jahaniande615832008-04-10 23:32:45 +00001968 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00001969 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1970 assert(EnclosingDecl && "missing record or interface decl");
1971 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1972
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001973 if (Record && Record->isDefinition()) {
Chris Lattner1300fb92007-01-23 23:42:53 +00001974 // Diagnose code like:
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001975 // struct S { struct S {} X; };
Chris Lattner1300fb92007-01-23 23:42:53 +00001976 // We discover this when we complete the outer S. Reject and ignore the
1977 // outer S.
1978 Diag(Record->getLocation(), diag::err_nested_redefinition,
1979 Record->getKindName());
1980 Diag(RecLoc, diag::err_previous_definition);
Steve Naroffdb47ee22007-09-14 22:20:54 +00001981 Record->setInvalidDecl();
Chris Lattner1300fb92007-01-23 23:42:53 +00001982 return;
1983 }
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001984 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +00001985 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +00001986 llvm::SmallVector<FieldDecl*, 32> RecFields;
1987 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroffdb47ee22007-09-14 22:20:54 +00001988
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001989 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001990
Steve Naroffdb47ee22007-09-14 22:20:54 +00001991 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1992 assert(FD && "missing field decl");
1993
1994 // Remember all fields.
1995 RecFields.push_back(FD);
Chris Lattner720a0542007-01-25 00:44:24 +00001996
1997 // Get the type for the field.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001998 Type *FDTy = FD->getType().getTypePtr();
Steve Naroff2e688fd2007-09-14 23:09:53 +00001999
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00002000 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner0fd893e2007-07-31 21:33:24 +00002001 if (FDTy->isFunctionType()) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00002002 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00002003 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00002004 FD->setInvalidDecl();
2005 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00002006 continue;
2007 }
Chris Lattner82625602007-01-24 02:26:21 +00002008 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
Chris Lattner720a0542007-01-25 00:44:24 +00002009 if (FDTy->isIncompleteType()) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00002010 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian67341402007-10-04 00:45:27 +00002011 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00002012 FD->setInvalidDecl();
2013 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian67341402007-10-04 00:45:27 +00002014 continue;
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00002015 }
Chris Lattner82625602007-01-24 02:26:21 +00002016 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002017 !Record->isStruct() || // ... of a structure ...
Chris Lattner0fd893e2007-07-31 21:33:24 +00002018 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner82625602007-01-24 02:26:21 +00002019 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00002020 FD->setInvalidDecl();
2021 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00002022 continue;
2023 }
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00002024 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner82625602007-01-24 02:26:21 +00002025 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2026 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00002027 FD->setInvalidDecl();
2028 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00002029 continue;
2030 }
Chris Lattner720a0542007-01-25 00:44:24 +00002031 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00002032 if (Record)
2033 Record->setHasFlexibleArrayMember(true);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00002034 }
Chris Lattner720a0542007-01-25 00:44:24 +00002035 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2036 /// field of another structure or the element of an array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00002037 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner720a0542007-01-25 00:44:24 +00002038 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2039 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002040 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +00002041 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00002042 } else {
2043 // If this is a struct/class and this is not the last element, reject
2044 // it. Note that GCC supports variable sized arrays in the middle of
2045 // structures.
2046 if (i != NumFields-1) {
2047 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2048 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00002049 FD->setInvalidDecl();
2050 EnclosingDecl->setInvalidDecl();
Chris Lattner720a0542007-01-25 00:44:24 +00002051 continue;
2052 }
Chris Lattner720a0542007-01-25 00:44:24 +00002053 // We support flexible arrays at the end of structs in other structs
2054 // as an extension.
2055 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2056 FD->getName());
Fariborz Jahanian67341402007-10-04 00:45:27 +00002057 if (Record)
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00002058 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00002059 }
2060 }
2061 }
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00002062 /// A field cannot be an Objective-c object
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002063 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00002064 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2065 FD->getName());
2066 FD->setInvalidDecl();
2067 EnclosingDecl->setInvalidDecl();
2068 continue;
2069 }
Chris Lattner82625602007-01-24 02:26:21 +00002070 // Keep track of the number of named members.
Chris Lattnere5a66562007-01-25 22:48:42 +00002071 if (IdentifierInfo *II = FD->getIdentifier()) {
2072 // Detect duplicate member names.
Chris Lattnerbaf33662007-01-27 02:14:08 +00002073 if (!FieldIDs.insert(II)) {
Chris Lattnere5a66562007-01-25 22:48:42 +00002074 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2075 // Find the previous decl.
2076 SourceLocation PrevLoc;
2077 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2078 assert(i != e && "Didn't find previous def!");
2079 if (RecFields[i]->getIdentifier() == II) {
2080 PrevLoc = RecFields[i]->getLocation();
2081 break;
2082 }
2083 }
2084 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroffdb47ee22007-09-14 22:20:54 +00002085 FD->setInvalidDecl();
2086 EnclosingDecl->setInvalidDecl();
Chris Lattnere5a66562007-01-25 22:48:42 +00002087 continue;
2088 }
Chris Lattner82625602007-01-24 02:26:21 +00002089 ++NumNamedMembers;
Chris Lattnere5a66562007-01-25 22:48:42 +00002090 }
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00002091 }
Chris Lattner82625602007-01-24 02:26:21 +00002092
Chris Lattner82625602007-01-24 02:26:21 +00002093 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +00002094 if (Record) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00002095 Record->defineBody(&RecFields[0], RecFields.size());
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +00002096 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2097 // Sema::ActOnFinishCXXClassDef.
2098 if (!isa<CXXRecordDecl>(Record))
2099 Consumer.HandleTagDeclDefinition(Record);
Chris Lattner622c1932008-02-06 00:51:33 +00002100 } else {
Chris Lattner9413a012008-02-05 22:40:55 +00002101 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2102 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2103 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2104 else if (ObjCImplementationDecl *IMPDecl =
2105 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002106 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2107 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian95b60762007-10-31 18:48:14 +00002108 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00002109 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00002110 }
Chris Lattner1300fb92007-01-23 23:42:53 +00002111}
2112
Steve Naroff30d242c2007-09-15 18:49:24 +00002113Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4ef40012007-06-11 01:28:17 +00002114 DeclTy *lastEnumConst,
Chris Lattnerc1915e22007-01-25 07:29:02 +00002115 SourceLocation IdLoc, IdentifierInfo *Id,
Chris Lattner4ef40012007-06-11 01:28:17 +00002116 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002117 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4ef40012007-06-11 01:28:17 +00002118 EnumConstantDecl *LastEnumConst =
2119 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2120 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00002121
Chris Lattner1a76a3c2007-08-26 06:24:45 +00002122 // The scope passed in may not be a decl scope. Zip up the scope tree until
2123 // we find one that is.
2124 while ((S->getFlags() & Scope::DeclScope) == 0)
2125 S = S->getParent();
2126
Chris Lattner8116d1b2007-01-25 22:38:29 +00002127 // Verify that there isn't already something declared with this name in this
2128 // scope.
Steve Naroff2fc93f52008-04-02 14:35:35 +00002129 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +00002130 // When in C++, we may get a TagDecl with the same name; in this case the
2131 // enum constant will 'hide' the tag.
2132 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2133 "Received TagDecl when not in C++!");
2134 if (!isa<TagDecl>(PrevDecl) &&
2135 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00002136 if (isa<EnumConstantDecl>(PrevDecl))
2137 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2138 else
2139 Diag(IdLoc, diag::err_redefinition, Id->getName());
2140 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner77683132008-02-26 00:33:57 +00002141 delete Val;
Chris Lattner8116d1b2007-01-25 22:38:29 +00002142 return 0;
2143 }
2144 }
Chris Lattner4ef40012007-06-11 01:28:17 +00002145
Chris Lattner23b7eb62007-06-15 23:05:46 +00002146 llvm::APSInt EnumVal(32);
Chris Lattner4ef40012007-06-11 01:28:17 +00002147 QualType EltTy;
2148 if (Val) {
Chris Lattner0515e4b2007-08-27 21:16:18 +00002149 // Make sure to promote the operand type to int.
2150 UsualUnaryConversions(Val);
2151
Chris Lattner4ef40012007-06-11 01:28:17 +00002152 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2153 SourceLocation ExpLoc;
Chris Lattner0e9d6222007-07-15 23:26:56 +00002154 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Chris Lattner4ef40012007-06-11 01:28:17 +00002155 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2156 Id->getName());
Chris Lattner77683132008-02-26 00:33:57 +00002157 delete Val;
Chris Lattnerf283a372007-08-27 17:37:24 +00002158 Val = 0; // Just forget about it.
Chris Lattnerc92bc4c2007-08-29 16:03:41 +00002159 } else {
2160 EltTy = Val->getType();
Chris Lattner4ef40012007-06-11 01:28:17 +00002161 }
Chris Lattnerf283a372007-08-27 17:37:24 +00002162 }
2163
2164 if (!Val) {
2165 if (LastEnumConst) {
2166 // Assign the last value + 1.
2167 EnumVal = LastEnumConst->getInitVal();
2168 ++EnumVal;
Chris Lattner0515e4b2007-08-27 21:16:18 +00002169
2170 // Check for overflow on increment.
2171 if (EnumVal < LastEnumConst->getInitVal())
2172 Diag(IdLoc, diag::warn_enum_value_overflow);
2173
Chris Lattnerf283a372007-08-27 17:37:24 +00002174 EltTy = LastEnumConst->getType();
2175 } else {
2176 // First value, set to zero.
2177 EltTy = Context.IntTy;
Chris Lattner37e05872008-03-05 18:54:05 +00002178 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerf283a372007-08-27 17:37:24 +00002179 }
Steve Naroff63969212007-05-07 21:22:42 +00002180 }
Chris Lattner4ef40012007-06-11 01:28:17 +00002181
Chris Lattnera7b32872008-03-15 06:12:44 +00002182 EnumConstantDecl *New =
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002183 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2184 Val, EnumVal,
Chris Lattner96c460d2008-03-15 21:32:50 +00002185 LastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +00002186
2187 // Register this decl in the current scope stack.
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00002188 PushOnScopeChains(New, S);
Chris Lattner8116d1b2007-01-25 22:38:29 +00002189 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +00002190}
2191
Steve Narofff960c0b2008-08-07 14:08:16 +00002192// FIXME: For consistency with ActOnFields(), we should have the parser
2193// pass in the source location for the left/right braces.
Steve Naroff30d242c2007-09-15 18:49:24 +00002194void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattnerc1915e22007-01-25 07:29:02 +00002195 DeclTy **Elements, unsigned NumElements) {
2196 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Chris Lattnerc1915e22007-01-25 07:29:02 +00002197
Steve Narofff960c0b2008-08-07 14:08:16 +00002198 if (Enum && Enum->isDefinition()) {
2199 // Diagnose code like:
2200 // enum e0 {
2201 // E0 = sizeof(enum e0 { E1 })
2202 // };
2203 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2204 Enum->getName());
2205 Diag(EnumLoc, diag::err_previous_definition);
2206 Enum->setInvalidDecl();
2207 return;
2208 }
Chris Lattner67933c02007-08-28 05:10:31 +00002209 // TODO: If the result value doesn't fit in an int, it must be a long or long
2210 // long value. ISO C does not support this, but GCC does as an extension,
2211 // emit a warning.
Chris Lattner37e05872008-03-05 18:54:05 +00002212 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner67933c02007-08-28 05:10:31 +00002213
Chris Lattnerb8a501c2007-08-28 06:15:15 +00002214 // Verify that all the values are okay, compute the size of the values, and
2215 // reverse the list.
2216 unsigned NumNegativeBits = 0;
2217 unsigned NumPositiveBits = 0;
2218
2219 // Keep track of whether all elements have type int.
2220 bool AllElementsInt = true;
2221
Chris Lattner4ef40012007-06-11 01:28:17 +00002222 EnumConstantDecl *EltList = 0;
Chris Lattnerc1915e22007-01-25 07:29:02 +00002223 for (unsigned i = 0; i != NumElements; ++i) {
2224 EnumConstantDecl *ECD =
2225 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2226 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnerbf478cb2007-08-28 05:27:00 +00002227
2228 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnerbf478cb2007-08-28 05:27:00 +00002229 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner77683132008-02-26 00:33:57 +00002230 assert(InitVal.getBitWidth() >= IntWidth &&
2231 "Should have promoted value to int");
Chris Lattnerbf478cb2007-08-28 05:27:00 +00002232 if (InitVal.getBitWidth() > IntWidth) {
2233 llvm::APSInt V(InitVal);
2234 V.trunc(IntWidth);
2235 V.extend(InitVal.getBitWidth());
2236 if (V != InitVal)
2237 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattner5d1cfa12008-08-17 07:19:51 +00002238 InitVal.toString(10));
Chris Lattnerbf478cb2007-08-28 05:27:00 +00002239 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00002240
2241 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +00002242 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +00002243 NumPositiveBits = std::max(NumPositiveBits,
2244 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +00002245 else
Chris Lattner49f980c2008-01-14 21:47:29 +00002246 NumNegativeBits = std::max(NumNegativeBits,
2247 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00002248
Chris Lattnerb8a501c2007-08-28 06:15:15 +00002249 // Keep track of whether every enum element has type int (very commmon).
2250 if (AllElementsInt)
2251 AllElementsInt = ECD->getType() == Context.IntTy;
2252
Chris Lattner4ef40012007-06-11 01:28:17 +00002253 ECD->setNextDeclarator(EltList);
2254 EltList = ECD;
Chris Lattnerc1915e22007-01-25 07:29:02 +00002255 }
2256
Chris Lattnerb8a501c2007-08-28 06:15:15 +00002257 // Figure out the type that should be used for this enum.
2258 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2259 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00002260 unsigned BestWidth;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00002261
2262 if (NumNegativeBits) {
2263 // If there is a negative value, figure out the smallest integer type (of
2264 // int/long/longlong) that fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00002265 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00002266 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00002267 BestWidth = IntWidth;
2268 } else {
Chris Lattner37e05872008-03-05 18:54:05 +00002269 BestWidth = Context.Target.getLongWidth();
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00002270
Chris Lattner3a370bf2007-08-29 17:31:48 +00002271 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00002272 BestType = Context.LongTy;
2273 else {
Chris Lattner37e05872008-03-05 18:54:05 +00002274 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00002275
Chris Lattner3a370bf2007-08-29 17:31:48 +00002276 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00002277 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2278 BestType = Context.LongLongTy;
2279 }
2280 }
2281 } else {
2282 // If there is no negative value, figure out which of uint, ulong, ulonglong
2283 // fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00002284 if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00002285 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00002286 BestWidth = IntWidth;
2287 } else if (NumPositiveBits <=
Chris Lattner37e05872008-03-05 18:54:05 +00002288 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00002289 BestType = Context.UnsignedLongTy;
Chris Lattner37e05872008-03-05 18:54:05 +00002290 } else {
2291 BestWidth = Context.Target.getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +00002292 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00002293 "How could an initializer get larger than ULL?");
2294 BestType = Context.UnsignedLongLongTy;
2295 }
2296 }
2297
Chris Lattner3a370bf2007-08-29 17:31:48 +00002298 // Loop over all of the enumerator constants, changing their types to match
2299 // the type of the enum if needed.
2300 for (unsigned i = 0; i != NumElements; ++i) {
2301 EnumConstantDecl *ECD =
2302 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2303 if (!ECD) continue; // Already issued a diagnostic.
2304
2305 // Standard C says the enumerators have int type, but we allow, as an
2306 // extension, the enumerators to be larger than int size. If each
2307 // enumerator value fits in an int, type it as an int, otherwise type it the
2308 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2309 // that X has type 'int', not 'unsigned'.
Chris Lattner77683132008-02-26 00:33:57 +00002310 if (ECD->getType() == Context.IntTy) {
2311 // Make sure the init value is signed.
2312 llvm::APSInt IV = ECD->getInitVal();
2313 IV.setIsSigned(true);
2314 ECD->setInitVal(IV);
Chris Lattner3a370bf2007-08-29 17:31:48 +00002315 continue; // Already int type.
Chris Lattner77683132008-02-26 00:33:57 +00002316 }
Chris Lattner3a370bf2007-08-29 17:31:48 +00002317
2318 // Determine whether the value fits into an int.
2319 llvm::APSInt InitVal = ECD->getInitVal();
2320 bool FitsInInt;
2321 if (InitVal.isUnsigned() || !InitVal.isNegative())
2322 FitsInInt = InitVal.getActiveBits() < IntWidth;
2323 else
2324 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2325
2326 // If it fits into an integer type, force it. Otherwise force it to match
2327 // the enum decl type.
2328 QualType NewTy;
2329 unsigned NewWidth;
2330 bool NewSign;
2331 if (FitsInInt) {
2332 NewTy = Context.IntTy;
2333 NewWidth = IntWidth;
2334 NewSign = true;
2335 } else if (ECD->getType() == BestType) {
2336 // Already the right type!
2337 continue;
2338 } else {
2339 NewTy = BestType;
2340 NewWidth = BestWidth;
2341 NewSign = BestType->isSignedIntegerType();
2342 }
2343
2344 // Adjust the APSInt value.
2345 InitVal.extOrTrunc(NewWidth);
2346 InitVal.setIsSigned(NewSign);
2347 ECD->setInitVal(InitVal);
2348
2349 // Adjust the Expr initializer and type.
2350 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2351 ECD->setType(NewTy);
2352 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00002353
Chris Lattner1c1f9322007-08-28 18:24:31 +00002354 Enum->defineElements(EltList, BestType);
Chris Lattner622c1932008-02-06 00:51:33 +00002355 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +00002356}
Chris Lattner1300fb92007-01-23 23:42:53 +00002357
Anders Carlsson5c6c0592008-02-08 00:33:21 +00002358Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2359 ExprTy *expr) {
2360 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2361
Chris Lattneree1284a2008-03-16 00:16:02 +00002362 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson5c6c0592008-02-08 00:33:21 +00002363}
2364
Chris Lattner38376f12008-01-12 07:05:38 +00002365Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnereb85ab42008-02-25 21:04:36 +00002366 SourceLocation LBrace,
2367 SourceLocation RBrace,
2368 const char *Lang,
2369 unsigned StrSize,
2370 DeclTy *D) {
Chris Lattner38376f12008-01-12 07:05:38 +00002371 LinkageSpecDecl::LanguageIDs Language;
2372 Decl *dcl = static_cast<Decl *>(D);
2373 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2374 Language = LinkageSpecDecl::lang_c;
2375 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2376 Language = LinkageSpecDecl::lang_cxx;
2377 else {
2378 Diag(Loc, diag::err_bad_language);
2379 return 0;
2380 }
2381
2382 // FIXME: Add all the various semantics of linkage specifications
Chris Lattneree1284a2008-03-16 00:16:02 +00002383 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner38376f12008-01-12 07:05:38 +00002384}