blob: 24308f6b4a67471b64ce68376fc07b50eeec7b2e [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6953a072008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-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 Lattner33aad6e2008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallSet.h"
Daniel Dunbar81c7d472008-10-14 05:35:18 +000028#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029using namespace clang;
30
Douglas Gregorb0212bd2008-11-17 20:34:05 +000031Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000032 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000033 DeclContext *DC = 0;
34 if (SS) {
35 if (SS->isInvalid())
36 return 0;
37 DC = static_cast<DeclContext*>(SS->getScopeRep());
38 }
39 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroff6384a012008-04-02 14:35:35 +000040
Douglas Gregor1d661552008-04-13 21:07:44 +000041 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
42 isa<ObjCInterfaceDecl>(IIDecl) ||
43 isa<TagDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000044 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000045 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000046}
47
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000048DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000049 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000050 // A C++ out-of-line method will return to the file declaration context.
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000051 if (MD->isOutOfLineDefinition())
52 return MD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000053
54 // A C++ inline method is parsed *after* the topmost class it was declared in
55 // is fully parsed (it's "complete").
56 // The parsing of a C++ inline method happens at the declaration context of
57 // the topmost (non-nested) class it is declared in.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000058 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
59 DC = MD->getParent();
60 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
61 DC = RD;
62
63 // Return the declaration context of the topmost class the inline method is
64 // declared in.
65 return DC;
66 }
67
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000068 if (isa<ObjCMethodDecl>(DC))
69 return Context.getTranslationUnitDecl();
70
71 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
72 return SD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000073
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000074 return DC->getParent();
75}
76
Chris Lattneref87a202008-04-22 18:39:57 +000077void Sema::PushDeclContext(DeclContext *DC) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000078 assert(getContainingDC(DC) == CurContext &&
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000079 "The next DeclContext should be lexically contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000080 CurContext = DC;
Chris Lattnereee57c02008-04-04 06:12:32 +000081}
82
Chris Lattnerf3874bc2008-04-06 04:47:34 +000083void Sema::PopDeclContext() {
84 assert(CurContext && "DeclContext imbalance!");
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000085 CurContext = getContainingDC(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +000086}
87
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000088/// Add this decl to the scope shadowed decl chains.
89void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000090 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000091
92 // C++ [basic.scope]p4:
93 // -- exactly one declaration shall declare a class name or
94 // enumeration name that is not a typedef name and the other
95 // declarations shall all refer to the same object or
96 // enumerator, or all refer to functions and function templates;
97 // in this case the class name or enumeration name is hidden.
98 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
99 // We are pushing the name of a tag (enum or class).
Argiris Kirtzidis94805232008-07-17 17:49:50 +0000100 IdentifierResolver::iterator
101 I = IdResolver.begin(TD->getIdentifier(),
102 TD->getDeclContext(), false/*LookInParentCtx*/);
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000103 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) {
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000104 // There is already a declaration with the same name in the same
105 // scope. It must be found before we find the new declaration,
106 // so swap the order on the shadowed declaration chain.
107
Argiris Kirtzidis94805232008-07-17 17:49:50 +0000108 IdResolver.AddShadowedDecl(TD, *I);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000109 return;
110 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +0000111 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
112 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000113 // We are pushing the name of a function, which might be an
114 // overloaded name.
115 IdentifierResolver::iterator
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000116 I = IdResolver.begin(FD->getDeclName(),
Douglas Gregord2baafd2008-10-21 16:13:35 +0000117 FD->getDeclContext(), false/*LookInParentCtx*/);
118 if (I != IdResolver.end() &&
119 IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) &&
120 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
121 // There is already a declaration with the same name in the same
122 // scope. It must be a function or an overloaded function.
123 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
124 if (!Ovl) {
125 // We haven't yet overloaded this function. Take the existing
126 // FunctionDecl and put it into an OverloadedFunctionDecl.
127 Ovl = OverloadedFunctionDecl::Create(Context,
128 FD->getDeclContext(),
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000129 FD->getDeclName());
Douglas Gregord2baafd2008-10-21 16:13:35 +0000130 Ovl->addOverload(dyn_cast<FunctionDecl>(*I));
131
132 // Remove the name binding to the existing FunctionDecl...
133 IdResolver.RemoveDecl(*I);
134
135 // ... and put the OverloadedFunctionDecl in its place.
136 IdResolver.AddDecl(Ovl);
137 }
138
139 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
140 // to its list of overloads.
141 Ovl->addOverload(FD);
142
143 return;
144 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000145 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000146
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000147 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000148}
149
Steve Naroff9637a9b2007-10-09 22:01:59 +0000150void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000151 if (S->decl_empty()) return;
152 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000153
Chris Lattner4b009652007-07-25 00:24:17 +0000154 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
155 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000156 Decl *TmpD = static_cast<Decl*>(*I);
157 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000158
159 if (isa<CXXFieldDecl>(TmpD)) continue;
160
161 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
162 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000163
Chris Lattner4b009652007-07-25 00:24:17 +0000164 IdentifierInfo *II = D->getIdentifier();
165 if (!II) continue;
166
Ted Kremenek40e70e72008-09-03 18:03:35 +0000167 // We only want to remove the decls from the identifier decl chains for
168 // local scopes, when inside a function/method.
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000169 if (S->getFnParent() != 0)
170 IdResolver.RemoveDecl(D);
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000171
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000172 // Chain this decl to the containing DeclContext.
173 D->setNext(CurContext->getDeclChain());
174 CurContext->setDeclChain(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000175 }
176}
177
Steve Naroffe57c21a2008-04-01 23:04:06 +0000178/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
179/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000180ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000181 // The third "scope" argument is 0 since we aren't enabling lazy built-in
182 // creation from this context.
183 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000184
Steve Naroff6384a012008-04-02 14:35:35 +0000185 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000186}
187
Steve Naroffe57c21a2008-04-01 23:04:06 +0000188/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000189/// namespace.
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000190Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000191 const DeclContext *LookupCtx,
192 bool enableLazyBuiltinCreation) {
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000193 if (!Name) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000194 unsigned NS = NSI;
195 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
196 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000197
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000198 IdentifierResolver::iterator
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000199 I = LookupCtx ? IdResolver.begin(Name, LookupCtx, false/*LookInParentCtx*/)
200 : IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/);
Chris Lattner4b009652007-07-25 00:24:17 +0000201 // Scan up the scope chain looking for a decl that matches this identifier
202 // that is in the appropriate namespace. This search should not take long, as
203 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000204 for (; I != IdResolver.end(); ++I)
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000205 if ((*I)->getIdentifierNamespace() & NS)
206 return *I;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000207
Chris Lattner4b009652007-07-25 00:24:17 +0000208 // If we didn't find a use of this identifier, and if the identifier
209 // corresponds to a compiler builtin, create the decl object for the builtin
210 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1d661552008-04-13 21:07:44 +0000211 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000212 IdentifierInfo *II = Name.getAsIdentifierInfo();
213 if (enableLazyBuiltinCreation && II &&
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000214 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroff6384a012008-04-02 14:35:35 +0000215 // If this is a builtin on this (or all) targets, create the decl.
216 if (unsigned BuiltinID = II->getBuiltinID())
217 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
218 }
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000219 if (getLangOptions().ObjC1 && II) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000220 // @interface and @compatibility_alias introduce typedef-like names.
221 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000222 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000223 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000224 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
225 if (IDI != ObjCInterfaceDecls.end())
226 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000227 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
228 if (I != ObjCAliasDecls.end())
229 return I->second->getClassInterface();
230 }
Chris Lattner4b009652007-07-25 00:24:17 +0000231 }
232 return 0;
233}
234
Chris Lattnera9c87f22008-05-05 22:18:14 +0000235void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000236 if (!Context.getBuiltinVaListType().isNull())
237 return;
238
239 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000240 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000241 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000242 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
243}
244
Chris Lattner4b009652007-07-25 00:24:17 +0000245/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
246/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000247ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
248 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000249 Builtin::ID BID = (Builtin::ID)bid;
250
Chris Lattnerb23469f2008-09-28 05:54:29 +0000251 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000252 InitBuiltinVaListType();
253
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000254 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000255 FunctionDecl *New = FunctionDecl::Create(Context,
256 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000257 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000258 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000259
Chris Lattnera9c87f22008-05-05 22:18:14 +0000260 // Create Decl objects for each parameter, adding them to the
261 // FunctionDecl.
262 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
263 llvm::SmallVector<ParmVarDecl*, 16> Params;
264 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
265 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
266 FT->getArgType(i), VarDecl::None, 0,
267 0));
268 New->setParams(&Params[0], Params.size());
269 }
270
271
272
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000273 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000274 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000275 return New;
276}
277
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000278/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
279/// everything from the standard library is defined.
280NamespaceDecl *Sema::GetStdNamespace() {
281 if (!StdNamespace) {
282 DeclContext *Global = Context.getTranslationUnitDecl();
283 Decl *Std = LookupDecl(Ident_StdNs, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
284 0, Global, /*enableLazyBuiltinCreation=*/false);
285 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
286 }
287 return StdNamespace;
288}
289
Chris Lattner4b009652007-07-25 00:24:17 +0000290/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
291/// and scope as a previous declaration 'Old'. Figure out how to resolve this
292/// situation, merging decls or emitting diagnostics as appropriate.
293///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000294TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff453a8782008-09-09 14:32:20 +0000295 // Allow multiple definitions for ObjC built-in typedefs.
296 // FIXME: Verify the underlying types are equivalent!
297 if (getLangOptions().ObjC1) {
298 const IdentifierInfo *typeIdent = New->getIdentifier();
299 if (typeIdent == Ident_id) {
300 Context.setObjCIdType(New);
301 return New;
302 } else if (typeIdent == Ident_Class) {
303 Context.setObjCClassType(New);
304 return New;
305 } else if (typeIdent == Ident_SEL) {
306 Context.setObjCSelType(New);
307 return New;
308 } else if (typeIdent == Ident_Protocol) {
309 Context.setObjCProtoType(New->getUnderlyingType());
310 return New;
311 }
312 // Fall through - the typedef name was not a builtin type.
313 }
Chris Lattner4b009652007-07-25 00:24:17 +0000314 // Verify the old decl was also a typedef.
315 TypedefDecl *Old = dyn_cast<TypedefDecl>(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 }
322
Chris Lattnerbef8d622008-07-25 18:44:27 +0000323 // If the typedef types are not identical, reject them in all languages and
324 // with any extensions enabled.
325 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
326 Context.getCanonicalType(Old->getUnderlyingType()) !=
327 Context.getCanonicalType(New->getUnderlyingType())) {
328 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
329 New->getUnderlyingType().getAsString(),
330 Old->getUnderlyingType().getAsString());
331 Diag(Old->getLocation(), diag::err_previous_definition);
332 return Old;
333 }
334
Eli Friedman324d5032008-06-11 06:20:39 +0000335 if (getLangOptions().Microsoft) return New;
336
Steve Naroffa9eae582008-01-30 23:46:05 +0000337 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
338 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
339 // *either* declaration is in a system header. The code below implements
340 // this adhoc compatibility rule. FIXME: The following code will not
341 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000342 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
343 SourceManager &SrcMgr = Context.getSourceManager();
344 if (SrcMgr.isInSystemHeader(Old->getLocation()))
345 return New;
346 if (SrcMgr.isInSystemHeader(New->getLocation()))
347 return New;
348 }
Eli Friedman324d5032008-06-11 06:20:39 +0000349
Ted Kremenek64845ce2008-05-23 21:28:18 +0000350 Diag(New->getLocation(), diag::err_redefinition, New->getName());
351 Diag(Old->getLocation(), diag::err_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000352 return New;
353}
354
Chris Lattner6953a072008-06-26 18:38:35 +0000355/// DeclhasAttr - returns true if decl Declaration already has the target
356/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000357static bool DeclHasAttr(const Decl *decl, const Attr *target) {
358 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
359 if (attr->getKind() == target->getKind())
360 return true;
361
362 return false;
363}
364
365/// MergeAttributes - append attributes from the Old decl to the New one.
366static void MergeAttributes(Decl *New, Decl *Old) {
367 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
368
Chris Lattner402b3372008-03-03 03:28:21 +0000369 while (attr) {
370 tmp = attr;
371 attr = attr->getNext();
372
373 if (!DeclHasAttr(New, tmp)) {
374 New->addAttr(tmp);
375 } else {
376 tmp->setNext(0);
377 delete(tmp);
378 }
379 }
Nuno Lopes77654342008-06-01 22:53:53 +0000380
381 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000382}
383
Chris Lattner3e254fb2008-04-08 04:40:51 +0000384/// MergeFunctionDecl - We just parsed a function 'New' from
385/// declarator D which has the same name and scope as a previous
386/// declaration 'Old'. Figure out how to resolve this situation,
387/// merging decls or emitting diagnostics as appropriate.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000388/// Redeclaration will be set true if this New is a redeclaration OldD.
389///
390/// In C++, New and Old must be declarations that are not
391/// overloaded. Use IsOverload to determine whether New and Old are
392/// overloaded, and to select the Old declaration that New should be
393/// merged with.
Douglas Gregor42214c52008-04-21 02:02:58 +0000394FunctionDecl *
395Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000396 assert(!isa<OverloadedFunctionDecl>(OldD) &&
397 "Cannot merge with an overloaded function declaration");
398
Douglas Gregor42214c52008-04-21 02:02:58 +0000399 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000400 // Verify the old decl was also a function.
401 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
402 if (!Old) {
403 Diag(New->getLocation(), diag::err_redefinition_different_kind,
404 New->getName());
405 Diag(OldD->getLocation(), diag::err_previous_definition);
406 return New;
407 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000408
409 // Determine whether the previous declaration was a definition,
410 // implicit declaration, or a declaration.
411 diag::kind PrevDiag;
412 if (Old->isThisDeclarationADefinition())
413 PrevDiag = diag::err_previous_definition;
414 else if (Old->isImplicit())
415 PrevDiag = diag::err_previous_implicit_declaration;
416 else
417 PrevDiag = diag::err_previous_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000418
Chris Lattner42a21742008-04-06 23:10:54 +0000419 QualType OldQType = Context.getCanonicalType(Old->getType());
420 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000421
Douglas Gregord2baafd2008-10-21 16:13:35 +0000422 if (getLangOptions().CPlusPlus) {
423 // (C++98 13.1p2):
424 // Certain function declarations cannot be overloaded:
425 // -- Function declarations that differ only in the return type
426 // cannot be overloaded.
427 QualType OldReturnType
428 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
429 QualType NewReturnType
430 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
431 if (OldReturnType != NewReturnType) {
432 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
433 Diag(Old->getLocation(), PrevDiag);
434 return New;
435 }
436
437 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
438 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
439 if (OldMethod && NewMethod) {
440 // -- Member function declarations with the same name and the
441 // same parameter types cannot be overloaded if any of them
442 // is a static member function declaration.
443 if (OldMethod->isStatic() || NewMethod->isStatic()) {
444 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
445 Diag(Old->getLocation(), PrevDiag);
446 return New;
447 }
448 }
449
450 // (C++98 8.3.5p3):
451 // All declarations for a function shall agree exactly in both the
452 // return type and the parameter-type-list.
453 if (OldQType == NewQType) {
454 // We have a redeclaration.
455 MergeAttributes(New, Old);
456 Redeclaration = true;
457 return MergeCXXFunctionDecl(New, Old);
458 }
459
460 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor42214c52008-04-21 02:02:58 +0000461 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000462
463 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000464 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000465 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000466 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000467 MergeAttributes(New, Old);
468 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000469 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000470 }
Chris Lattner1470b072007-11-06 06:07:26 +0000471
Steve Naroff6c9e7922008-01-16 15:01:34 +0000472 // A function that has already been declared has been redeclared or defined
473 // with a different type- show appropriate diagnostic
Steve Naroff6c9e7922008-01-16 15:01:34 +0000474
Chris Lattner4b009652007-07-25 00:24:17 +0000475 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
476 // TODO: This is totally simplistic. It should handle merging functions
477 // together etc, merging extern int X; int X; ...
Steve Naroff6c9e7922008-01-16 15:01:34 +0000478 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
479 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000480 return New;
481}
482
Steve Naroffb5e78152008-08-08 17:50:35 +0000483/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000484static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000485 if (VD->isFileVarDecl())
486 return (!VD->getInit() &&
487 (VD->getStorageClass() == VarDecl::None ||
488 VD->getStorageClass() == VarDecl::Static));
489 return false;
490}
491
492/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
493/// when dealing with C "tentative" external object definitions (C99 6.9.2).
494void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
495 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000496 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000497
498 for (IdentifierResolver::iterator
499 I = IdResolver.begin(VD->getIdentifier(),
500 VD->getDeclContext(), false/*LookInParentCtx*/),
501 E = IdResolver.end(); I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000502 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000503 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
504
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000505 // Handle the following case:
506 // int a[10];
507 // int a[]; - the code below makes sure we set the correct type.
508 // int a[11]; - this is an error, size isn't 10.
509 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
510 OldDecl->getType()->isConstantArrayType())
511 VD->setType(OldDecl->getType());
512
Steve Naroffb5e78152008-08-08 17:50:35 +0000513 // Check for "tentative" definitions. We can't accomplish this in
514 // MergeVarDecl since the initializer hasn't been attached.
515 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
516 continue;
517
518 // Handle __private_extern__ just like extern.
519 if (OldDecl->getStorageClass() != VarDecl::Extern &&
520 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
521 VD->getStorageClass() != VarDecl::Extern &&
522 VD->getStorageClass() != VarDecl::PrivateExtern) {
523 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
524 Diag(OldDecl->getLocation(), diag::err_previous_definition);
525 }
526 }
527 }
528}
529
Chris Lattner4b009652007-07-25 00:24:17 +0000530/// MergeVarDecl - We just parsed a variable 'New' which has the same name
531/// and scope as a previous declaration 'Old'. Figure out how to resolve this
532/// situation, merging decls or emitting diagnostics as appropriate.
533///
Steve Naroffb5e78152008-08-08 17:50:35 +0000534/// Tentative definition rules (C99 6.9.2p2) are checked by
535/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
536/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000537///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000538VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000539 // Verify the old decl was also a variable.
540 VarDecl *Old = dyn_cast<VarDecl>(OldD);
541 if (!Old) {
542 Diag(New->getLocation(), diag::err_redefinition_different_kind,
543 New->getName());
544 Diag(OldD->getLocation(), diag::err_previous_definition);
545 return New;
546 }
Chris Lattner402b3372008-03-03 03:28:21 +0000547
548 MergeAttributes(New, Old);
549
Chris Lattner4b009652007-07-25 00:24:17 +0000550 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000551 QualType OldCType = Context.getCanonicalType(Old->getType());
552 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff12508172008-08-09 16:04:40 +0000553 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000554 Diag(New->getLocation(), diag::err_redefinition, New->getName());
555 Diag(Old->getLocation(), diag::err_previous_definition);
556 return New;
557 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000558 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
559 if (New->getStorageClass() == VarDecl::Static &&
560 (Old->getStorageClass() == VarDecl::None ||
561 Old->getStorageClass() == VarDecl::Extern)) {
562 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
563 Diag(Old->getLocation(), diag::err_previous_definition);
564 return New;
565 }
566 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
567 if (New->getStorageClass() != VarDecl::Static &&
568 Old->getStorageClass() == VarDecl::Static) {
569 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
570 Diag(Old->getLocation(), diag::err_previous_definition);
571 return New;
572 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000573 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
574 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000575 Diag(New->getLocation(), diag::err_redefinition, New->getName());
576 Diag(Old->getLocation(), diag::err_previous_definition);
577 }
578 return New;
579}
580
Chris Lattner3e254fb2008-04-08 04:40:51 +0000581/// CheckParmsForFunctionDef - Check that the parameters of the given
582/// function are appropriate for the definition of a function. This
583/// takes care of any checks that cannot be performed on the
584/// declaration itself, e.g., that the types of each of the function
585/// parameters are complete.
586bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
587 bool HasInvalidParm = false;
588 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
589 ParmVarDecl *Param = FD->getParamDecl(p);
590
591 // C99 6.7.5.3p4: the parameters in a parameter type list in a
592 // function declarator that is part of a function definition of
593 // that function shall not have incomplete type.
594 if (Param->getType()->isIncompleteType() &&
595 !Param->isInvalidDecl()) {
596 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
597 Param->getType().getAsString());
598 Param->setInvalidDecl();
599 HasInvalidParm = true;
600 }
601 }
602
603 return HasInvalidParm;
604}
605
Chris Lattner4b009652007-07-25 00:24:17 +0000606/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
607/// no declarator (e.g. "struct foo;") is parsed.
608Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
609 // TODO: emit error on 'int;' or 'const enum foo;'.
610 // TODO: emit error on 'typedef int;'
611 // if (!DS.isMissingDeclaratorOk()) Diag(...);
612
Steve Naroffedafc0b2007-11-17 21:37:36 +0000613 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000614}
615
Steve Narofff0b23542008-01-10 22:15:12 +0000616bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000617 // Get the type before calling CheckSingleAssignmentConstraints(), since
618 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000619 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000620
Chris Lattner005ed752008-01-04 18:04:52 +0000621 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
622 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
623 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000624}
625
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000626bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000627 const ArrayType *AT = Context.getAsArrayType(DeclT);
628
629 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000630 // C99 6.7.8p14. We have an array of character type with unknown size
631 // being initialized to a string literal.
632 llvm::APSInt ConstVal(32);
633 ConstVal = strLiteral->getByteLength() + 1;
634 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000635 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000636 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000637 } else {
638 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000639 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000640 // FIXME: Avoid truncation for 64-bit length strings.
641 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000642 Diag(strLiteral->getSourceRange().getBegin(),
643 diag::warn_initializer_string_for_char_array_too_long,
644 strLiteral->getSourceRange());
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000645 }
646 // Set type from "char *" to "constant array of char".
647 strLiteral->setType(DeclT);
648 // For now, we always return false (meaning success).
649 return false;
650}
651
652StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000653 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +0000654 if (AT && AT->getElementType()->isCharType()) {
655 return dyn_cast<StringLiteral>(Init);
656 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000657 return 0;
658}
659
Douglas Gregor6428e762008-11-05 15:29:30 +0000660bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
661 SourceLocation InitLoc,
662 std::string InitEntity) {
Douglas Gregor81c29152008-10-29 00:13:59 +0000663 // C++ [dcl.init.ref]p1:
664 // A variable declared to be a T&, that is “reference to type T”
665 // (8.3.2), shall be initialized by an object, or function, of
666 // type T or by an object that can be converted into a T.
667 if (DeclType->isReferenceType())
668 return CheckReferenceInit(Init, DeclType);
669
Steve Naroff8e9337f2008-01-21 23:53:58 +0000670 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
671 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +0000672 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Douglas Gregor6428e762008-11-05 15:29:30 +0000673 return Diag(InitLoc,
Steve Naroff8e9337f2008-01-21 23:53:58 +0000674 diag::err_variable_object_no_init,
675 VAT->getSizeExpr()->getSourceRange());
676
Steve Naroffcb69fb72007-12-10 22:44:33 +0000677 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
678 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000679 // FIXME: Handle wide strings
680 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
681 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000682
Douglas Gregor6428e762008-11-05 15:29:30 +0000683 // C++ [dcl.init]p14:
684 // -- If the destination type is a (possibly cv-qualified) class
685 // type:
686 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
687 QualType DeclTypeC = Context.getCanonicalType(DeclType);
688 QualType InitTypeC = Context.getCanonicalType(Init->getType());
689
690 // -- If the initialization is direct-initialization, or if it is
691 // copy-initialization where the cv-unqualified version of the
692 // source type is the same class as, or a derived class of, the
693 // class of the destination, constructors are considered.
694 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
695 IsDerivedFrom(InitTypeC, DeclTypeC)) {
696 CXXConstructorDecl *Constructor
697 = PerformInitializationByConstructor(DeclType, &Init, 1,
698 InitLoc, Init->getSourceRange(),
699 InitEntity, IK_Copy);
700 return Constructor == 0;
701 }
702
703 // -- Otherwise (i.e., for the remaining copy-initialization
704 // cases), user-defined conversion sequences that can
705 // convert from the source type to the destination type or
706 // (when a conversion function is used) to a derived class
707 // thereof are enumerated as described in 13.3.1.4, and the
708 // best one is chosen through overload resolution
709 // (13.3). If the conversion cannot be done or is
710 // ambiguous, the initialization is ill-formed. The
711 // function selected is called with the initializer
712 // expression as its argument; if the function is a
713 // constructor, the call initializes a temporary of the
714 // destination type.
715 // FIXME: We're pretending to do copy elision here; return to
716 // this when we have ASTs for such things.
Chris Lattner70b93d82008-11-18 22:52:51 +0000717 if (!PerformImplicitConversion(Init, DeclType))
Douglas Gregor6428e762008-11-05 15:29:30 +0000718 return false;
Chris Lattner70b93d82008-11-18 22:52:51 +0000719
720 return Diag(InitLoc, diag::err_typecheck_convert_incompatible)
721 << DeclType.getAsString() << InitEntity << "initializing"
722 << Init->getSourceRange();
Douglas Gregor6428e762008-11-05 15:29:30 +0000723 }
724
Steve Naroffb2f72412008-09-29 20:07:05 +0000725 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +0000726 if (DeclType->isArrayType())
727 return Diag(Init->getLocStart(),
728 diag::err_array_init_list_required,
729 Init->getSourceRange());
730
Steve Narofff0b23542008-01-10 22:15:12 +0000731 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor15e04622008-11-05 16:20:31 +0000732 } else if (getLangOptions().CPlusPlus) {
733 // C++ [dcl.init]p14:
734 // [...] If the class is an aggregate (8.5.1), and the initializer
735 // is a brace-enclosed list, see 8.5.1.
736 //
737 // Note: 8.5.1 is handled below; here, we diagnose the case where
738 // we have an initializer list and a destination type that is not
739 // an aggregate.
740 // FIXME: In C++0x, this is yet another form of initialization.
741 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
742 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
743 if (!ClassDecl->isAggregate())
744 return Diag(InitLoc,
745 diag::err_init_non_aggr_init_list,
746 DeclType.getAsString(),
747 Init->getSourceRange());
748 }
Steve Naroffcb69fb72007-12-10 22:44:33 +0000749 }
Eli Friedman38b7a912008-06-06 19:40:52 +0000750
Steve Naroffc4d4a482008-05-01 22:18:59 +0000751 InitListChecker CheckInitList(this, InitList, DeclType);
752 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +0000753}
754
Douglas Gregor6704b312008-11-17 22:58:34 +0000755/// GetNameForDeclarator - Determine the full declaration name for the
756/// given Declarator.
757DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
758 switch (D.getKind()) {
759 case Declarator::DK_Abstract:
760 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
761 return DeclarationName();
762
763 case Declarator::DK_Normal:
764 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
765 return DeclarationName(D.getIdentifier());
766
767 case Declarator::DK_Constructor: {
768 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
769 Ty = Context.getCanonicalType(Ty);
770 return Context.DeclarationNames.getCXXConstructorName(Ty);
771 }
772
773 case Declarator::DK_Destructor: {
774 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
775 Ty = Context.getCanonicalType(Ty);
776 return Context.DeclarationNames.getCXXDestructorName(Ty);
777 }
778
779 case Declarator::DK_Conversion: {
780 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
781 Ty = Context.getCanonicalType(Ty);
782 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
783 }
Douglas Gregor96a32dd2008-11-18 14:39:36 +0000784
785 case Declarator::DK_Operator:
786 assert(D.getIdentifier() == 0 && "operator names have no identifier");
787 return Context.DeclarationNames.getCXXOperatorName(
788 D.getOverloadedOperator());
Douglas Gregor6704b312008-11-17 22:58:34 +0000789 }
790
791 assert(false && "Unknown name kind");
792 return DeclarationName();
793}
794
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000795Sema::DeclTy *
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000796Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000797 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor6704b312008-11-17 22:58:34 +0000798 DeclarationName Name = GetNameForDeclarator(D);
799
Chris Lattner4b009652007-07-25 00:24:17 +0000800 // All of these full declarators require an identifier. If it doesn't have
801 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor6704b312008-11-17 22:58:34 +0000802 if (!Name) {
Chris Lattnercd61d592008-11-11 06:13:16 +0000803 if (!D.getInvalidType()) // Reject this if we think it is valid.
804 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000805 diag::err_declarator_need_ident)
806 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +0000807 return 0;
808 }
809
Chris Lattnera7549902007-08-26 06:24:45 +0000810 // The scope passed in may not be a decl scope. Zip up the scope tree until
811 // we find one that is.
812 while ((S->getFlags() & Scope::DeclScope) == 0)
813 S = S->getParent();
814
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000815 DeclContext *DC;
816 Decl *PrevDecl;
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000817 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000818 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000819
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000820 // See if this is a redefinition of a variable in the same scope.
821 if (!D.getCXXScopeSpec().isSet()) {
822 DC = CurContext;
Douglas Gregor6704b312008-11-17 22:58:34 +0000823 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000824 } else { // Something like "int foo::x;"
825 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor6704b312008-11-17 22:58:34 +0000826 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000827
828 // C++ 7.3.1.2p2:
829 // Members (including explicit specializations of templates) of a named
830 // namespace can also be defined outside that namespace by explicit
831 // qualification of the name being defined, provided that the entity being
832 // defined was already declared in the namespace and the definition appears
833 // after the point of declaration in a namespace that encloses the
834 // declarations namespace.
835 //
836 if (PrevDecl == 0) {
837 // No previous declaration in the qualifying scope.
838 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member,
Douglas Gregor6704b312008-11-17 22:58:34 +0000839 Name.getAsString(), D.getCXXScopeSpec().getRange());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000840 } else if (!CurContext->Encloses(DC)) {
841 // The qualifying scope doesn't enclose the original declaration.
842 // Emit diagnostic based on current scope.
843 SourceLocation L = D.getIdentifierLoc();
844 SourceRange R = D.getCXXScopeSpec().getRange();
845 if (isa<FunctionDecl>(CurContext)) {
Douglas Gregor6704b312008-11-17 22:58:34 +0000846 Diag(L, diag::err_invalid_declarator_in_function, Name.getAsString(),
847 R);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000848 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000849 Diag(L, diag::err_invalid_declarator_scope)
850 << Name.getAsString() << cast<NamedDecl>(DC)->getName() << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000851 }
852 }
853 }
854
Douglas Gregor1d661552008-04-13 21:07:44 +0000855 // In C++, the previous declaration we find might be a tag type
856 // (class or enum). In this case, the new declaration will hide the
857 // tag type.
858 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
859 PrevDecl = 0;
860
Chris Lattner82bb4792007-11-14 06:34:38 +0000861 QualType R = GetTypeForDeclarator(D, S);
862 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
863
Chris Lattner4b009652007-07-25 00:24:17 +0000864 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000865 // Check that there are no default arguments (C++ only).
866 if (getLangOptions().CPlusPlus)
867 CheckExtraCXXDefaultArguments(D);
868
Chris Lattner82bb4792007-11-14 06:34:38 +0000869 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000870 if (!NewTD) return 0;
871
872 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000873 ProcessDeclAttributes(NewTD, D);
Steve Narofff8a09432008-01-09 23:34:55 +0000874 // Merge the decl with the existing one if appropriate. If the decl is
875 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000876 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000877 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
878 if (NewTD == 0) return 0;
879 }
880 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000881 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000882 // C99 6.7.7p2: If a typedef name specifies a variably modified type
883 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000884 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
885 // FIXME: Diagnostic needs to be fixed.
886 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff5eb879b2007-08-31 17:20:07 +0000887 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000888 }
889 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000890 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000891 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000892 switch (D.getDeclSpec().getStorageClassSpec()) {
893 default: assert(0 && "Unknown storage class!");
894 case DeclSpec::SCS_auto:
895 case DeclSpec::SCS_register:
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000896 case DeclSpec::SCS_mutable:
Chris Lattner4b009652007-07-25 00:24:17 +0000897 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
898 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000899 InvalidDecl = true;
900 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000901 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
902 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
903 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000904 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000905 }
906
Chris Lattner4c7802b2008-03-15 21:24:04 +0000907 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000908 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000909 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
910
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000911 FunctionDecl *NewFD;
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000912 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000913 // This is a C++ constructor declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000914 assert(DC->isCXXRecord() &&
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000915 "Constructors can only be declared in a member context");
916
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000917 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000918
919 // Create the new declaration
920 NewFD = CXXConstructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000921 cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +0000922 D.getIdentifierLoc(), Name, R,
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000923 isExplicit, isInline,
924 /*isImplicitlyDeclared=*/false);
925
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000926 if (isInvalidDecl)
927 NewFD->setInvalidDecl();
928 } else if (D.getKind() == Declarator::DK_Destructor) {
929 // This is a C++ destructor declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000930 if (DC->isCXXRecord()) {
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000931 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000932
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000933 NewFD = CXXDestructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000934 cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +0000935 D.getIdentifierLoc(), Name, R,
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000936 isInline,
937 /*isImplicitlyDeclared=*/false);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000938
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000939 if (isInvalidDecl)
940 NewFD->setInvalidDecl();
941 } else {
942 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
943 // Create a FunctionDecl to satisfy the function definition parsing
944 // code path.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000945 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor6704b312008-11-17 22:58:34 +0000946 Name, R, SC, isInline, LastDeclarator,
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000947 // FIXME: Move to DeclGroup...
948 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000949 NewFD->setInvalidDecl();
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000950 }
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000951 } else if (D.getKind() == Declarator::DK_Conversion) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000952 if (!DC->isCXXRecord()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000953 Diag(D.getIdentifierLoc(),
954 diag::err_conv_function_not_member);
955 return 0;
956 } else {
957 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
958
959 NewFD = CXXConversionDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000960 cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +0000961 D.getIdentifierLoc(), Name, R,
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000962 isInline, isExplicit);
963
964 if (isInvalidDecl)
965 NewFD->setInvalidDecl();
966 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000967 } else if (DC->isCXXRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000968 // This is a C++ method declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000969 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +0000970 D.getIdentifierLoc(), Name, R,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000971 (SC == FunctionDecl::Static), isInline,
972 LastDeclarator);
973 } else {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000974 NewFD = FunctionDecl::Create(Context, DC,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000975 D.getIdentifierLoc(),
Douglas Gregor6704b312008-11-17 22:58:34 +0000976 Name, R, SC, isInline, LastDeclarator,
Steve Naroff71cd7762008-10-03 00:02:03 +0000977 // FIXME: Move to DeclGroup...
978 D.getDeclSpec().getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000979 }
Ted Kremenek117f1862008-02-27 22:18:07 +0000980 // Handle attributes.
Chris Lattner9b384ca2008-06-29 00:02:00 +0000981 ProcessDeclAttributes(NewFD, D);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000982
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000983 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000984 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000985 // The parser guarantees this is a string.
986 StringLiteral *SE = cast<StringLiteral>(E);
987 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
988 SE->getByteLength())));
989 }
990
Chris Lattner3e254fb2008-04-08 04:40:51 +0000991 // Copy the parameter declarations from the declarator D to
992 // the function declaration NewFD, if they are available.
Eli Friedman769e7302008-08-25 21:31:01 +0000993 if (D.getNumTypeObjects() > 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000994 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
995
996 // Create Decl objects for each parameter, adding them to the
997 // FunctionDecl.
998 llvm::SmallVector<ParmVarDecl*, 16> Params;
999
1000 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1001 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +00001002 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +00001003 // We let through "const void" here because Sema::GetTypeForDeclarator
1004 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001005 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1006 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +00001007 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1008 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +00001009 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1010
Chris Lattnerda7b5f02008-04-10 02:26:16 +00001011 // In C++, the empty parameter-type-list must be spelled "void"; a
1012 // typedef of void is not permitted.
1013 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +00001014 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +00001015 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1016 }
Eli Friedman769e7302008-08-25 21:31:01 +00001017 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001018 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1019 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1020 }
1021
1022 NewFD->setParams(&Params[0], Params.size());
Douglas Gregorba3e8b72008-10-24 18:09:54 +00001023 } else if (R->getAsTypedefType()) {
1024 // When we're declaring a function with a typedef, as in the
1025 // following example, we'll need to synthesize (unnamed)
1026 // parameters for use in the declaration.
1027 //
1028 // @code
1029 // typedef void fn(int);
1030 // fn f;
1031 // @endcode
1032 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1033 if (!FT) {
1034 // This is a typedef of a function with no prototype, so we
1035 // don't need to do anything.
1036 } else if ((FT->getNumArgs() == 0) ||
1037 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1038 FT->getArgType(0)->isVoidType())) {
1039 // This is a zero-argument function. We don't need to do anything.
1040 } else {
1041 // Synthesize a parameter for each argument type.
1042 llvm::SmallVector<ParmVarDecl*, 16> Params;
1043 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1044 ArgType != FT->arg_type_end(); ++ArgType) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001045 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregorba3e8b72008-10-24 18:09:54 +00001046 SourceLocation(), 0,
1047 *ArgType, VarDecl::None,
1048 0, 0));
1049 }
1050
1051 NewFD->setParams(&Params[0], Params.size());
1052 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001053 }
1054
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001055 // C++ constructors and destructors are handled by separate
1056 // routines, since they don't require any declaration merging (C++
1057 // [class.mfct]p2) and they aren't ever pushed into scope, because
1058 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
1059 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1060 return ActOnConstructorDeclarator(Constructor);
1061 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
1062 return ActOnDestructorDeclarator(Destructor);
Douglas Gregorb0212bd2008-11-17 20:34:05 +00001063
1064 // Extra checking for conversion functions, including recording
1065 // the conversion function in its class.
1066 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1067 ActOnConversionDeclarator(Conversion);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001068
Douglas Gregore60e5d32008-11-06 22:13:31 +00001069 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1070 if (NewFD->isOverloadedOperator() &&
1071 CheckOverloadedOperatorDeclaration(NewFD))
1072 NewFD->setInvalidDecl();
1073
Steve Narofff8a09432008-01-09 23:34:55 +00001074 // Merge the decl with the existing one if appropriate. Since C functions
1075 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001076 if (PrevDecl &&
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001077 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregor42214c52008-04-21 02:02:58 +00001078 bool Redeclaration = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001079
1080 // If C++, determine whether NewFD is an overload of PrevDecl or
1081 // a declaration that requires merging. If it's an overload,
1082 // there's no more work to do here; we'll just add the new
1083 // function to the scope.
1084 OverloadedFunctionDecl::function_iterator MatchedDecl;
1085 if (!getLangOptions().CPlusPlus ||
1086 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1087 Decl *OldDecl = PrevDecl;
1088
1089 // If PrevDecl was an overloaded function, extract the
1090 // FunctionDecl that matched.
1091 if (isa<OverloadedFunctionDecl>(PrevDecl))
1092 OldDecl = *MatchedDecl;
1093
1094 // NewFD and PrevDecl represent declarations that need to be
1095 // merged.
1096 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1097
1098 if (NewFD == 0) return 0;
1099 if (Redeclaration) {
1100 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1101
1102 if (OldDecl == PrevDecl) {
1103 // Remove the name binding for the previous
1104 // declaration. We'll add the binding back later, but then
1105 // it will refer to the new declaration (which will
1106 // contain more information).
1107 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1108 } else {
1109 // We need to update the OverloadedFunctionDecl with the
1110 // latest declaration of this function, so that name
1111 // lookup will always refer to the latest declaration of
1112 // this function.
1113 *MatchedDecl = NewFD;
1114
1115 // Add the redeclaration to the current scope, since we'll
1116 // be skipping PushOnScopeChains.
1117 S->AddDecl(NewFD);
1118
1119 return NewFD;
1120 }
1121 }
Douglas Gregor42214c52008-04-21 02:02:58 +00001122 }
Chris Lattner4b009652007-07-25 00:24:17 +00001123 }
1124 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001125
1126 // In C++, check default arguments now that we have merged decls.
1127 if (getLangOptions().CPlusPlus)
1128 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +00001129 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001130 // Check that there are no default arguments (C++ only).
1131 if (getLangOptions().CPlusPlus)
1132 CheckExtraCXXDefaultArguments(D);
1133
Ted Kremenek42730c52008-01-07 19:49:32 +00001134 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001135 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
1136 D.getIdentifier()->getName());
1137 InvalidDecl = true;
1138 }
Chris Lattner4b009652007-07-25 00:24:17 +00001139
1140 VarDecl *NewVD;
1141 VarDecl::StorageClass SC;
1142 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +00001143 default: assert(0 && "Unknown storage class!");
1144 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1145 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1146 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1147 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1148 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1149 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001150 case DeclSpec::SCS_mutable:
1151 // mutable can only appear on non-static class members, so it's always
1152 // an error here
1153 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1154 InvalidDecl = true;
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +00001155 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001156 }
Douglas Gregor6704b312008-11-17 22:58:34 +00001157
1158 IdentifierInfo *II = Name.getAsIdentifierInfo();
1159 if (!II) {
1160 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name,
1161 Name.getAsString());
1162 return 0;
1163 }
1164
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001165 if (DC->isCXXRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001166 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1167 // This is a static data member for a C++ class.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001168 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001169 D.getIdentifierLoc(), II,
1170 R, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +00001171 } else {
Daniel Dunbar5eea5622008-09-08 20:05:47 +00001172 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001173 if (S->getFnParent() == 0) {
1174 // C99 6.9p2: The storage-class specifiers auto and register shall not
1175 // appear in the declaration specifiers in an external declaration.
1176 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1177 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
1178 R.getAsString());
1179 InvalidDecl = true;
1180 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001181 }
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001182 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1183 II, R, SC, LastDeclarator,
1184 // FIXME: Move to DeclGroup...
1185 D.getDeclSpec().getSourceRange().getBegin());
1186 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroffcae537d2007-08-28 18:45:29 +00001187 }
Chris Lattner4b009652007-07-25 00:24:17 +00001188 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +00001189 ProcessDeclAttributes(NewVD, D);
Nate Begemanea583262008-03-14 18:07:10 +00001190
Daniel Dunbarced89142008-08-06 00:03:29 +00001191 // Handle GNU asm-label extension (encoded as an attribute).
1192 if (Expr *E = (Expr*) D.getAsmLabel()) {
1193 // The parser guarantees this is a string.
1194 StringLiteral *SE = cast<StringLiteral>(E);
1195 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1196 SE->getByteLength())));
1197 }
1198
Nate Begemanea583262008-03-14 18:07:10 +00001199 // Emit an error if an address space was applied to decl with local storage.
1200 // This includes arrays of objects with address space qualifiers, but not
1201 // automatic variables that point to other address spaces.
1202 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +00001203 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1204 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1205 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +00001206 }
Steve Narofff8a09432008-01-09 23:34:55 +00001207 // Merge the decl with the existing one if appropriate. If the decl is
1208 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001209 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001210 NewVD = MergeVarDecl(NewVD, PrevDecl);
1211 if (NewVD == 0) return 0;
1212 }
Chris Lattner4b009652007-07-25 00:24:17 +00001213 New = NewVD;
1214 }
1215
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00001216 // Set the lexical context. If the declarator has a C++ scope specifier, the
1217 // lexical context will be different from the semantic context.
1218 New->setLexicalDeclContext(CurContext);
1219
Chris Lattner4b009652007-07-25 00:24:17 +00001220 // If this has an identifier, add it to the scope stack.
Douglas Gregor6704b312008-11-17 22:58:34 +00001221 if (Name)
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001222 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001223 // If any semantic error occurred, mark the decl as invalid.
1224 if (D.getInvalidType() || InvalidDecl)
1225 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001226
1227 return New;
1228}
1229
Steve Narofffc08f5e2008-10-27 11:34:16 +00001230void Sema::InitializerElementNotConstant(const Expr *Init) {
1231 Diag(Init->getExprLoc(),
1232 diag::err_init_element_not_constant, Init->getSourceRange());
1233}
1234
Eli Friedman02c22ce2008-05-20 13:48:25 +00001235bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1236 switch (Init->getStmtClass()) {
1237 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001238 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001239 return true;
1240 case Expr::ParenExprClass: {
1241 const ParenExpr* PE = cast<ParenExpr>(Init);
1242 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1243 }
1244 case Expr::CompoundLiteralExprClass:
1245 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1246 case Expr::DeclRefExprClass: {
1247 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001248 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1249 if (VD->hasGlobalStorage())
1250 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001251 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001252 return true;
1253 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001254 if (isa<FunctionDecl>(D))
1255 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001256 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001257 return true;
1258 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001259 case Expr::MemberExprClass: {
1260 const MemberExpr *M = cast<MemberExpr>(Init);
1261 if (M->isArrow())
1262 return CheckAddressConstantExpression(M->getBase());
1263 return CheckAddressConstantExpressionLValue(M->getBase());
1264 }
1265 case Expr::ArraySubscriptExprClass: {
1266 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1267 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1268 return CheckAddressConstantExpression(ASE->getBase()) ||
1269 CheckArithmeticConstantExpression(ASE->getIdx());
1270 }
1271 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001272 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001273 return false;
1274 case Expr::UnaryOperatorClass: {
1275 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1276
1277 // C99 6.6p9
1278 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001279 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001280
Steve Narofffc08f5e2008-10-27 11:34:16 +00001281 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001282 return true;
1283 }
1284 }
1285}
1286
1287bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1288 switch (Init->getStmtClass()) {
1289 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001290 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001291 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001292 case Expr::ParenExprClass:
1293 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001294 case Expr::StringLiteralClass:
1295 case Expr::ObjCStringLiteralClass:
1296 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001297 case Expr::CallExprClass:
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001298 case Expr::CXXOperatorCallExprClass:
Chris Lattner0903cba2008-10-06 07:26:43 +00001299 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1300 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1301 Builtin::BI__builtin___CFStringMakeConstantString)
1302 return false;
1303
Steve Narofffc08f5e2008-10-27 11:34:16 +00001304 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001305 return true;
1306
Eli Friedman02c22ce2008-05-20 13:48:25 +00001307 case Expr::UnaryOperatorClass: {
1308 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1309
1310 // C99 6.6p9
1311 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1312 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1313
1314 if (Exp->getOpcode() == UnaryOperator::Extension)
1315 return CheckAddressConstantExpression(Exp->getSubExpr());
1316
Steve Narofffc08f5e2008-10-27 11:34:16 +00001317 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001318 return true;
1319 }
1320 case Expr::BinaryOperatorClass: {
1321 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1322 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1323
1324 Expr *PExp = Exp->getLHS();
1325 Expr *IExp = Exp->getRHS();
1326 if (IExp->getType()->isPointerType())
1327 std::swap(PExp, IExp);
1328
1329 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1330 return CheckAddressConstantExpression(PExp) ||
1331 CheckArithmeticConstantExpression(IExp);
1332 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001333 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001334 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001335 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001336 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1337 // Check for implicit promotion
1338 if (SubExpr->getType()->isFunctionType() ||
1339 SubExpr->getType()->isArrayType())
1340 return CheckAddressConstantExpressionLValue(SubExpr);
1341 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001342
1343 // Check for pointer->pointer cast
1344 if (SubExpr->getType()->isPointerType())
1345 return CheckAddressConstantExpression(SubExpr);
1346
Eli Friedman1fad3c62008-08-25 20:46:57 +00001347 if (SubExpr->getType()->isIntegralType()) {
1348 // Check for the special-case of a pointer->int->pointer cast;
1349 // this isn't standard, but some code requires it. See
1350 // PR2720 for an example.
1351 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1352 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1353 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1354 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1355 if (IntWidth >= PointerWidth) {
1356 return CheckAddressConstantExpression(SubCast->getSubExpr());
1357 }
1358 }
1359 }
1360 }
1361 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001362 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001363 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001364
Steve Narofffc08f5e2008-10-27 11:34:16 +00001365 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001366 return true;
1367 }
1368 case Expr::ConditionalOperatorClass: {
1369 // FIXME: Should we pedwarn here?
1370 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1371 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001372 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001373 return true;
1374 }
1375 if (CheckArithmeticConstantExpression(Exp->getCond()))
1376 return true;
1377 if (Exp->getLHS() &&
1378 CheckAddressConstantExpression(Exp->getLHS()))
1379 return true;
1380 return CheckAddressConstantExpression(Exp->getRHS());
1381 }
1382 case Expr::AddrLabelExprClass:
1383 return false;
1384 }
1385}
1386
Eli Friedman998dffb2008-06-09 05:05:07 +00001387static const Expr* FindExpressionBaseAddress(const Expr* E);
1388
1389static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1390 switch (E->getStmtClass()) {
1391 default:
1392 return E;
1393 case Expr::ParenExprClass: {
1394 const ParenExpr* PE = cast<ParenExpr>(E);
1395 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1396 }
1397 case Expr::MemberExprClass: {
1398 const MemberExpr *M = cast<MemberExpr>(E);
1399 if (M->isArrow())
1400 return FindExpressionBaseAddress(M->getBase());
1401 return FindExpressionBaseAddressLValue(M->getBase());
1402 }
1403 case Expr::ArraySubscriptExprClass: {
1404 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1405 return FindExpressionBaseAddress(ASE->getBase());
1406 }
1407 case Expr::UnaryOperatorClass: {
1408 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1409
1410 if (Exp->getOpcode() == UnaryOperator::Deref)
1411 return FindExpressionBaseAddress(Exp->getSubExpr());
1412
1413 return E;
1414 }
1415 }
1416}
1417
1418static const Expr* FindExpressionBaseAddress(const Expr* E) {
1419 switch (E->getStmtClass()) {
1420 default:
1421 return E;
1422 case Expr::ParenExprClass: {
1423 const ParenExpr* PE = cast<ParenExpr>(E);
1424 return FindExpressionBaseAddress(PE->getSubExpr());
1425 }
1426 case Expr::UnaryOperatorClass: {
1427 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1428
1429 // C99 6.6p9
1430 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1431 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1432
1433 if (Exp->getOpcode() == UnaryOperator::Extension)
1434 return FindExpressionBaseAddress(Exp->getSubExpr());
1435
1436 return E;
1437 }
1438 case Expr::BinaryOperatorClass: {
1439 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1440
1441 Expr *PExp = Exp->getLHS();
1442 Expr *IExp = Exp->getRHS();
1443 if (IExp->getType()->isPointerType())
1444 std::swap(PExp, IExp);
1445
1446 return FindExpressionBaseAddress(PExp);
1447 }
1448 case Expr::ImplicitCastExprClass: {
1449 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1450
1451 // Check for implicit promotion
1452 if (SubExpr->getType()->isFunctionType() ||
1453 SubExpr->getType()->isArrayType())
1454 return FindExpressionBaseAddressLValue(SubExpr);
1455
1456 // Check for pointer->pointer cast
1457 if (SubExpr->getType()->isPointerType())
1458 return FindExpressionBaseAddress(SubExpr);
1459
1460 // We assume that we have an arithmetic expression here;
1461 // if we don't, we'll figure it out later
1462 return 0;
1463 }
Douglas Gregor035d0882008-10-28 15:36:24 +00001464 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001465 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1466
1467 // Check for pointer->pointer cast
1468 if (SubExpr->getType()->isPointerType())
1469 return FindExpressionBaseAddress(SubExpr);
1470
1471 // We assume that we have an arithmetic expression here;
1472 // if we don't, we'll figure it out later
1473 return 0;
1474 }
1475 }
1476}
1477
Eli Friedman02c22ce2008-05-20 13:48:25 +00001478bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1479 switch (Init->getStmtClass()) {
1480 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001481 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001482 return true;
1483 case Expr::ParenExprClass: {
1484 const ParenExpr* PE = cast<ParenExpr>(Init);
1485 return CheckArithmeticConstantExpression(PE->getSubExpr());
1486 }
1487 case Expr::FloatingLiteralClass:
1488 case Expr::IntegerLiteralClass:
1489 case Expr::CharacterLiteralClass:
1490 case Expr::ImaginaryLiteralClass:
1491 case Expr::TypesCompatibleExprClass:
1492 case Expr::CXXBoolLiteralExprClass:
1493 return false;
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001494 case Expr::CallExprClass:
1495 case Expr::CXXOperatorCallExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001496 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001497
1498 // Allow any constant foldable calls to builtins.
1499 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001500 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001501
Steve Narofffc08f5e2008-10-27 11:34:16 +00001502 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001503 return true;
1504 }
1505 case Expr::DeclRefExprClass: {
1506 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1507 if (isa<EnumConstantDecl>(D))
1508 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001509 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001510 return true;
1511 }
1512 case Expr::CompoundLiteralExprClass:
1513 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1514 // but vectors are allowed to be magic.
1515 if (Init->getType()->isVectorType())
1516 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001517 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001518 return true;
1519 case Expr::UnaryOperatorClass: {
1520 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1521
1522 switch (Exp->getOpcode()) {
1523 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1524 // See C99 6.6p3.
1525 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001526 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001527 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001528 case UnaryOperator::OffsetOf:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001529 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1530 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001531 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001532 return true;
1533 case UnaryOperator::Extension:
1534 case UnaryOperator::LNot:
1535 case UnaryOperator::Plus:
1536 case UnaryOperator::Minus:
1537 case UnaryOperator::Not:
1538 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1539 }
1540 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001541 case Expr::SizeOfAlignOfExprClass: {
1542 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001543 // Special check for void types, which are allowed as an extension
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001544 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedman02c22ce2008-05-20 13:48:25 +00001545 return false;
1546 // alignof always evaluates to a constant.
1547 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001548 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001549 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001550 return true;
1551 }
1552 return false;
1553 }
1554 case Expr::BinaryOperatorClass: {
1555 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1556
1557 if (Exp->getLHS()->getType()->isArithmeticType() &&
1558 Exp->getRHS()->getType()->isArithmeticType()) {
1559 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1560 CheckArithmeticConstantExpression(Exp->getRHS());
1561 }
1562
Eli Friedman998dffb2008-06-09 05:05:07 +00001563 if (Exp->getLHS()->getType()->isPointerType() &&
1564 Exp->getRHS()->getType()->isPointerType()) {
1565 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1566 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1567
1568 // Only allow a null (constant integer) base; we could
1569 // allow some additional cases if necessary, but this
1570 // is sufficient to cover offsetof-like constructs.
1571 if (!LHSBase && !RHSBase) {
1572 return CheckAddressConstantExpression(Exp->getLHS()) ||
1573 CheckAddressConstantExpression(Exp->getRHS());
1574 }
1575 }
1576
Steve Narofffc08f5e2008-10-27 11:34:16 +00001577 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001578 return true;
1579 }
1580 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001581 case Expr::CStyleCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001582 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00001583 if (SubExpr->getType()->isArithmeticType())
1584 return CheckArithmeticConstantExpression(SubExpr);
1585
Eli Friedman266df142008-09-02 09:37:00 +00001586 if (SubExpr->getType()->isPointerType()) {
1587 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1588 // If the pointer has a null base, this is an offsetof-like construct
1589 if (!Base)
1590 return CheckAddressConstantExpression(SubExpr);
1591 }
1592
Steve Narofffc08f5e2008-10-27 11:34:16 +00001593 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00001594 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001595 }
1596 case Expr::ConditionalOperatorClass: {
1597 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00001598
1599 // If GNU extensions are disabled, we require all operands to be arithmetic
1600 // constant expressions.
1601 if (getLangOptions().NoExtensions) {
1602 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1603 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1604 CheckArithmeticConstantExpression(Exp->getRHS());
1605 }
1606
1607 // Otherwise, we have to emulate some of the behavior of fold here.
1608 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1609 // because it can constant fold things away. To retain compatibility with
1610 // GCC code, we see if we can fold the condition to a constant (which we
1611 // should always be able to do in theory). If so, we only require the
1612 // specified arm of the conditional to be a constant. This is a horrible
1613 // hack, but is require by real world code that uses __builtin_constant_p.
1614 APValue Val;
Chris Lattneref069662008-11-16 21:24:15 +00001615 if (!Exp->getCond()->Evaluate(Val, Context)) {
1616 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner94d45412008-10-06 05:42:39 +00001617 // won't be able to either. Use it to emit the diagnostic though.
1618 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattneref069662008-11-16 21:24:15 +00001619 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner94d45412008-10-06 05:42:39 +00001620 return Res;
1621 }
1622
1623 // Verify that the side following the condition is also a constant.
1624 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1625 if (Val.getInt() == 0)
1626 std::swap(TrueSide, FalseSide);
1627
1628 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001629 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00001630
1631 // Okay, the evaluated side evaluates to a constant, so we accept this.
1632 // Check to see if the other side is obviously not a constant. If so,
1633 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001634 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00001635 Diag(Init->getExprLoc(),
1636 diag::ext_typecheck_expression_not_constant_but_accepted,
1637 FalseSide->getSourceRange());
1638 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001639 }
1640 }
1641}
1642
1643bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopese7280452008-07-07 16:46:50 +00001644 Init = Init->IgnoreParens();
1645
Eli Friedman02c22ce2008-05-20 13:48:25 +00001646 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1647 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1648 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1649
Nuno Lopese7280452008-07-07 16:46:50 +00001650 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1651 return CheckForConstantInitializer(e->getInitializer(), DclT);
1652
Eli Friedman02c22ce2008-05-20 13:48:25 +00001653 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1654 unsigned numInits = Exp->getNumInits();
1655 for (unsigned i = 0; i < numInits; i++) {
1656 // FIXME: Need to get the type of the declaration for C++,
1657 // because it could be a reference?
1658 if (CheckForConstantInitializer(Exp->getInit(i),
1659 Exp->getInit(i)->getType()))
1660 return true;
1661 }
1662 return false;
1663 }
1664
1665 if (Init->isNullPointerConstant(Context))
1666 return false;
1667 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001668 QualType InitTy = Context.getCanonicalType(Init->getType())
1669 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00001670 if (InitTy == Context.BoolTy) {
1671 // Special handling for pointers implicitly cast to bool;
1672 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1673 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1674 Expr* SubE = ICE->getSubExpr();
1675 if (SubE->getType()->isPointerType() ||
1676 SubE->getType()->isArrayType() ||
1677 SubE->getType()->isFunctionType()) {
1678 return CheckAddressConstantExpression(Init);
1679 }
1680 }
1681 } else if (InitTy->isIntegralType()) {
1682 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001683 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00001684 SubE = CE->getSubExpr();
1685 // Special check for pointer cast to int; we allow as an extension
1686 // an address constant cast to an integer if the integer
1687 // is of an appropriate width (this sort of code is apparently used
1688 // in some places).
1689 // FIXME: Add pedwarn?
1690 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1691 if (SubE && (SubE->getType()->isPointerType() ||
1692 SubE->getType()->isArrayType() ||
1693 SubE->getType()->isFunctionType())) {
1694 unsigned IntWidth = Context.getTypeSize(Init->getType());
1695 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1696 if (IntWidth >= PointerWidth)
1697 return CheckAddressConstantExpression(Init);
1698 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001699 }
1700
1701 return CheckArithmeticConstantExpression(Init);
1702 }
1703
1704 if (Init->getType()->isPointerType())
1705 return CheckAddressConstantExpression(Init);
1706
Eli Friedman25086f02008-05-30 18:14:48 +00001707 // An array type at the top level that isn't an init-list must
1708 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00001709 if (Init->getType()->isArrayType())
1710 return false;
1711
Nuno Lopes1dc26762008-09-01 18:42:41 +00001712 if (Init->getType()->isFunctionType())
1713 return false;
1714
Steve Naroffdff3fb22008-10-02 17:12:56 +00001715 // Allow block exprs at top level.
1716 if (Init->getType()->isBlockPointerType())
1717 return false;
1718
Steve Narofffc08f5e2008-10-27 11:34:16 +00001719 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001720 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00001721}
1722
Steve Naroff6a0e2092007-09-12 14:07:44 +00001723void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001724 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001725 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001726 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00001727
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001728 // If there is no declaration, there was an error parsing it. Just ignore
1729 // the initializer.
1730 if (RealDecl == 0) {
1731 delete Init;
1732 return;
1733 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001734
Steve Naroff420d0f52007-09-12 20:13:48 +00001735 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1736 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00001737 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1738 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00001739 RealDecl->setInvalidDecl();
1740 return;
1741 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001742 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00001743 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00001744 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001745 if (VDecl->isBlockVarDecl()) {
1746 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001747 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00001748 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001749 VDecl->setInvalidDecl();
1750 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00001751 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1752 VDecl->getName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001753 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00001754
1755 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1756 if (!getLangOptions().CPlusPlus) {
1757 if (SC == VarDecl::Static) // C99 6.7.8p4.
1758 CheckForConstantInitializer(Init, DclT);
1759 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001760 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001761 } else if (VDecl->isFileVarDecl()) {
1762 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00001763 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001764 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00001765 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1766 VDecl->getName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001767 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001768
Anders Carlssonea7140a2008-08-22 05:00:02 +00001769 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1770 if (!getLangOptions().CPlusPlus) {
1771 // C99 6.7.8p4. All file scoped initializers need to be constant.
1772 CheckForConstantInitializer(Init, DclT);
1773 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001774 }
1775 // If the type changed, it means we had an incomplete type that was
1776 // completed by the initializer. For example:
1777 // int ary[] = { 1, 3, 5 };
1778 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00001779 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001780 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00001781 Init->setType(DclT);
1782 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001783
1784 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00001785 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001786 return;
1787}
1788
Douglas Gregor81c29152008-10-29 00:13:59 +00001789void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1790 Decl *RealDecl = static_cast<Decl *>(dcl);
1791
Argiris Kirtzidis9c0e9942008-11-07 13:01:22 +00001792 // If there is no declaration, there was an error parsing it. Just ignore it.
1793 if (RealDecl == 0)
1794 return;
1795
Douglas Gregor81c29152008-10-29 00:13:59 +00001796 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1797 QualType Type = Var->getType();
1798 // C++ [dcl.init.ref]p3:
1799 // The initializer can be omitted for a reference only in a
1800 // parameter declaration (8.3.5), in the declaration of a
1801 // function return type, in the declaration of a class member
1802 // within its class declaration (9.2), and where the extern
1803 // specifier is explicitly used.
Douglas Gregor5870a952008-11-03 20:45:27 +00001804 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001805 Diag(Var->getLocation(),
1806 diag::err_reference_var_requires_init,
1807 Var->getName(),
1808 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor5870a952008-11-03 20:45:27 +00001809 Var->setInvalidDecl();
1810 return;
1811 }
1812
1813 // C++ [dcl.init]p9:
1814 //
1815 // If no initializer is specified for an object, and the object
1816 // is of (possibly cv-qualified) non-POD class type (or array
1817 // thereof), the object shall be default-initialized; if the
1818 // object is of const-qualified type, the underlying class type
1819 // shall have a user-declared default constructor.
1820 if (getLangOptions().CPlusPlus) {
1821 QualType InitType = Type;
1822 if (const ArrayType *Array = Context.getAsArrayType(Type))
1823 InitType = Array->getElementType();
1824 if (InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00001825 const CXXConstructorDecl *Constructor
1826 = PerformInitializationByConstructor(InitType, 0, 0,
1827 Var->getLocation(),
1828 SourceRange(Var->getLocation(),
1829 Var->getLocation()),
1830 Var->getName(),
1831 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00001832 if (!Constructor)
1833 Var->setInvalidDecl();
1834 }
1835 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001836
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001837#if 0
1838 // FIXME: Temporarily disabled because we are not properly parsing
1839 // linkage specifications on declarations, e.g.,
1840 //
1841 // extern "C" const CGPoint CGPointerZero;
1842 //
Douglas Gregor81c29152008-10-29 00:13:59 +00001843 // C++ [dcl.init]p9:
1844 //
1845 // If no initializer is specified for an object, and the
1846 // object is of (possibly cv-qualified) non-POD class type (or
1847 // array thereof), the object shall be default-initialized; if
1848 // the object is of const-qualified type, the underlying class
1849 // type shall have a user-declared default
1850 // constructor. Otherwise, if no initializer is specified for
1851 // an object, the object and its subobjects, if any, have an
1852 // indeterminate initial value; if the object or any of its
1853 // subobjects are of const-qualified type, the program is
1854 // ill-formed.
1855 //
1856 // This isn't technically an error in C, so we don't diagnose it.
1857 //
1858 // FIXME: Actually perform the POD/user-defined default
1859 // constructor check.
1860 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001861 Context.getCanonicalType(Type).isConstQualified() &&
1862 Var->getStorageClass() != VarDecl::Extern)
Douglas Gregor81c29152008-10-29 00:13:59 +00001863 Diag(Var->getLocation(),
1864 diag::err_const_var_requires_init,
1865 Var->getName(),
1866 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001867#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00001868 }
1869}
1870
Chris Lattner4b009652007-07-25 00:24:17 +00001871/// The declarators are chained together backwards, reverse the list.
1872Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1873 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001874 Decl *GroupDecl = static_cast<Decl*>(group);
1875 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00001876 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00001877
1878 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1879 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001880 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00001881 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001882 else { // reverse the list.
1883 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001884 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001885 Group->setNextDeclarator(NewGroup);
1886 NewGroup = Group;
1887 Group = Next;
1888 }
1889 }
1890 // Perform semantic analysis that depends on having fully processed both
1891 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001892 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00001893 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1894 if (!IDecl)
1895 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001896 QualType T = IDecl->getType();
1897
1898 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1899 // static storage duration, it shall not have a variable length array.
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001900 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1901 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001902 if (T->isVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001903 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1904 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001905 }
1906 }
1907 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1908 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001909 if (IDecl->isBlockVarDecl() &&
1910 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001911 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +00001912 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1913 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001914 IDecl->setInvalidDecl();
1915 }
1916 }
1917 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1918 // object that has file scope without an initializer, and without a
1919 // storage-class specifier or with the storage-class specifier "static",
1920 // constitutes a tentative definition. Note: A tentative definition with
1921 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00001922 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00001923 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00001924 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1925 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001926 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00001927 // C99 6.9.2p3: If the declaration of an identifier for an object is
1928 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1929 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +00001930 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1931 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001932 IDecl->setInvalidDecl();
1933 }
1934 }
Steve Naroffb5e78152008-08-08 17:50:35 +00001935 if (IDecl->isFileVarDecl())
1936 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001937 }
1938 return NewGroup;
1939}
Steve Naroff91b03f72007-08-28 03:03:08 +00001940
Chris Lattner3e254fb2008-04-08 04:40:51 +00001941/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1942/// to introduce parameters into function prototype scope.
1943Sema::DeclTy *
1944Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001945 // FIXME: disallow CXXScopeSpec for param declarators.
Chris Lattner5e77ade2008-06-26 06:49:43 +00001946 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001947
1948 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00001949 VarDecl::StorageClass StorageClass = VarDecl::None;
1950 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1951 StorageClass = VarDecl::Register;
1952 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001953 Diag(DS.getStorageClassSpecLoc(),
1954 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001955 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001956 }
1957 if (DS.isThreadSpecified()) {
1958 Diag(DS.getThreadSpecLoc(),
1959 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001960 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001961 }
1962
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001963 // Check that there are no default arguments inside the type of this
1964 // parameter (C++ only).
1965 if (getLangOptions().CPlusPlus)
1966 CheckExtraCXXDefaultArguments(D);
1967
Chris Lattner3e254fb2008-04-08 04:40:51 +00001968 // In this context, we *do not* check D.getInvalidType(). If the declarator
1969 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1970 // though it will not reflect the user specified type.
1971 QualType parmDeclType = GetTypeForDeclarator(D, S);
1972
1973 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1974
Chris Lattner4b009652007-07-25 00:24:17 +00001975 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1976 // Can this happen for params? We already checked that they don't conflict
1977 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001978 IdentifierInfo *II = D.getIdentifier();
1979 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1980 if (S->isDeclScope(PrevDecl)) {
1981 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1982 dyn_cast<NamedDecl>(PrevDecl)->getName());
1983
1984 // Recover by removing the name
1985 II = 0;
1986 D.SetIdentifier(0, D.getIdentifierLoc());
1987 }
Chris Lattner4b009652007-07-25 00:24:17 +00001988 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00001989
1990 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1991 // Doing the promotion here has a win and a loss. The win is the type for
1992 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1993 // code generator). The loss is the orginal type isn't preserved. For example:
1994 //
1995 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1996 // int blockvardecl[5];
1997 // sizeof(parmvardecl); // size == 4
1998 // sizeof(blockvardecl); // size == 20
1999 // }
2000 //
2001 // For expressions, all implicit conversions are captured using the
2002 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2003 //
2004 // FIXME: If a source translation tool needs to see the original type, then
2005 // we need to consider storing both types (in ParmVarDecl)...
2006 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00002007 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00002008 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00002009 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00002010 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00002011 parmDeclType = Context.getPointerType(parmDeclType);
2012
Chris Lattner3e254fb2008-04-08 04:40:51 +00002013 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2014 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002015 parmDeclType, StorageClass,
Chris Lattner3e254fb2008-04-08 04:40:51 +00002016 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00002017
Chris Lattner3e254fb2008-04-08 04:40:51 +00002018 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00002019 New->setInvalidDecl();
2020
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002021 if (II)
2022 PushOnScopeChains(New, S);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00002023
Chris Lattner9b384ca2008-06-29 00:02:00 +00002024 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00002025 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002026
Chris Lattner4b009652007-07-25 00:24:17 +00002027}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00002028
Chris Lattnerea148702007-10-09 17:14:05 +00002029Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002030 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00002031 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2032 "Not a function declarator!");
2033 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002034
Chris Lattner4b009652007-07-25 00:24:17 +00002035 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2036 // for a K&R function.
2037 if (!FTI.hasPrototype) {
2038 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002039 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00002040 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
2041 FTI.ArgInfo[i].Ident->getName());
2042 // Implicitly declare the argument as type 'int' for lack of a better
2043 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002044 DeclSpec DS;
2045 const char* PrevSpec; // unused
2046 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2047 PrevSpec);
2048 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2049 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2050 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00002051 }
2052 }
Chris Lattner4b009652007-07-25 00:24:17 +00002053 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002054 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00002055 }
2056
2057 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00002058
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002059 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002060 ActOnDeclarator(GlobalScope, D, 0));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002061}
2062
2063Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2064 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00002065 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00002066
2067 // See if this is a redefinition.
2068 const FunctionDecl *Definition;
2069 if (FD->getBody(Definition)) {
2070 Diag(FD->getLocation(), diag::err_redefinition,
2071 FD->getName());
2072 Diag(Definition->getLocation(), diag::err_previous_definition);
2073 }
2074
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002075 PushDeclContext(FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00002076
2077 // Check the validity of our function parameters
2078 CheckParmsForFunctionDef(FD);
2079
2080 // Introduce our parameters into the function scope
2081 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2082 ParmVarDecl *Param = FD->getParamDecl(p);
2083 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002084 if (Param->getIdentifier())
2085 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00002086 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002087
Chris Lattner4b009652007-07-25 00:24:17 +00002088 return FD;
2089}
2090
Steve Naroff99ee4302007-11-11 23:20:51 +00002091Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
2092 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002093 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002094 FD->setBody((Stmt*)Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002095 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00002096 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002097 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002098 } else
2099 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002100 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00002101 // Verify and clean out per-function state.
2102
2103 // Check goto/label use.
2104 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2105 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2106 // Verify that we have no forward references left. If so, there was a goto
2107 // or address of a label taken, but no definition of it. Label fwd
2108 // definitions are indicated with a null substmt.
2109 if (I->second->getSubStmt() == 0) {
2110 LabelStmt *L = I->second;
2111 // Emit error.
2112 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
2113
2114 // At this point, we have gotos that use the bogus label. Stitch it into
2115 // the function body so that they aren't leaked and that the AST is well
2116 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002117 if (Body) {
2118 L->setSubStmt(new NullStmt(L->getIdentLoc()));
2119 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2120 } else {
2121 // The whole function wasn't parsed correctly, just delete this.
2122 delete L;
2123 }
Chris Lattner4b009652007-07-25 00:24:17 +00002124 }
2125 }
2126 LabelMap.clear();
2127
Steve Naroff99ee4302007-11-11 23:20:51 +00002128 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002129}
2130
Chris Lattner4b009652007-07-25 00:24:17 +00002131/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2132/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00002133ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2134 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002135 // Extension in C99. Legal in C90, but warn about it.
2136 if (getLangOptions().C99)
Chris Lattner4b009652007-07-25 00:24:17 +00002137 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002138 else
Chris Lattner4b009652007-07-25 00:24:17 +00002139 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
2140
2141 // FIXME: handle stuff like:
2142 // void foo() { extern float X(); }
2143 // void bar() { X(); } <-- implicit decl for X in another scope.
2144
2145 // Set a Declarator for the implicit definition: int foo();
2146 const char *Dummy;
2147 DeclSpec DS;
2148 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2149 Error = Error; // Silence warning.
2150 assert(!Error && "Error setting up implicit decl!");
2151 Declarator D(DS, Declarator::BlockContext);
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00002152 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Chris Lattner4b009652007-07-25 00:24:17 +00002153 D.SetIdentifier(&II, Loc);
2154
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002155 // Insert this function into translation-unit scope.
2156
2157 DeclContext *PrevDC = CurContext;
2158 CurContext = Context.getTranslationUnitDecl();
2159
Steve Naroff9104f3c2008-04-04 14:32:09 +00002160 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002161 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002162 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002163
2164 CurContext = PrevDC;
2165
Steve Naroff9104f3c2008-04-04 14:32:09 +00002166 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002167}
2168
2169
Chris Lattner82bb4792007-11-14 06:34:38 +00002170TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00002171 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002172 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002173 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002174
2175 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002176 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2177 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002178 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00002179 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002180 if (D.getInvalidType())
2181 NewTD->setInvalidDecl();
2182 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002183}
2184
Steve Naroff0acc9c92007-09-15 18:49:24 +00002185/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002186/// former case, Name will be non-null. In the later case, Name will be null.
2187/// TagType indicates what kind of tag this is. TK indicates whether this is a
2188/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002189Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00002190 SourceLocation KWLoc, const CXXScopeSpec &SS,
2191 IdentifierInfo *Name, SourceLocation NameLoc,
2192 AttributeList *Attr) {
Chris Lattner4b009652007-07-25 00:24:17 +00002193 // If this is a use of an existing tag, it must have a name.
2194 assert((Name != 0 || TK == TK_Definition) &&
2195 "Nameless record must be a definition!");
2196
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002197 TagDecl::TagKind Kind;
Chris Lattner4b009652007-07-25 00:24:17 +00002198 switch (TagType) {
2199 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002200 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2201 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2202 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2203 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002204 }
2205
Ted Kremenek46a837c2008-09-05 17:16:31 +00002206 // Two code paths: a new one for structs/unions/classes where we create
2207 // separate decls for forward declarations, and an old (eventually to
2208 // be removed) code path for enums.
2209 if (Kind != TagDecl::TK_enum)
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002210 return ActOnTagStruct(S, Kind, TK, KWLoc, SS, Name, NameLoc, Attr);
Ted Kremenek46a837c2008-09-05 17:16:31 +00002211
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002212 DeclContext *DC = CurContext;
2213 ScopedDecl *PrevDecl = 0;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002214
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002215 if (Name && SS.isNotEmpty()) {
2216 // We have a nested-name tag ('struct foo::bar').
2217
2218 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002219 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002220 Name = 0;
2221 goto CreateNewDecl;
2222 }
2223
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002224 DC = static_cast<DeclContext*>(SS.getScopeRep());
2225 // Look-up name inside 'foo::'.
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002226 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2227
2228 // A tag 'foo::bar' must already exist.
2229 if (PrevDecl == 0) {
2230 Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(),
2231 SS.getRange());
2232 Name = 0;
2233 goto CreateNewDecl;
2234 }
2235 } else {
2236 // If this is a named struct, check to see if there was a previous forward
2237 // declaration or definition.
2238 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2239 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2240 }
2241
Ted Kremenekd4434152008-09-02 21:26:19 +00002242 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002243 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2244 "unexpected Decl type");
2245 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002246 // If this is a use of a previous tag, or if the tag is already declared
2247 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002248 // rementions the tag), reuse the decl.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002249 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002250 // Make sure that this wasn't declared as an enum and now used as a
2251 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002252 if (PrevTagDecl->getTagKind() != Kind) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002253 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2254 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002255 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002256 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002257 PrevDecl = 0;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002258 } else {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002259 // If this is a use or a forward declaration, we're good.
2260 if (TK != TK_Definition)
2261 return PrevDecl;
2262
2263 // Diagnose attempts to redefine a tag.
2264 if (PrevTagDecl->isDefinition()) {
2265 Diag(NameLoc, diag::err_redefinition, Name->getName());
2266 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2267 // If this is a redefinition, recover by making this struct be
2268 // anonymous, which will make any later references get the previous
2269 // definition.
2270 Name = 0;
2271 } else {
2272 // Okay, this is definition of a previously declared or referenced
2273 // tag. Move the location of the decl to be the definition site.
2274 PrevDecl->setLocation(NameLoc);
2275 return PrevDecl;
2276 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002277 }
Chris Lattner4b009652007-07-25 00:24:17 +00002278 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002279 // If we get here, this is a definition of a new struct type in a nested
2280 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2281 // type.
2282 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002283 // PrevDecl is a namespace.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002284 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002285 // The tag name clashes with a namespace name, issue an error and
2286 // recover by making this tag be anonymous.
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002287 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2288 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2289 Name = 0;
2290 }
Chris Lattner4b009652007-07-25 00:24:17 +00002291 }
Chris Lattner4b009652007-07-25 00:24:17 +00002292 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002293
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002294 CreateNewDecl:
Chris Lattner4b009652007-07-25 00:24:17 +00002295
2296 // If there is an identifier, use the location of the identifier as the
2297 // location of the decl, otherwise use the location of the struct/union
2298 // keyword.
2299 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2300
2301 // Otherwise, if this is the first time we've seen this tag, create the decl.
2302 TagDecl *New;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002303 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00002304 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2305 // enum X { A, B, C } D; D should chain to X.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002306 New = EnumDecl::Create(Context, DC, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002307 // If this is an undefined enum, warn.
2308 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002309 } else {
2310 // struct/union/class
2311
Chris Lattner4b009652007-07-25 00:24:17 +00002312 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2313 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002314 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002315 // FIXME: Look for a way to use RecordDecl for simple structs.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002316 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002317 else
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002318 New = RecordDecl::Create(Context, Kind, DC, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002319 }
Chris Lattner4b009652007-07-25 00:24:17 +00002320
2321 // If this has an identifier, add it to the scope stack.
2322 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00002323 // The scope passed in may not be a decl scope. Zip up the scope tree until
2324 // we find one that is.
2325 while ((S->getFlags() & Scope::DeclScope) == 0)
2326 S = S->getParent();
2327
2328 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002329 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002330 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00002331
Chris Lattnerd7e83d82008-06-28 23:58:55 +00002332 if (Attr)
2333 ProcessDeclAttributeList(New, Attr);
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00002334
2335 // Set the lexical context. If the tag has a C++ scope specifier, the
2336 // lexical context will be different from the semantic context.
2337 New->setLexicalDeclContext(CurContext);
2338
Chris Lattner4b009652007-07-25 00:24:17 +00002339 return New;
2340}
2341
Ted Kremenek46a837c2008-09-05 17:16:31 +00002342/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2343/// the logic for enums, we create separate decls for forward declarations.
2344/// This is called by ActOnTag, but eventually will replace its logic.
2345Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002346 SourceLocation KWLoc, const CXXScopeSpec &SS,
2347 IdentifierInfo *Name, SourceLocation NameLoc,
2348 AttributeList *Attr) {
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002349 DeclContext *DC = CurContext;
2350 ScopedDecl *PrevDecl = 0;
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002351
2352 if (Name && SS.isNotEmpty()) {
2353 // We have a nested-name tag ('struct foo::bar').
2354
2355 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002356 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002357 Name = 0;
2358 goto CreateNewDecl;
2359 }
2360
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002361 DC = static_cast<DeclContext*>(SS.getScopeRep());
2362 // Look-up name inside 'foo::'.
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002363 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2364
2365 // A tag 'foo::bar' must already exist.
2366 if (PrevDecl == 0) {
2367 Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(),
2368 SS.getRange());
2369 Name = 0;
2370 goto CreateNewDecl;
2371 }
2372 } else {
2373 // If this is a named struct, check to see if there was a previous forward
2374 // declaration or definition.
2375 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2376 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2377 }
Ted Kremenek46a837c2008-09-05 17:16:31 +00002378
2379 if (PrevDecl) {
2380 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2381 "unexpected Decl type");
2382
2383 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2384 // If this is a use of a previous tag, or if the tag is already declared
2385 // in the same scope (so that the definition/declaration completes or
2386 // rementions the tag), reuse the decl.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002387 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002388 // Make sure that this wasn't declared as an enum and now used as a
2389 // struct or something similar.
2390 if (PrevTagDecl->getTagKind() != Kind) {
2391 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2392 Diag(PrevDecl->getLocation(), diag::err_previous_use);
2393 // Recover by making this an anonymous redefinition.
2394 Name = 0;
2395 PrevDecl = 0;
2396 } else {
2397 // If this is a use, return the original decl.
2398
2399 // FIXME: In the future, return a variant or some other clue
2400 // for the consumer of this Decl to know it doesn't own it.
2401 // For our current ASTs this shouldn't be a problem, but will
2402 // need to be changed with DeclGroups.
2403 if (TK == TK_Reference)
2404 return PrevDecl;
2405
2406 // The new decl is a definition?
2407 if (TK == TK_Definition) {
2408 // Diagnose attempts to redefine a tag.
2409 if (RecordDecl* DefRecord =
2410 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
2411 Diag(NameLoc, diag::err_redefinition, Name->getName());
2412 Diag(DefRecord->getLocation(), diag::err_previous_definition);
2413 // If this is a redefinition, recover by making this struct be
2414 // anonymous, which will make any later references get the previous
2415 // definition.
2416 Name = 0;
2417 PrevDecl = 0;
2418 }
2419 // Okay, this is definition of a previously declared or referenced
2420 // tag. We're going to create a new Decl.
2421 }
2422 }
2423 // If we get here we have (another) forward declaration. Just create
2424 // a new decl.
2425 }
2426 else {
2427 // If we get here, this is a definition of a new struct type in a nested
2428 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2429 // new decl/type. We set PrevDecl to NULL so that the Records
2430 // have distinct types.
2431 PrevDecl = 0;
2432 }
2433 } else {
2434 // PrevDecl is a namespace.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002435 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002436 // The tag name clashes with a namespace name, issue an error and
2437 // recover by making this tag be anonymous.
2438 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2439 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2440 Name = 0;
2441 }
2442 }
2443 }
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002444
2445 CreateNewDecl:
2446
Ted Kremenek46a837c2008-09-05 17:16:31 +00002447 // If there is an identifier, use the location of the identifier as the
2448 // location of the decl, otherwise use the location of the struct/union
2449 // keyword.
2450 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2451
2452 // Otherwise, if this is the first time we've seen this tag, create the decl.
2453 TagDecl *New;
2454
2455 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2456 // struct X { int A; } D; D should chain to X.
2457 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002458 // FIXME: Look for a way to use RecordDecl for simple structs.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002459 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek46a837c2008-09-05 17:16:31 +00002460 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2461 else
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002462 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek46a837c2008-09-05 17:16:31 +00002463 dyn_cast_or_null<RecordDecl>(PrevDecl));
2464
2465 // If this has an identifier, add it to the scope stack.
2466 if ((TK == TK_Definition || !PrevDecl) && Name) {
2467 // The scope passed in may not be a decl scope. Zip up the scope tree until
2468 // we find one that is.
2469 while ((S->getFlags() & Scope::DeclScope) == 0)
2470 S = S->getParent();
2471
2472 // Add it to the decl chain.
2473 PushOnScopeChains(New, S);
2474 }
Daniel Dunbar2cb762f2008-10-16 02:34:03 +00002475
2476 // Handle #pragma pack: if the #pragma pack stack has non-default
2477 // alignment, make up a packed attribute for this decl. These
2478 // attributes are checked when the ASTContext lays out the
2479 // structure.
2480 //
2481 // It is important for implementing the correct semantics that this
2482 // happen here (in act on tag decl). The #pragma pack stack is
2483 // maintained as a result of parser callbacks which can occur at
2484 // many points during the parsing of a struct declaration (because
2485 // the #pragma tokens are effectively skipped over during the
2486 // parsing of the struct).
2487 if (unsigned Alignment = PackContext.getAlignment())
2488 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek46a837c2008-09-05 17:16:31 +00002489
2490 if (Attr)
2491 ProcessDeclAttributeList(New, Attr);
2492
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00002493 // Set the lexical context. If the tag has a C++ scope specifier, the
2494 // lexical context will be different from the semantic context.
2495 New->setLexicalDeclContext(CurContext);
2496
Ted Kremenek46a837c2008-09-05 17:16:31 +00002497 return New;
2498}
2499
2500
Chris Lattner1bf58f62008-06-21 19:39:06 +00002501/// Collect the instance variables declared in an Objective-C object. Used in
2502/// the creation of structures from objects using the @defs directive.
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002503static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattnere705e5e2008-07-21 22:17:28 +00002504 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00002505 if (Class->getSuperClass())
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002506 CollectIvars(Class->getSuperClass(), Ctx, ivars);
2507
2508 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremenek40e70e72008-09-03 18:03:35 +00002509 for (ObjCInterfaceDecl::ivar_iterator
2510 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2511
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002512 ObjCIvarDecl* ID = *I;
2513 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2514 ID->getIdentifier(),
2515 ID->getType(),
2516 ID->getBitWidth()));
2517 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002518}
2519
2520/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2521/// instance variables of ClassName into Decls.
2522void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2523 IdentifierInfo *ClassName,
Chris Lattnere705e5e2008-07-21 22:17:28 +00002524 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00002525 // Check that ClassName is a valid class
2526 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2527 if (!Class) {
2528 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
2529 return;
2530 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002531 // Collect the instance variables
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002532 CollectIvars(Class, Context, Decls);
Chris Lattner1bf58f62008-06-21 19:39:06 +00002533}
2534
Chris Lattnera73e2202008-11-12 21:17:48 +00002535/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2536/// types into constant array types in certain situations which would otherwise
2537/// be errors (for GCC compatibility).
2538static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2539 ASTContext &Context) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002540 // This method tries to turn a variable array into a constant
2541 // array even when the size isn't an ICE. This is necessary
2542 // for compatibility with code that depends on gcc's buggy
2543 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002544 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2545 if (!VLATy) return QualType();
2546
2547 APValue Result;
2548 if (!VLATy->getSizeExpr() ||
Chris Lattneref069662008-11-16 21:24:15 +00002549 !VLATy->getSizeExpr()->Evaluate(Result, Context))
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002550 return QualType();
2551
2552 assert(Result.isInt() && "Size expressions must be integers!");
2553 llvm::APSInt &Res = Result.getInt();
2554 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2555 return Context.getConstantArrayType(VLATy->getElementType(),
2556 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002557 return QualType();
2558}
2559
Steve Naroff0acc9c92007-09-15 18:49:24 +00002560/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00002561/// to create a FieldDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002562Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner4b009652007-07-25 00:24:17 +00002563 SourceLocation DeclStart,
2564 Declarator &D, ExprTy *BitfieldWidth) {
2565 IdentifierInfo *II = D.getIdentifier();
2566 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00002567 SourceLocation Loc = DeclStart;
2568 if (II) Loc = D.getIdentifierLoc();
2569
2570 // FIXME: Unnamed fields can be handled in various different ways, for
2571 // example, unnamed unions inject all members into the struct namespace!
Ted Kremenek40e70e72008-09-03 18:03:35 +00002572
Chris Lattner4b009652007-07-25 00:24:17 +00002573 if (BitWidth) {
2574 // TODO: Validate.
2575 //printf("WARNING: BITFIELDS IGNORED!\n");
2576
2577 // 6.7.2.1p3
2578 // 6.7.2.1p4
2579
2580 } else {
2581 // Not a bitfield.
2582
2583 // validate II.
2584
2585 }
2586
2587 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002588 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2589 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00002590
Chris Lattner4b009652007-07-25 00:24:17 +00002591 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2592 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00002593 if (T->isVariablyModifiedType()) {
Chris Lattnera73e2202008-11-12 21:17:48 +00002594 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002595 if (!FixedTy.isNull()) {
Chris Lattner86be8572008-11-13 18:49:38 +00002596 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002597 T = FixedTy;
2598 } else {
Chris Lattner86be8572008-11-13 18:49:38 +00002599 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner2a884752008-11-12 19:45:49 +00002600 T = Context.IntTy;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002601 InvalidDecl = true;
2602 }
Chris Lattner4b009652007-07-25 00:24:17 +00002603 }
Chris Lattner4b009652007-07-25 00:24:17 +00002604 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002605 FieldDecl *NewFD;
2606
2607 if (getLangOptions().CPlusPlus) {
2608 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2609 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +00002610 Loc, II, T,
2611 D.getDeclSpec().getStorageClassSpec() ==
2612 DeclSpec::SCS_mutable, BitWidth);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002613 if (II)
2614 PushOnScopeChains(NewFD, S);
2615 }
2616 else
2617 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff75494892007-09-11 21:17:26 +00002618
Chris Lattner9b384ca2008-06-29 00:02:00 +00002619 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002620
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002621 if (D.getInvalidType() || InvalidDecl)
2622 NewFD->setInvalidDecl();
2623 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00002624}
2625
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002626/// TranslateIvarVisibility - Translate visibility from a token ID to an
2627/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00002628static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002629TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00002630 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00002631 default: assert(0 && "Unknown visitibility kind");
2632 case tok::objc_private: return ObjCIvarDecl::Private;
2633 case tok::objc_public: return ObjCIvarDecl::Public;
2634 case tok::objc_protected: return ObjCIvarDecl::Protected;
2635 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00002636 }
2637}
2638
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002639/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2640/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002641Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002642 SourceLocation DeclStart,
2643 Declarator &D, ExprTy *BitfieldWidth,
2644 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002645 IdentifierInfo *II = D.getIdentifier();
2646 Expr *BitWidth = (Expr*)BitfieldWidth;
2647 SourceLocation Loc = DeclStart;
2648 if (II) Loc = D.getIdentifierLoc();
2649
2650 // FIXME: Unnamed fields can be handled in various different ways, for
2651 // example, unnamed unions inject all members into the struct namespace!
2652
2653
2654 if (BitWidth) {
2655 // TODO: Validate.
2656 //printf("WARNING: BITFIELDS IGNORED!\n");
2657
2658 // 6.7.2.1p3
2659 // 6.7.2.1p4
2660
2661 } else {
2662 // Not a bitfield.
2663
2664 // validate II.
2665
2666 }
2667
2668 QualType T = GetTypeForDeclarator(D, S);
2669 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2670 bool InvalidDecl = false;
2671
2672 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2673 // than a variably modified type.
2674 if (T->isVariablyModifiedType()) {
2675 // FIXME: This diagnostic needs work
2676 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2677 InvalidDecl = true;
2678 }
2679
Ted Kremenek173dd312008-07-23 18:04:17 +00002680 // Get the visibility (access control) for this ivar.
2681 ObjCIvarDecl::AccessControl ac =
2682 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2683 : ObjCIvarDecl::None;
2684
2685 // Construct the decl.
2686 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00002687 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002688
Ted Kremenek173dd312008-07-23 18:04:17 +00002689 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00002690 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002691
2692 if (D.getInvalidType() || InvalidDecl)
2693 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00002694
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002695 return NewID;
2696}
2697
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00002698void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002699 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00002700 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00002701 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00002702 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002703 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2704 assert(EnclosingDecl && "missing record or interface decl");
2705 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2706
Ted Kremenek46a837c2008-09-05 17:16:31 +00002707 if (Record)
2708 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2709 // Diagnose code like:
2710 // struct S { struct S {} X; };
2711 // We discover this when we complete the outer S. Reject and ignore the
2712 // outer S.
2713 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2714 DefRecord->getKindName());
2715 Diag(RecLoc, diag::err_previous_definition);
2716 Record->setInvalidDecl();
2717 return;
2718 }
2719
Chris Lattner4b009652007-07-25 00:24:17 +00002720 // Verify that all the fields are okay.
2721 unsigned NumNamedMembers = 0;
2722 llvm::SmallVector<FieldDecl*, 32> RecFields;
2723 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00002724
Chris Lattner4b009652007-07-25 00:24:17 +00002725 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002726
Steve Naroff9bb759f2007-09-14 22:20:54 +00002727 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2728 assert(FD && "missing field decl");
2729
2730 // Remember all fields.
2731 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00002732
2733 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00002734 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00002735
Chris Lattner4b009652007-07-25 00:24:17 +00002736 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00002737 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002738 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00002739 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002740 FD->setInvalidDecl();
2741 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002742 continue;
2743 }
Chris Lattner4b009652007-07-25 00:24:17 +00002744 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2745 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002746 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002747 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002748 FD->setInvalidDecl();
2749 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002750 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002751 }
Chris Lattner4b009652007-07-25 00:24:17 +00002752 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002753 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00002754 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00002755 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002756 FD->setInvalidDecl();
2757 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002758 continue;
2759 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002760 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00002761 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2762 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002763 FD->setInvalidDecl();
2764 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002765 continue;
2766 }
Chris Lattner4b009652007-07-25 00:24:17 +00002767 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002768 if (Record)
2769 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002770 }
Chris Lattner4b009652007-07-25 00:24:17 +00002771 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2772 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00002773 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002774 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2775 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002776 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002777 Record->setHasFlexibleArrayMember(true);
2778 } else {
2779 // If this is a struct/class and this is not the last element, reject
2780 // it. Note that GCC supports variable sized arrays in the middle of
2781 // structures.
2782 if (i != NumFields-1) {
2783 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2784 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002785 FD->setInvalidDecl();
2786 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002787 continue;
2788 }
Chris Lattner4b009652007-07-25 00:24:17 +00002789 // We support flexible arrays at the end of structs in other structs
2790 // as an extension.
2791 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2792 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002793 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002794 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002795 }
2796 }
2797 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002798 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00002799 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002800 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2801 FD->getName());
2802 FD->setInvalidDecl();
2803 EnclosingDecl->setInvalidDecl();
2804 continue;
2805 }
Chris Lattner4b009652007-07-25 00:24:17 +00002806 // Keep track of the number of named members.
2807 if (IdentifierInfo *II = FD->getIdentifier()) {
2808 // Detect duplicate member names.
2809 if (!FieldIDs.insert(II)) {
2810 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2811 // Find the previous decl.
2812 SourceLocation PrevLoc;
Chris Lattner504c5432008-10-12 00:28:42 +00002813 for (unsigned i = 0; ; ++i) {
2814 assert(i != RecFields.size() && "Didn't find previous def!");
Chris Lattner4b009652007-07-25 00:24:17 +00002815 if (RecFields[i]->getIdentifier() == II) {
2816 PrevLoc = RecFields[i]->getLocation();
2817 break;
2818 }
2819 }
2820 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002821 FD->setInvalidDecl();
2822 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002823 continue;
2824 }
2825 ++NumNamedMembers;
2826 }
Chris Lattner4b009652007-07-25 00:24:17 +00002827 }
2828
Chris Lattner4b009652007-07-25 00:24:17 +00002829 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00002830 if (Record) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002831 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +00002832 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2833 // Sema::ActOnFinishCXXClassDef.
2834 if (!isa<CXXRecordDecl>(Record))
2835 Consumer.HandleTagDeclDefinition(Record);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002836 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00002837 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2838 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2839 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2840 else if (ObjCImplementationDecl *IMPDecl =
2841 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002842 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2843 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00002844 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00002845 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00002846 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00002847
2848 if (Attr)
2849 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00002850}
2851
Steve Naroff0acc9c92007-09-15 18:49:24 +00002852Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00002853 DeclTy *lastEnumConst,
2854 SourceLocation IdLoc, IdentifierInfo *Id,
2855 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00002856 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002857 EnumConstantDecl *LastEnumConst =
2858 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2859 Expr *Val = static_cast<Expr*>(val);
2860
Chris Lattnera7549902007-08-26 06:24:45 +00002861 // The scope passed in may not be a decl scope. Zip up the scope tree until
2862 // we find one that is.
2863 while ((S->getFlags() & Scope::DeclScope) == 0)
2864 S = S->getParent();
2865
Chris Lattner4b009652007-07-25 00:24:17 +00002866 // Verify that there isn't already something declared with this name in this
2867 // scope.
Steve Naroff6384a012008-04-02 14:35:35 +00002868 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00002869 // When in C++, we may get a TagDecl with the same name; in this case the
2870 // enum constant will 'hide' the tag.
2871 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2872 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00002873 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002874 if (isa<EnumConstantDecl>(PrevDecl))
2875 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2876 else
2877 Diag(IdLoc, diag::err_redefinition, Id->getName());
2878 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002879 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00002880 return 0;
2881 }
2882 }
2883
2884 llvm::APSInt EnumVal(32);
2885 QualType EltTy;
2886 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00002887 // Make sure to promote the operand type to int.
2888 UsualUnaryConversions(Val);
2889
Chris Lattner4b009652007-07-25 00:24:17 +00002890 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2891 SourceLocation ExpLoc;
2892 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
2893 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2894 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002895 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00002896 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00002897 } else {
2898 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002899 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00002900 }
2901
2902 if (!Val) {
2903 if (LastEnumConst) {
2904 // Assign the last value + 1.
2905 EnumVal = LastEnumConst->getInitVal();
2906 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00002907
2908 // Check for overflow on increment.
2909 if (EnumVal < LastEnumConst->getInitVal())
2910 Diag(IdLoc, diag::warn_enum_value_overflow);
2911
Chris Lattnere7f53a42007-08-27 17:37:24 +00002912 EltTy = LastEnumConst->getType();
2913 } else {
2914 // First value, set to zero.
2915 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002916 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00002917 }
Chris Lattner4b009652007-07-25 00:24:17 +00002918 }
2919
Chris Lattnere4650482008-03-15 06:12:44 +00002920 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00002921 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2922 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00002923 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00002924
2925 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002926 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002927 return New;
2928}
2929
Steve Naroffb0726b82008-08-07 14:08:16 +00002930// FIXME: For consistency with ActOnFields(), we should have the parser
2931// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002932void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00002933 DeclTy **Elements, unsigned NumElements) {
2934 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Chris Lattner4b009652007-07-25 00:24:17 +00002935
Steve Naroffb0726b82008-08-07 14:08:16 +00002936 if (Enum && Enum->isDefinition()) {
2937 // Diagnose code like:
2938 // enum e0 {
2939 // E0 = sizeof(enum e0 { E1 })
2940 // };
2941 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2942 Enum->getName());
2943 Diag(EnumLoc, diag::err_previous_definition);
2944 Enum->setInvalidDecl();
2945 return;
2946 }
Chris Lattner435c3fd2007-08-28 05:10:31 +00002947 // TODO: If the result value doesn't fit in an int, it must be a long or long
2948 // long value. ISO C does not support this, but GCC does as an extension,
2949 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002950 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00002951
Chris Lattner206754a2007-08-28 06:15:15 +00002952 // Verify that all the values are okay, compute the size of the values, and
2953 // reverse the list.
2954 unsigned NumNegativeBits = 0;
2955 unsigned NumPositiveBits = 0;
2956
2957 // Keep track of whether all elements have type int.
2958 bool AllElementsInt = true;
2959
Chris Lattner4b009652007-07-25 00:24:17 +00002960 EnumConstantDecl *EltList = 0;
2961 for (unsigned i = 0; i != NumElements; ++i) {
2962 EnumConstantDecl *ECD =
2963 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2964 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002965
2966 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002967 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002968 assert(InitVal.getBitWidth() >= IntWidth &&
2969 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00002970 if (InitVal.getBitWidth() > IntWidth) {
2971 llvm::APSInt V(InitVal);
2972 V.trunc(IntWidth);
2973 V.extend(InitVal.getBitWidth());
2974 if (V != InitVal)
2975 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattneread053a2008-08-17 07:19:51 +00002976 InitVal.toString(10));
Chris Lattnercb33ae12007-08-28 05:27:00 +00002977 }
Chris Lattner206754a2007-08-28 06:15:15 +00002978
2979 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002980 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00002981 NumPositiveBits = std::max(NumPositiveBits,
2982 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00002983 else
Chris Lattneraff63f02008-01-14 21:47:29 +00002984 NumNegativeBits = std::max(NumNegativeBits,
2985 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00002986
Chris Lattner206754a2007-08-28 06:15:15 +00002987 // Keep track of whether every enum element has type int (very commmon).
2988 if (AllElementsInt)
2989 AllElementsInt = ECD->getType() == Context.IntTy;
2990
Chris Lattner4b009652007-07-25 00:24:17 +00002991 ECD->setNextDeclarator(EltList);
2992 EltList = ECD;
2993 }
2994
Chris Lattner206754a2007-08-28 06:15:15 +00002995 // Figure out the type that should be used for this enum.
2996 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2997 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002998 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00002999
3000 if (NumNegativeBits) {
3001 // If there is a negative value, figure out the smallest integer type (of
3002 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003003 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003004 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003005 BestWidth = IntWidth;
3006 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003007 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003008
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003009 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003010 BestType = Context.LongTy;
3011 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003012 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003013
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003014 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003015 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3016 BestType = Context.LongLongTy;
3017 }
3018 }
3019 } else {
3020 // If there is no negative value, figure out which of uint, ulong, ulonglong
3021 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003022 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003023 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003024 BestWidth = IntWidth;
3025 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00003026 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00003027 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003028 } else {
3029 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003030 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00003031 "How could an initializer get larger than ULL?");
3032 BestType = Context.UnsignedLongLongTy;
3033 }
3034 }
3035
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003036 // Loop over all of the enumerator constants, changing their types to match
3037 // the type of the enum if needed.
3038 for (unsigned i = 0; i != NumElements; ++i) {
3039 EnumConstantDecl *ECD =
3040 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3041 if (!ECD) continue; // Already issued a diagnostic.
3042
3043 // Standard C says the enumerators have int type, but we allow, as an
3044 // extension, the enumerators to be larger than int size. If each
3045 // enumerator value fits in an int, type it as an int, otherwise type it the
3046 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3047 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003048 if (ECD->getType() == Context.IntTy) {
3049 // Make sure the init value is signed.
3050 llvm::APSInt IV = ECD->getInitVal();
3051 IV.setIsSigned(true);
3052 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003053 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003054 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003055
3056 // Determine whether the value fits into an int.
3057 llvm::APSInt InitVal = ECD->getInitVal();
3058 bool FitsInInt;
3059 if (InitVal.isUnsigned() || !InitVal.isNegative())
3060 FitsInInt = InitVal.getActiveBits() < IntWidth;
3061 else
3062 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3063
3064 // If it fits into an integer type, force it. Otherwise force it to match
3065 // the enum decl type.
3066 QualType NewTy;
3067 unsigned NewWidth;
3068 bool NewSign;
3069 if (FitsInInt) {
3070 NewTy = Context.IntTy;
3071 NewWidth = IntWidth;
3072 NewSign = true;
3073 } else if (ECD->getType() == BestType) {
3074 // Already the right type!
3075 continue;
3076 } else {
3077 NewTy = BestType;
3078 NewWidth = BestWidth;
3079 NewSign = BestType->isSignedIntegerType();
3080 }
3081
3082 // Adjust the APSInt value.
3083 InitVal.extOrTrunc(NewWidth);
3084 InitVal.setIsSigned(NewSign);
3085 ECD->setInitVal(InitVal);
3086
3087 // Adjust the Expr initializer and type.
Douglas Gregor70d26122008-11-12 17:17:38 +00003088 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3089 /*isLvalue=*/false));
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003090 ECD->setType(NewTy);
3091 }
Chris Lattner206754a2007-08-28 06:15:15 +00003092
Chris Lattner90a018d2007-08-28 18:24:31 +00003093 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003094 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003095}
3096
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003097Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3098 ExprTy *expr) {
3099 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
3100
Chris Lattner81db64a2008-03-16 00:16:02 +00003101 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003102}
3103
Chris Lattner806a5f52008-01-12 07:05:38 +00003104Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00003105 SourceLocation LBrace,
3106 SourceLocation RBrace,
3107 const char *Lang,
3108 unsigned StrSize,
3109 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00003110 LinkageSpecDecl::LanguageIDs Language;
3111 Decl *dcl = static_cast<Decl *>(D);
3112 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3113 Language = LinkageSpecDecl::lang_c;
3114 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3115 Language = LinkageSpecDecl::lang_cxx;
3116 else {
3117 Diag(Loc, diag::err_bad_language);
3118 return 0;
3119 }
3120
3121 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00003122 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00003123}
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003124
3125void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3126 ExprTy *alignment, SourceLocation PragmaLoc,
3127 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3128 Expr *Alignment = static_cast<Expr *>(alignment);
3129
3130 // If specified then alignment must be a "small" power of two.
3131 unsigned AlignmentVal = 0;
3132 if (Alignment) {
3133 llvm::APSInt Val;
3134 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3135 !Val.isPowerOf2() ||
3136 Val.getZExtValue() > 16) {
3137 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3138 delete Alignment;
3139 return; // Ignore
3140 }
3141
3142 AlignmentVal = (unsigned) Val.getZExtValue();
3143 }
3144
3145 switch (Kind) {
3146 case Action::PPK_Default: // pack([n])
3147 PackContext.setAlignment(AlignmentVal);
3148 break;
3149
3150 case Action::PPK_Show: // pack(show)
3151 // Show the current alignment, making sure to show the right value
3152 // for the default.
3153 AlignmentVal = PackContext.getAlignment();
3154 // FIXME: This should come from the target.
3155 if (AlignmentVal == 0)
3156 AlignmentVal = 8;
3157 Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal));
3158 break;
3159
3160 case Action::PPK_Push: // pack(push [, id] [, [n])
3161 PackContext.push(Name);
3162 // Set the new alignment if specified.
3163 if (Alignment)
3164 PackContext.setAlignment(AlignmentVal);
3165 break;
3166
3167 case Action::PPK_Pop: // pack(pop [, id] [, n])
3168 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3169 // "#pragma pack(pop, identifier, n) is undefined"
3170 if (Alignment && Name)
3171 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3172
3173 // Do the pop.
3174 if (!PackContext.pop(Name)) {
3175 // If a name was specified then failure indicates the name
3176 // wasn't found. Otherwise failure indicates the stack was
3177 // empty.
3178 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed,
3179 Name ? "no record matching name" : "stack empty");
3180
3181 // FIXME: Warn about popping named records as MSVC does.
3182 } else {
3183 // Pop succeeded, set the new alignment if specified.
3184 if (Alignment)
3185 PackContext.setAlignment(AlignmentVal);
3186 }
3187 break;
3188
3189 default:
3190 assert(0 && "Invalid #pragma pack kind.");
3191 }
3192}
3193
3194bool PragmaPackStack::pop(IdentifierInfo *Name) {
3195 if (Stack.empty())
3196 return false;
3197
3198 // If name is empty just pop top.
3199 if (!Name) {
3200 Alignment = Stack.back().first;
3201 Stack.pop_back();
3202 return true;
3203 }
3204
3205 // Otherwise, find the named record.
3206 for (unsigned i = Stack.size(); i != 0; ) {
3207 --i;
3208 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) {
3209 // Found it, pop up to and including this record.
3210 Alignment = Stack[i].first;
3211 Stack.erase(Stack.begin() + i, Stack.end());
3212 return true;
3213 }
3214 }
3215
3216 return false;
3217}