blob: 2228b41b331149a5e03b0516ea4db59b14f94547 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Mike Stumpb1682c52009-07-22 23:56:57 +000018#include "clang/Analysis/CFG.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000021#include "clang/AST/DeclTemplate.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000022#include "clang/AST/ExprCXX.h"
Sebastian Redld3a413d2009-04-26 20:35:05 +000023#include "clang/AST/StmtCXX.h"
Mike Stump10e975c2009-07-23 00:20:25 +000024#include "clang/AST/StmtObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "clang/Parse/DeclSpec.h"
Douglas Gregora786fdb2009-10-13 23:27:22 +000026#include "clang/Parse/ParseDiagnostic.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000027#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000029#include "clang/Basic/SourceManager.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000030#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000031// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000032#include "clang/Lex/Preprocessor.h"
Mike Stump1eb44332009-09-09 15:08:12 +000033#include "clang/Lex/HeaderSearch.h"
Daniel Dunbar1f15e762009-07-23 05:01:54 +000034#include "llvm/ADT/BitVector.h"
Douglas Gregore267ff32008-12-11 20:41:00 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000036#include <algorithm>
Douglas Gregor9a8c9a22009-09-28 21:14:19 +000037#include <cstring>
Douglas Gregor6ed40e32008-12-23 21:05:05 +000038#include <functional>
Mike Stumpb1682c52009-07-22 23:56:57 +000039#include <queue>
Reid Spencer5f016e22007-07-11 17:01:13 +000040using namespace clang;
41
Chris Lattner21ff9c92009-03-05 01:25:28 +000042/// getDeclName - Return a pretty name for the specified decl if possible, or
Mike Stump1eb44332009-09-09 15:08:12 +000043/// an empty string if not. This is used for pretty crash reporting.
Chris Lattnerb28317a2009-03-28 19:18:32 +000044std::string Sema::getDeclName(DeclPtrTy d) {
45 Decl *D = d.getAs<Decl>();
Chris Lattner21ff9c92009-03-05 01:25:28 +000046 if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
47 return DN->getQualifiedNameAsString();
48 return "";
49}
50
Chris Lattner682bf922009-03-29 16:50:03 +000051Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
52 return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
53}
54
Douglas Gregord6efafa2009-02-04 19:16:12 +000055/// \brief If the identifier refers to a type name within this scope,
56/// return the declaration of that type.
57///
58/// This routine performs ordinary name lookup of the identifier II
59/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor1a51b4a2009-02-09 15:09:02 +000060/// determine whether the name refers to a type. If so, returns an
61/// opaque pointer (actually a QualType) corresponding to that
62/// type. Otherwise, returns NULL.
Douglas Gregord6efafa2009-02-04 19:16:12 +000063///
64/// If name lookup results in an ambiguity, this routine will complain
65/// and then return NULL.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +000066Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
Douglas Gregor42c39f32009-08-26 18:27:52 +000067 Scope *S, const CXXScopeSpec *SS,
68 bool isClassName) {
Douglas Gregor5953d8b2009-03-19 17:26:29 +000069 // C++ [temp.res]p3:
70 // A qualified-id that refers to a type and in which the
71 // nested-name-specifier depends on a template-parameter (14.6.2)
72 // shall be prefixed by the keyword typename to indicate that the
73 // qualified-id denotes a type, forming an
74 // elaborated-type-specifier (7.1.5.3).
75 //
Douglas Gregor42af25f2009-05-11 19:58:34 +000076 // We therefore do not perform any name lookup if the result would
77 // refer to a member of an unknown specialization.
Douglas Gregor42c39f32009-08-26 18:27:52 +000078 if (SS && isUnknownSpecialization(*SS)) {
79 if (!isClassName)
80 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000081
82 // We know from the grammar that this name refers to a type, so build a
Douglas Gregor42c39f32009-08-26 18:27:52 +000083 // TypenameType node to describe the type.
84 // FIXME: Record somewhere that this TypenameType node has no "typename"
85 // keyword associated with it.
86 return CheckTypenameType((NestedNameSpecifier *)SS->getScopeRep(),
87 II, SS->getRange()).getAsOpaquePtr();
88 }
Mike Stump1eb44332009-09-09 15:08:12 +000089
John McCalla24dc2e2009-11-17 02:14:36 +000090 LookupResult Result(*this, &II, NameLoc, LookupOrdinaryName);
91 LookupParsedName(Result, S, SS, false);
Douglas Gregor42af25f2009-05-11 19:58:34 +000092
Chris Lattner22bd9052009-02-16 22:07:16 +000093 NamedDecl *IIDecl = 0;
John McCalla24dc2e2009-11-17 02:14:36 +000094 switch (Result.getResultKind()) {
Chris Lattner22bd9052009-02-16 22:07:16 +000095 case LookupResult::NotFound:
96 case LookupResult::FoundOverloaded:
97 return 0;
Douglas Gregorb696ea32009-02-04 17:00:24 +000098
Chris Lattnera64ef0a2009-10-25 22:09:09 +000099 case LookupResult::Ambiguous:
John McCall6e247262009-10-10 05:48:19 +0000100 // Recover from type-hiding ambiguities by hiding the type. We'll
101 // do the lookup again when looking for an object, and we can
102 // diagnose the error then. If we don't do this, then the error
103 // about hiding the type will be immediately followed by an error
104 // that only makes sense if the identifier was treated like a type.
John McCalla24dc2e2009-11-17 02:14:36 +0000105 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
106 Result.suppressDiagnostics();
John McCall6e247262009-10-10 05:48:19 +0000107 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000108 }
John McCall6e247262009-10-10 05:48:19 +0000109
Douglas Gregor31a19b62009-04-01 21:51:26 +0000110 // Look to see if we have a type anywhere in the list of results.
111 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
112 Res != ResEnd; ++Res) {
113 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000114 if (!IIDecl ||
115 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor841b53c2009-04-13 15:14:38 +0000116 IIDecl->getLocation().getRawEncoding())
117 IIDecl = *Res;
Douglas Gregor31a19b62009-04-01 21:51:26 +0000118 }
119 }
120
121 if (!IIDecl) {
122 // None of the entities we found is a type, so there is no way
123 // to even assume that the result is a type. In this case, don't
124 // complain about the ambiguity. The parser will either try to
125 // perform this lookup again (e.g., as an object name), which
126 // will produce the ambiguity, or will complain that it expected
127 // a type name.
John McCalla24dc2e2009-11-17 02:14:36 +0000128 Result.suppressDiagnostics();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000129 return 0;
130 }
131
132 // We found a type within the ambiguous lookup; diagnose the
133 // ambiguity and then return that type. This might be the right
134 // answer, or it might not be, but it suppresses any attempt to
135 // perform the name lookup again.
Douglas Gregor31a19b62009-04-01 21:51:26 +0000136 break;
Douglas Gregorb696ea32009-02-04 17:00:24 +0000137
Chris Lattner22bd9052009-02-16 22:07:16 +0000138 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +0000139 IIDecl = Result.getFoundDecl();
Chris Lattner22bd9052009-02-16 22:07:16 +0000140 break;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000141 }
142
Chris Lattner10ca3372009-10-25 17:16:46 +0000143 assert(IIDecl && "Didn't find decl");
John McCall54abf7d2009-11-04 02:18:39 +0000144
Chris Lattner10ca3372009-10-25 17:16:46 +0000145 QualType T;
146 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall54abf7d2009-11-04 02:18:39 +0000147 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCalla24dc2e2009-11-17 02:14:36 +0000148
Chris Lattner10ca3372009-10-25 17:16:46 +0000149 // C++ [temp.local]p2:
150 // Within the scope of a class template specialization or
151 // partial specialization, when the injected-class-name is
152 // not followed by a <, it is equivalent to the
153 // injected-class-name followed by the template-argument s
154 // of the class template specialization or partial
155 // specialization enclosed in <>.
156 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD))
157 if (RD->isInjectedClassName())
158 if (ClassTemplateDecl *Template = RD->getDescribedClassTemplate())
159 T = Template->getInjectedClassNameType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000160
Chris Lattner10ca3372009-10-25 17:16:46 +0000161 if (T.isNull())
162 T = Context.getTypeDeclType(TD);
163
Douglas Gregore6258932009-03-19 00:39:20 +0000164 if (SS)
165 T = getQualifiedNameType(*SS, T);
Chris Lattner10ca3372009-10-25 17:16:46 +0000166
167 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Chris Lattner10ca3372009-10-25 17:16:46 +0000168 T = Context.getObjCInterfaceType(IDecl);
John McCalla24dc2e2009-11-17 02:14:36 +0000169 } else {
170 // If it's not plausibly a type, suppress diagnostics.
171 Result.suppressDiagnostics();
Chris Lattner10ca3372009-10-25 17:16:46 +0000172 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000173 }
Douglas Gregore4e5b052009-03-19 00:18:19 +0000174
Chris Lattner10ca3372009-10-25 17:16:46 +0000175 return T.getAsOpaquePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +0000176}
177
Chris Lattner4c97d762009-04-12 21:49:30 +0000178/// isTagName() - This method is called *for error recovery purposes only*
179/// to determine if the specified name is a valid tag name ("struct foo"). If
180/// so, this returns the TST for the tag corresponding to it (TST_enum,
181/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
182/// where the user forgot to specify the tag.
183DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
184 // Do a tag name lookup in this scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000185 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
186 LookupName(R, S, false);
187 R.suppressDiagnostics();
188 if (R.getResultKind() == LookupResult::Found)
John McCallf36e02d2009-10-09 21:13:30 +0000189 if (const TagDecl *TD = dyn_cast<TagDecl>(R.getAsSingleDecl(Context))) {
Chris Lattner4c97d762009-04-12 21:49:30 +0000190 switch (TD->getTagKind()) {
191 case TagDecl::TK_struct: return DeclSpec::TST_struct;
192 case TagDecl::TK_union: return DeclSpec::TST_union;
193 case TagDecl::TK_class: return DeclSpec::TST_class;
194 case TagDecl::TK_enum: return DeclSpec::TST_enum;
195 }
196 }
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Chris Lattner4c97d762009-04-12 21:49:30 +0000198 return DeclSpec::TST_unspecified;
199}
200
Douglas Gregora786fdb2009-10-13 23:27:22 +0000201bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
202 SourceLocation IILoc,
203 Scope *S,
204 const CXXScopeSpec *SS,
205 TypeTy *&SuggestedType) {
206 // We don't have anything to suggest (yet).
207 SuggestedType = 0;
208
209 // FIXME: Should we move the logic that tries to recover from a missing tag
210 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
211
212 if (!SS)
213 Diag(IILoc, diag::err_unknown_typename) << &II;
214 else if (DeclContext *DC = computeDeclContext(*SS, false))
215 Diag(IILoc, diag::err_typename_nested_not_found)
216 << &II << DC << SS->getRange();
217 else if (isDependentScopeSpecifier(*SS)) {
218 Diag(SS->getRange().getBegin(), diag::err_typename_missing)
Daniel Dunbar01eb9b92009-10-18 21:17:35 +0000219 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
Douglas Gregora786fdb2009-10-13 23:27:22 +0000220 << SourceRange(SS->getRange().getBegin(), IILoc)
221 << CodeModificationHint::CreateInsertion(SS->getRange().getBegin(),
222 "typename ");
223 SuggestedType = ActOnTypenameType(SourceLocation(), *SS, II, IILoc).get();
224 } else {
225 assert(SS && SS->isInvalid() &&
226 "Invalid scope specifier has already been diagnosed");
227 }
228
229 return true;
230}
Chris Lattner4c97d762009-04-12 21:49:30 +0000231
John McCall88232aa2009-08-18 00:00:49 +0000232// Determines the context to return to after temporarily entering a
233// context. This depends in an unnecessarily complicated way on the
234// exact ordering of callbacks from the parser.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000235DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000236
John McCall88232aa2009-08-18 00:00:49 +0000237 // Functions defined inline within classes aren't parsed until we've
238 // finished parsing the top-level class, so the top-level class is
239 // the context we'll need to return to.
240 if (isa<FunctionDecl>(DC)) {
241 DC = DC->getLexicalParent();
242
243 // A function not defined within a class will always return to its
244 // lexical context.
245 if (!isa<CXXRecordDecl>(DC))
246 return DC;
247
248 // A C++ inline method/friend is parsed *after* the topmost class
249 // it was declared in is fully parsed ("complete"); the topmost
250 // class is the context we need to return to.
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000251 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000252 DC = RD;
253
254 // Return the declaration context of the topmost class the inline method is
255 // declared in.
256 return DC;
257 }
258
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +0000259 if (isa<ObjCMethodDecl>(DC))
260 return Context.getTranslationUnitDecl();
261
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000262 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000263}
264
Douglas Gregor44b43212008-12-11 16:49:14 +0000265void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000266 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +0000267 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +0000268 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +0000269 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000270}
271
Chris Lattnerb048c982008-04-06 04:47:34 +0000272void Sema::PopDeclContext() {
273 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +0000274
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000275 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000276}
277
Argyrios Kyrtzidis179fe1a2009-06-17 23:19:02 +0000278/// EnterDeclaratorContext - Used when we must lookup names in the context
279/// of a declarator's nested name specifier.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000280void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
281 assert(PreDeclaratorDC == 0 && "Previous declarator context not popped?");
282 PreDeclaratorDC = static_cast<DeclContext*>(S->getEntity());
283 CurContext = DC;
284 assert(CurContext && "No context?");
285 S->setEntity(CurContext);
286}
287
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000288void Sema::ExitDeclaratorContext(Scope *S) {
289 S->setEntity(PreDeclaratorDC);
290 PreDeclaratorDC = 0;
291
292 // Reset CurContext to the nearest enclosing context.
293 while (!S->getEntity() && S->getParent())
294 S = S->getParent();
295 CurContext = static_cast<DeclContext*>(S->getEntity());
296 assert(CurContext && "No context?");
297}
298
Douglas Gregorf9201e02009-02-11 23:02:49 +0000299/// \brief Determine whether we allow overloading of the function
300/// PrevDecl with another declaration.
301///
302/// This routine determines whether overloading is possible, not
303/// whether some new function is actually an overload. It will return
304/// true in C++ (where we can always provide overloads) or, as an
305/// extension, in C when the previous function is already an
306/// overloaded function declaration or has the "overloadable"
307/// attribute.
308static bool AllowOverloadingOfFunction(Decl *PrevDecl, ASTContext &Context) {
309 if (Context.getLangOptions().CPlusPlus)
310 return true;
311
312 if (isa<OverloadedFunctionDecl>(PrevDecl))
313 return true;
314
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000315 return PrevDecl->getAttr<OverloadableAttr>() != 0;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000316}
317
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000318/// Add this decl to the scope shadowed decl chains.
John McCallab88d972009-08-31 22:39:49 +0000319void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000320 // Move up the scope chain until we find the nearest enclosing
321 // non-transparent context. The declaration will be introduced into this
322 // scope.
Mike Stump1eb44332009-09-09 15:08:12 +0000323 while (S->getEntity() &&
Douglas Gregor074149e2009-01-05 19:45:36 +0000324 ((DeclContext *)S->getEntity())->isTransparentContext())
325 S = S->getParent();
326
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000327 // Add scoped declarations into their context, so that they can be
328 // found later. Declarations without a context won't be inserted
329 // into any context.
John McCallab88d972009-08-31 22:39:49 +0000330 if (AddToContext)
331 CurContext->addDecl(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000332
Douglas Gregord04b1be2009-09-28 18:41:37 +0000333 // Out-of-line function and variable definitions should not be pushed into
334 // scope.
335 if ((isa<FunctionTemplateDecl>(D) &&
336 cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->isOutOfLine()) ||
337 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isOutOfLine()) ||
338 (isa<VarDecl>(D) && cast<VarDecl>(D)->isOutOfLine()))
339 return;
340
John McCallf36e02d2009-10-09 21:13:30 +0000341 // If this replaces anything in the current scope,
342 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
343 IEnd = IdResolver.end();
344 for (; I != IEnd; ++I) {
345 if (S->isDeclScope(DeclPtrTy::make(*I)) && D->declarationReplaces(*I)) {
346 S->RemoveDecl(DeclPtrTy::make(*I));
347 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000348
John McCallf36e02d2009-10-09 21:13:30 +0000349 // Should only need to replace one decl.
350 break;
Douglas Gregor516ff432009-04-24 02:57:34 +0000351 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000352 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000353
John McCallf36e02d2009-10-09 21:13:30 +0000354 S->AddDecl(DeclPtrTy::make(D));
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000355 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000356}
357
Douglas Gregor2531c2d2009-09-28 00:47:05 +0000358bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) {
359 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) {
360 // Look inside the overload set to determine if any of the declarations
361 // are in scope. (Possibly) build a new overload set containing only
362 // those declarations that are in scope.
363 OverloadedFunctionDecl *NewOvl = 0;
364 bool FoundInScope = false;
365 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
366 FEnd = Ovl->function_end();
367 F != FEnd; ++F) {
368 NamedDecl *FD = F->get();
369 if (!isDeclInScope(FD, Ctx, S)) {
370 if (!NewOvl && F != Ovl->function_begin()) {
371 NewOvl = OverloadedFunctionDecl::Create(Context,
372 F->get()->getDeclContext(),
373 F->get()->getDeclName());
374 D = NewOvl;
375 for (OverloadedFunctionDecl::function_iterator
376 First = Ovl->function_begin();
377 First != F; ++First)
378 NewOvl->addOverload(*First);
379 }
380 } else {
381 FoundInScope = true;
382 if (NewOvl)
383 NewOvl->addOverload(*F);
384 }
385 }
386
387 return FoundInScope;
388 }
389
390 return IdResolver.isDeclInScope(D, Ctx, Context, S);
391}
392
Anders Carlsson99a000e2009-11-07 07:18:14 +0000393static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
Anders Carlssonf7613d52009-11-07 07:26:56 +0000394 if (D->isUsed() || D->hasAttr<UnusedAttr>())
395 return false;
396
397 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
398 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
399 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
400 if (!RD->hasTrivialConstructor())
401 return false;
402 if (!RD->hasTrivialDestructor())
403 return false;
404 }
405 }
406 }
407
408 return (isa<VarDecl>(D) && !isa<ParmVarDecl>(D) &&
409 !isa<ImplicitParamDecl>(D) &&
Anders Carlsson99a000e2009-11-07 07:18:14 +0000410 D->getDeclContext()->isFunctionOrMethod());
411}
412
Steve Naroffb216c882007-10-09 22:01:59 +0000413void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000414 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000415 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump1eb44332009-09-09 15:08:12 +0000416 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000417
Reid Spencer5f016e22007-07-11 17:01:13 +0000418 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
419 I != E; ++I) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000420 Decl *TmpD = (*I).getAs<Decl>();
Steve Naroffc752d042007-09-13 18:10:37 +0000421 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000422
Douglas Gregor44b43212008-12-11 16:49:14 +0000423 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
424 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000425
Douglas Gregor44b43212008-12-11 16:49:14 +0000426 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000427
Douglas Gregorb5352cf2009-10-08 21:35:42 +0000428 // Diagnose unused variables in this scope.
Anders Carlsson99a000e2009-11-07 07:18:14 +0000429 if (ShouldDiagnoseUnusedDecl(D))
430 Diag(D->getLocation(), diag::warn_unused_variable) << D->getDeclName();
Douglas Gregorb5352cf2009-10-08 21:35:42 +0000431
Douglas Gregor44b43212008-12-11 16:49:14 +0000432 // Remove this name from our lexical scope.
433 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000434 }
435}
436
Steve Naroffe8043c32008-04-01 23:04:06 +0000437/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
438/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000439ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000440 // The third "scope" argument is 0 since we aren't enabling lazy built-in
441 // creation from this context.
John McCallf36e02d2009-10-09 21:13:30 +0000442 NamedDecl *IDecl = LookupSingleName(TUScope, Id, LookupOrdinaryName);
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Steve Naroffb327ce02008-04-02 14:35:35 +0000444 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000445}
446
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000447/// getNonFieldDeclScope - Retrieves the innermost scope, starting
448/// from S, where a non-field would be declared. This routine copes
449/// with the difference between C and C++ scoping rules in structs and
450/// unions. For example, the following code is well-formed in C but
451/// ill-formed in C++:
452/// @code
453/// struct S6 {
454/// enum { BAR } e;
455/// };
Mike Stump1eb44332009-09-09 15:08:12 +0000456///
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000457/// void test_S6() {
458/// struct S6 a;
459/// a.e = BAR;
460/// }
461/// @endcode
462/// For the declaration of BAR, this routine will return a different
463/// scope. The scope S will be the scope of the unnamed enumeration
464/// within S6. In C++, this routine will return the scope associated
465/// with S6, because the enumeration's scope is a transparent
466/// context but structures can contain non-field names. In C, this
467/// routine will return the translation unit scope, since the
468/// enumeration's scope is a transparent context and structures cannot
469/// contain non-field names.
470Scope *Sema::getNonFieldDeclScope(Scope *S) {
471 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000472 (S->getEntity() &&
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000473 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
474 (S->isClassScope() && !getLangOptions().CPlusPlus))
475 S = S->getParent();
476 return S;
477}
478
Chris Lattner95e2c712008-05-05 22:18:14 +0000479void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000480 if (!Context.getBuiltinVaListType().isNull())
481 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000483 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
John McCallf36e02d2009-10-09 21:13:30 +0000484 NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, LookupOrdinaryName);
Steve Naroff733002f2007-10-18 22:17:45 +0000485 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000486 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
487}
488
Douglas Gregor3e41d602009-02-13 23:20:09 +0000489/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
490/// file scope. lazily create a decl for it. ForRedeclaration is true
491/// if we're creating this built-in in anticipation of redeclaring the
492/// built-in.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000493NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000494 Scope *S, bool ForRedeclaration,
495 SourceLocation Loc) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000496 Builtin::ID BID = (Builtin::ID)bid;
497
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000498 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000499 InitBuiltinVaListType();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000500
Chris Lattner86df27b2009-06-14 00:45:47 +0000501 ASTContext::GetBuiltinTypeError Error;
Mike Stump1eb44332009-09-09 15:08:12 +0000502 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000503 switch (Error) {
Chris Lattner86df27b2009-06-14 00:45:47 +0000504 case ASTContext::GE_None:
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000505 // Okay
506 break;
507
Mike Stumpf711c412009-07-28 23:57:15 +0000508 case ASTContext::GE_Missing_stdio:
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000509 if (ForRedeclaration)
510 Diag(Loc, diag::err_implicit_decl_requires_stdio)
511 << Context.BuiltinInfo.GetName(BID);
512 return 0;
Mike Stump782fa302009-07-28 02:25:19 +0000513
Mike Stumpf711c412009-07-28 23:57:15 +0000514 case ASTContext::GE_Missing_setjmp:
Mike Stump782fa302009-07-28 02:25:19 +0000515 if (ForRedeclaration)
516 Diag(Loc, diag::err_implicit_decl_requires_setjmp)
517 << Context.BuiltinInfo.GetName(BID);
518 return 0;
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000519 }
Douglas Gregor3e41d602009-02-13 23:20:09 +0000520
521 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
522 Diag(Loc, diag::ext_implicit_lib_function_decl)
523 << Context.BuiltinInfo.GetName(BID)
524 << R;
Douglas Gregorb1152d82009-02-16 21:58:21 +0000525 if (Context.BuiltinInfo.getHeaderName(BID) &&
Chris Lattner6a7334d2009-04-16 03:59:32 +0000526 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
527 != Diagnostic::Ignored)
Douglas Gregor3e41d602009-02-13 23:20:09 +0000528 Diag(Loc, diag::note_please_include_header)
529 << Context.BuiltinInfo.getHeaderName(BID)
530 << Context.BuiltinInfo.GetName(BID);
531 }
532
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000533 FunctionDecl *New = FunctionDecl::Create(Context,
534 Context.getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000535 Loc, II, R, /*DInfo=*/0,
Douglas Gregor2224f842009-02-25 16:33:18 +0000536 FunctionDecl::Extern, false,
537 /*hasPrototype=*/true);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000538 New->setImplicit();
539
Chris Lattner95e2c712008-05-05 22:18:14 +0000540 // Create Decl objects for each parameter, adding them to the
541 // FunctionDecl.
Douglas Gregor72564e72009-02-26 23:50:07 +0000542 if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner95e2c712008-05-05 22:18:14 +0000543 llvm::SmallVector<ParmVarDecl*, 16> Params;
544 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
545 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000546 FT->getArgType(i), /*DInfo=*/0,
547 VarDecl::None, 0));
Jay Foadbeaaccd2009-05-21 09:52:38 +0000548 New->setParams(Context, Params.data(), Params.size());
Chris Lattner95e2c712008-05-05 22:18:14 +0000549 }
Mike Stump1eb44332009-09-09 15:08:12 +0000550
551 AddKnownFunctionAttributes(New);
552
Chris Lattner7f925cc2008-04-11 07:00:53 +0000553 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000554 // FIXME: This is hideous. We need to teach PushOnScopeChains to
555 // relate Scopes to DeclContexts, and probably eliminate CurContext
556 // entirely, but we're not there yet.
557 DeclContext *SavedContext = CurContext;
558 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000559 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000560 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 return New;
562}
563
Douglas Gregorcda9c672009-02-16 17:45:42 +0000564/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
565/// same name and scope as a previous declaration 'Old'. Figure out
566/// how to resolve this situation, merging decls or emitting
Chris Lattnereaaebc72009-04-25 08:06:05 +0000567/// diagnostics as appropriate. If there was an error, set New to be invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +0000568///
Chris Lattnereaaebc72009-04-25 08:06:05 +0000569void Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
570 // If either decl is known invalid already, set the new one to be invalid and
571 // don't bother doing any merging checks.
572 if (New->isInvalidDecl() || OldD->isInvalidDecl())
573 return New->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Steve Naroff2b255c42008-09-09 14:32:20 +0000575 // Allow multiple definitions for ObjC built-in typedefs.
576 // FIXME: Verify the underlying types are equivalent!
577 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000578 const IdentifierInfo *TypeID = New->getIdentifier();
579 switch (TypeID->getLength()) {
580 default: break;
Mike Stump1eb44332009-09-09 15:08:12 +0000581 case 2:
Chris Lattner2bac0f62008-11-20 05:41:43 +0000582 if (!TypeID->isStr("id"))
583 break;
David Chisnall0f436562009-08-17 16:35:33 +0000584 Context.ObjCIdRedefinitionType = New->getUnderlyingType();
Steve Naroff14108da2009-07-10 23:34:53 +0000585 // Install the built-in type for 'id', ignoring the current definition.
586 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
587 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000588 case 5:
589 if (!TypeID->isStr("Class"))
590 break;
David Chisnall0f436562009-08-17 16:35:33 +0000591 Context.ObjCClassRedefinitionType = New->getUnderlyingType();
Steve Naroff14108da2009-07-10 23:34:53 +0000592 // Install the built-in type for 'Class', ignoring the current definition.
593 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +0000594 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000595 case 3:
596 if (!TypeID->isStr("SEL"))
597 break;
Douglas Gregor319ac892009-04-23 22:29:11 +0000598 Context.setObjCSelType(Context.getTypeDeclType(New));
Chris Lattnereaaebc72009-04-25 08:06:05 +0000599 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000600 case 8:
601 if (!TypeID->isStr("Protocol"))
602 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000603 Context.setObjCProtoType(New->getUnderlyingType());
Chris Lattnereaaebc72009-04-25 08:06:05 +0000604 return;
Steve Naroff2b255c42008-09-09 14:32:20 +0000605 }
606 // Fall through - the typedef name was not a builtin type.
607 }
Douglas Gregor66973122009-01-28 17:15:10 +0000608 // Verify the old decl was also a type.
609 TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000610 if (!Old) {
Mike Stump1eb44332009-09-09 15:08:12 +0000611 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000612 << New->getDeclName();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000613 if (OldD->getLocation().isValid())
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000614 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000615 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000616 }
Douglas Gregor66973122009-01-28 17:15:10 +0000617
Mike Stump1eb44332009-09-09 15:08:12 +0000618 // Determine the "old" type we'll use for checking and diagnostics.
Douglas Gregor66973122009-01-28 17:15:10 +0000619 QualType OldType;
620 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
621 OldType = OldTypedef->getUnderlyingType();
622 else
623 OldType = Context.getTypeDeclType(Old);
624
Chris Lattner99cb9972008-07-25 18:44:27 +0000625 // If the typedef types are not identical, reject them in all languages and
626 // with any extensions enabled.
Douglas Gregor66973122009-01-28 17:15:10 +0000627
Mike Stump1eb44332009-09-09 15:08:12 +0000628 if (OldType != New->getUnderlyingType() &&
629 Context.getCanonicalType(OldType) !=
Chris Lattner99cb9972008-07-25 18:44:27 +0000630 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000631 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregor66973122009-01-28 17:15:10 +0000632 << New->getUnderlyingType() << OldType;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000633 if (Old->getLocation().isValid())
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000634 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000635 return New->setInvalidDecl();
Chris Lattner99cb9972008-07-25 18:44:27 +0000636 }
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Steve Naroff14108da2009-07-10 23:34:53 +0000638 if (getLangOptions().Microsoft)
Chris Lattnereaaebc72009-04-25 08:06:05 +0000639 return;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000640
Douglas Gregorbbe27432008-11-21 16:29:06 +0000641 // C++ [dcl.typedef]p2:
642 // In a given non-class scope, a typedef specifier can be used to
643 // redefine the name of any type declared in that scope to refer
644 // to the type to which it already refers.
Chris Lattner32b06752009-04-17 22:04:20 +0000645 if (getLangOptions().CPlusPlus) {
646 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnereaaebc72009-04-25 08:06:05 +0000647 return;
Chris Lattner32b06752009-04-17 22:04:20 +0000648 Diag(New->getLocation(), diag::err_redefinition)
649 << New->getDeclName();
650 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000651 return New->setInvalidDecl();
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000652 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000653
Chris Lattner32b06752009-04-17 22:04:20 +0000654 // If we have a redefinition of a typedef in C, emit a warning. This warning
655 // is normally mapped to an error, but can be controlled with
Eli Friedman340a4e52009-06-04 23:03:07 +0000656 // -Wtypedef-redefinition. If either the original or the redefinition is
657 // in a system header, don't emit this for compatibility with GCC.
Chris Lattnerd0359af2009-04-27 01:46:12 +0000658 if (PP.getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman340a4e52009-06-04 23:03:07 +0000659 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
660 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattnerd0359af2009-04-27 01:46:12 +0000661 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Chris Lattner32b06752009-04-17 22:04:20 +0000663 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
664 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000665 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000666 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000667}
668
Chris Lattner6b6b5372008-06-26 18:38:35 +0000669/// DeclhasAttr - returns true if decl Declaration already has the target
670/// attribute.
Mike Stump1eb44332009-09-09 15:08:12 +0000671static bool
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000672DeclHasAttr(const Decl *decl, const Attr *target) {
673 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
Chris Lattnerddee4232008-03-03 03:28:21 +0000674 if (attr->getKind() == target->getKind())
675 return true;
676
677 return false;
678}
679
680/// MergeAttributes - append attributes from the Old decl to the New one.
Chris Lattnercc581472009-03-04 06:05:19 +0000681static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000682 for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
683 if (!DeclHasAttr(New, attr) && attr->isMerged()) {
Douglas Gregor9f9bf252009-04-28 06:37:30 +0000684 Attr *NewAttr = attr->clone(C);
685 NewAttr->setInherited(true);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000686 New->addAttr(NewAttr);
Chris Lattnerddee4232008-03-03 03:28:21 +0000687 }
688 }
689}
690
Douglas Gregorc8376562009-03-06 22:43:54 +0000691/// Used in MergeFunctionDecl to keep track of function parameters in
692/// C.
693struct GNUCompatibleParamWarning {
694 ParmVarDecl *OldParm;
695 ParmVarDecl *NewParm;
696 QualType PromotedType;
697};
698
Chris Lattner04421082008-04-08 04:40:51 +0000699/// MergeFunctionDecl - We just parsed a function 'New' from
700/// declarator D which has the same name and scope as a previous
701/// declaration 'Old'. Figure out how to resolve this situation,
702/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000703///
704/// In C++, New and Old must be declarations that are not
705/// overloaded. Use IsOverload to determine whether New and Old are
706/// overloaded, and to select the Old declaration that New should be
707/// merged with.
Douglas Gregorcda9c672009-02-16 17:45:42 +0000708///
709/// Returns true if there was an error, false otherwise.
710bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Mike Stump1eb44332009-09-09 15:08:12 +0000711 assert(!isa<OverloadedFunctionDecl>(OldD) &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000712 "Cannot merge with an overloaded function declaration");
713
Reid Spencer5f016e22007-07-11 17:01:13 +0000714 // Verify the old decl was also a function.
Douglas Gregore53060f2009-06-25 22:08:12 +0000715 FunctionDecl *Old = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000716 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregore53060f2009-06-25 22:08:12 +0000717 = dyn_cast<FunctionTemplateDecl>(OldD))
718 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000719 else
Douglas Gregore53060f2009-06-25 22:08:12 +0000720 Old = dyn_cast<FunctionDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000721 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000722 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000723 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000724 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000725 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000727
728 // Determine whether the previous declaration was a definition,
729 // implicit declaration, or a declaration.
730 diag::kind PrevDiag;
731 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000732 PrevDiag = diag::note_previous_definition;
Douglas Gregorcda9c672009-02-16 17:45:42 +0000733 else if (Old->isImplicit())
734 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +0000735 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000736 PrevDiag = diag::note_previous_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000738 QualType OldQType = Context.getCanonicalType(Old->getType());
739 QualType NewQType = Context.getCanonicalType(New->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Douglas Gregor04495c82009-02-24 01:23:02 +0000741 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
742 New->getStorageClass() == FunctionDecl::Static &&
743 Old->getStorageClass() != FunctionDecl::Static) {
744 Diag(New->getLocation(), diag::err_static_non_static)
745 << New;
746 Diag(Old->getLocation(), PrevDiag);
747 return true;
748 }
749
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000750 if (getLangOptions().CPlusPlus) {
751 // (C++98 13.1p2):
752 // Certain function declarations cannot be overloaded:
Mike Stump1eb44332009-09-09 15:08:12 +0000753 // -- Function declarations that differ only in the return type
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000754 // cannot be overloaded.
Mike Stump1eb44332009-09-09 15:08:12 +0000755 QualType OldReturnType
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000756 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000757 QualType NewReturnType
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000758 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
759 if (OldReturnType != NewReturnType) {
760 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000761 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000762 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000763 }
764
765 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
766 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall02cace72009-08-28 07:59:38 +0000767 if (OldMethod && NewMethod && !NewMethod->getFriendObjectKind() &&
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000768 NewMethod->getLexicalDeclContext()->isRecord()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000769 // -- Member function declarations with the same name and the
770 // same parameter types cannot be overloaded if any of them
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000771 // is a static member function declaration.
772 if (OldMethod->isStatic() || NewMethod->isStatic()) {
773 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000774 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000775 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000776 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000777
778 // C++ [class.mem]p1:
779 // [...] A member shall not be declared twice in the
780 // member-specification, except that a nested class or member
781 // class template can be declared and then later defined.
Douglas Gregor656de632009-03-11 23:52:16 +0000782 unsigned NewDiag;
783 if (isa<CXXConstructorDecl>(OldMethod))
784 NewDiag = diag::err_constructor_redeclared;
785 else if (isa<CXXDestructorDecl>(NewMethod))
786 NewDiag = diag::err_destructor_redeclared;
787 else if (isa<CXXConversionDecl>(NewMethod))
788 NewDiag = diag::err_conv_function_redeclared;
789 else
790 NewDiag = diag::err_member_redeclared;
Mike Stump1eb44332009-09-09 15:08:12 +0000791
Douglas Gregor656de632009-03-11 23:52:16 +0000792 Diag(New->getLocation(), NewDiag);
793 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000794 }
795
796 // (C++98 8.3.5p3):
797 // All declarations for a function shall agree exactly in both the
798 // return type and the parameter-type-list.
Douglas Gregor04495c82009-02-24 01:23:02 +0000799 if (OldQType == NewQType)
800 return MergeCompatibleFunctionDecls(New, Old);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000801
802 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000803 }
Chris Lattner04421082008-04-08 04:40:51 +0000804
805 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000806 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000807 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000808 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall183700f2009-09-21 23:43:11 +0000809 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
810 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +0000811 const FunctionProtoType *OldProto = 0;
812 if (isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregorc8376562009-03-06 22:43:54 +0000813 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregor68719812009-02-16 18:20:44 +0000814 // The old declaration provided a function prototype, but the
815 // new declaration does not. Merge in the prototype.
Sebastian Redl465226e2009-05-27 22:11:52 +0000816 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Douglas Gregor68719812009-02-16 18:20:44 +0000817 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
818 OldProto->arg_type_end());
819 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jay Foadbeaaccd2009-05-21 09:52:38 +0000820 ParamTypes.data(), ParamTypes.size(),
Douglas Gregor68719812009-02-16 18:20:44 +0000821 OldProto->isVariadic(),
822 OldProto->getTypeQuals());
823 New->setType(NewQType);
Anders Carlssona75e8532009-05-14 21:46:00 +0000824 New->setHasInheritedPrototype();
Douglas Gregor450da982009-02-16 20:58:07 +0000825
826 // Synthesize a parameter for each argument type.
827 llvm::SmallVector<ParmVarDecl*, 16> Params;
Mike Stump1eb44332009-09-09 15:08:12 +0000828 for (FunctionProtoType::arg_type_iterator
829 ParamType = OldProto->arg_type_begin(),
Douglas Gregor450da982009-02-16 20:58:07 +0000830 ParamEnd = OldProto->arg_type_end();
831 ParamType != ParamEnd; ++ParamType) {
832 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
833 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000834 *ParamType, /*DInfo=*/0,
835 VarDecl::None, 0);
Douglas Gregor450da982009-02-16 20:58:07 +0000836 Param->setImplicit();
837 Params.push_back(Param);
838 }
839
Jay Foadbeaaccd2009-05-21 09:52:38 +0000840 New->setParams(Context, Params.data(), Params.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000841 }
Douglas Gregor68719812009-02-16 18:20:44 +0000842
Douglas Gregor04495c82009-02-24 01:23:02 +0000843 return MergeCompatibleFunctionDecls(New, Old);
Chris Lattner04421082008-04-08 04:40:51 +0000844 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000845
Douglas Gregorc8376562009-03-06 22:43:54 +0000846 // GNU C permits a K&R definition to follow a prototype declaration
847 // if the declared types of the parameters in the K&R definition
848 // match the types in the prototype declaration, even when the
849 // promoted types of the parameters from the K&R definition differ
850 // from the types in the prototype. GCC then keeps the types from
851 // the prototype.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +0000852 //
853 // If a variadic prototype is followed by a non-variadic K&R definition,
854 // the K&R definition becomes variadic. This is sort of an edge case, but
855 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
856 // C99 6.9.1p8.
Douglas Gregorc8376562009-03-06 22:43:54 +0000857 if (!getLangOptions().CPlusPlus &&
Douglas Gregorc8376562009-03-06 22:43:54 +0000858 Old->hasPrototype() && !New->hasPrototype() &&
John McCall183700f2009-09-21 23:43:11 +0000859 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregorc8376562009-03-06 22:43:54 +0000860 Old->getNumParams() == New->getNumParams()) {
861 llvm::SmallVector<QualType, 16> ArgTypes;
862 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump1eb44332009-09-09 15:08:12 +0000863 const FunctionProtoType *OldProto
John McCall183700f2009-09-21 23:43:11 +0000864 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +0000865 const FunctionProtoType *NewProto
John McCall183700f2009-09-21 23:43:11 +0000866 = New->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Douglas Gregorc8376562009-03-06 22:43:54 +0000868 // Determine whether this is the GNU C extension.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +0000869 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
870 NewProto->getResultType());
871 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump1eb44332009-09-09 15:08:12 +0000872 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +0000873 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregorc8376562009-03-06 22:43:54 +0000874 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
875 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump1eb44332009-09-09 15:08:12 +0000876 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregorc8376562009-03-06 22:43:54 +0000877 NewProto->getArgType(Idx))) {
878 ArgTypes.push_back(NewParm->getType());
879 } else if (Context.typesAreCompatible(OldParm->getType(),
880 NewParm->getType())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000881 GNUCompatibleParamWarning Warn
Douglas Gregorc8376562009-03-06 22:43:54 +0000882 = { OldParm, NewParm, NewProto->getArgType(Idx) };
883 Warnings.push_back(Warn);
884 ArgTypes.push_back(NewParm->getType());
885 } else
Eli Friedmanbc4e29f2009-06-01 09:24:59 +0000886 LooseCompatible = false;
Douglas Gregorc8376562009-03-06 22:43:54 +0000887 }
888
Eli Friedmanbc4e29f2009-06-01 09:24:59 +0000889 if (LooseCompatible) {
Douglas Gregorc8376562009-03-06 22:43:54 +0000890 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
891 Diag(Warnings[Warn].NewParm->getLocation(),
892 diag::ext_param_promoted_not_compatible_with_prototype)
893 << Warnings[Warn].PromotedType
894 << Warnings[Warn].OldParm->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000895 Diag(Warnings[Warn].OldParm->getLocation(),
Douglas Gregorc8376562009-03-06 22:43:54 +0000896 diag::note_previous_declaration);
897 }
898
Eli Friedmanbc4e29f2009-06-01 09:24:59 +0000899 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
900 ArgTypes.size(),
901 OldProto->isVariadic(), 0));
Douglas Gregorc8376562009-03-06 22:43:54 +0000902 return MergeCompatibleFunctionDecls(New, Old);
903 }
904
905 // Fall through to diagnose conflicting types.
906 }
907
Steve Naroff837618c2008-01-16 15:01:34 +0000908 // A function that has already been declared has been redeclared or defined
909 // with a different type- show appropriate diagnostic
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000910 if (unsigned BuiltinID = Old->getBuiltinID()) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000911 // The user has declared a builtin function with an incompatible
912 // signature.
913 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
914 // The function the user is redeclaring is a library-defined
915 // function like 'malloc' or 'printf'. Warn about the
Douglas Gregor374e1562009-03-23 17:47:24 +0000916 // redeclaration, then pretend that we don't know about this
917 // library built-in.
Douglas Gregorcda9c672009-02-16 17:45:42 +0000918 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
919 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
920 << Old << Old->getType();
Douglas Gregor374e1562009-03-23 17:47:24 +0000921 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
922 Old->setInvalidDecl();
923 return false;
Douglas Gregorcda9c672009-02-16 17:45:42 +0000924 }
Steve Naroff837618c2008-01-16 15:01:34 +0000925
Douglas Gregorcda9c672009-02-16 17:45:42 +0000926 PrevDiag = diag::note_previous_builtin_declaration;
927 }
928
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000929 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000930 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000931 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000932}
933
Douglas Gregor04495c82009-02-24 01:23:02 +0000934/// \brief Completes the merge of two function declarations that are
Mike Stump1eb44332009-09-09 15:08:12 +0000935/// known to be compatible.
Douglas Gregor04495c82009-02-24 01:23:02 +0000936///
937/// This routine handles the merging of attributes and other
938/// properties of function declarations form the old declaration to
939/// the new declaration, once we know that New is in fact a
940/// redeclaration of Old.
941///
942/// \returns false
943bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
944 // Merge the attributes
Chris Lattnercc581472009-03-04 06:05:19 +0000945 MergeAttributes(New, Old, Context);
Douglas Gregor04495c82009-02-24 01:23:02 +0000946
947 // Merge the storage class.
Douglas Gregor1fc09a92009-09-13 07:46:26 +0000948 if (Old->getStorageClass() != FunctionDecl::Extern &&
949 Old->getStorageClass() != FunctionDecl::None)
Douglas Gregor9f9bf252009-04-28 06:37:30 +0000950 New->setStorageClass(Old->getStorageClass());
Douglas Gregor04495c82009-02-24 01:23:02 +0000951
Douglas Gregor04495c82009-02-24 01:23:02 +0000952 // Merge "pure" flag.
953 if (Old->isPure())
954 New->setPure();
955
956 // Merge the "deleted" flag.
957 if (Old->isDeleted())
958 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Douglas Gregor04495c82009-02-24 01:23:02 +0000960 if (getLangOptions().CPlusPlus)
961 return MergeCXXFunctionDecl(New, Old);
962
963 return false;
964}
965
Reid Spencer5f016e22007-07-11 17:01:13 +0000966/// MergeVarDecl - We just parsed a variable 'New' which has the same name
967/// and scope as a previous declaration 'Old'. Figure out how to resolve this
968/// situation, merging decls or emitting diagnostics as appropriate.
969///
Mike Stump1eb44332009-09-09 15:08:12 +0000970/// Tentative definition rules (C99 6.9.2p2) are checked by
971/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000972/// definitions here, since the initializer hasn't been attached.
Mike Stump1eb44332009-09-09 15:08:12 +0000973///
Chris Lattnereaaebc72009-04-25 08:06:05 +0000974void Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
975 // If either decl is invalid, make sure the new one is marked invalid and
976 // don't do any other checking.
977 if (New->isInvalidDecl() || OldD->isInvalidDecl())
978 return New->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Reid Spencer5f016e22007-07-11 17:01:13 +0000980 // Verify the old decl was also a variable.
981 VarDecl *Old = dyn_cast<VarDecl>(OldD);
982 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000983 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000984 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000985 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000986 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000987 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000988
Chris Lattnercc581472009-03-04 06:05:19 +0000989 MergeAttributes(New, Old, Context);
Chris Lattnerddee4232008-03-03 03:28:21 +0000990
Eli Friedman13ca96a2009-01-24 23:49:55 +0000991 // Merge the types
Eli Friedman88d936b2009-05-16 13:54:38 +0000992 QualType MergedT;
993 if (getLangOptions().CPlusPlus) {
994 if (Context.hasSameType(New->getType(), Old->getType()))
995 MergedT = New->getType();
Douglas Gregor3dab34a2009-09-09 01:45:28 +0000996 // C++ [basic.types]p7:
Mike Stump1eb44332009-09-09 15:08:12 +0000997 // [...] The declared type of an array object might be an array of
998 // unknown size and therefore be incomplete at one point in a
Douglas Gregor3dab34a2009-09-09 01:45:28 +0000999 // translation unit and complete later on; [...]
Mike Stump1eb44332009-09-09 15:08:12 +00001000 else if (Old->getType()->isIncompleteArrayType() &&
Douglas Gregor8dfb7ec2009-09-09 06:04:29 +00001001 New->getType()->isArrayType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001002 CanQual<ArrayType> OldArray
Douglas Gregor8dfb7ec2009-09-09 06:04:29 +00001003 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001004 CanQual<ArrayType> NewArray
Douglas Gregor8dfb7ec2009-09-09 06:04:29 +00001005 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1006 if (OldArray->getElementType() == NewArray->getElementType())
1007 MergedT = New->getType();
1008 }
Eli Friedman88d936b2009-05-16 13:54:38 +00001009 } else {
1010 MergedT = Context.mergeTypes(New->getType(), Old->getType());
1011 }
Eli Friedman13ca96a2009-01-24 23:49:55 +00001012 if (MergedT.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001013 Diag(New->getLocation(), diag::err_redefinition_different_type)
Douglas Gregor6037fcb2009-01-09 19:42:16 +00001014 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001015 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001016 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001017 }
Eli Friedman13ca96a2009-01-24 23:49:55 +00001018 New->setType(MergedT);
Douglas Gregor656de632009-03-11 23:52:16 +00001019
Steve Naroffb7b032e2008-01-30 00:44:01 +00001020 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
1021 if (New->getStorageClass() == VarDecl::Static &&
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00001022 (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001023 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001024 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001025 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00001026 }
Mike Stump1eb44332009-09-09 15:08:12 +00001027 // C99 6.2.2p4:
Douglas Gregor5ef122e2009-03-19 22:01:50 +00001028 // For an identifier declared with the storage-class specifier
1029 // extern in a scope in which a prior declaration of that
1030 // identifier is visible,23) if the prior declaration specifies
1031 // internal or external linkage, the linkage of the identifier at
1032 // the later declaration is the same as the linkage specified at
1033 // the prior declaration. If no prior declaration is visible, or
1034 // if the prior declaration specifies no linkage, then the
1035 // identifier has external linkage.
Douglas Gregor38179b22009-03-23 16:17:01 +00001036 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor5ef122e2009-03-19 22:01:50 +00001037 /* Okay */;
1038 else if (New->getStorageClass() != VarDecl::Static &&
1039 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001040 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001041 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001042 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00001043 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00001044
Steve Naroff094cefb2008-09-17 14:05:40 +00001045 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump1eb44332009-09-09 15:08:12 +00001046
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00001047 // FIXME: The test for external storage here seems wrong? We still
1048 // need to check for mismatches.
1049 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor656de632009-03-11 23:52:16 +00001050 // Don't complain about out-of-line definitions of static members.
1051 !(Old->getLexicalDeclContext()->isRecord() &&
1052 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattner08631c52008-11-23 21:45:46 +00001053 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001054 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001055 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001056 }
Douglas Gregor275a3692009-03-10 23:43:53 +00001057
Eli Friedman63054b32009-04-19 20:27:55 +00001058 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1059 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1060 Diag(Old->getLocation(), diag::note_previous_definition);
1061 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1062 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1063 Diag(Old->getLocation(), diag::note_previous_definition);
1064 }
1065
Douglas Gregor275a3692009-03-10 23:43:53 +00001066 // Keep a chain of previous declarations.
1067 New->setPreviousDeclaration(Old);
Reid Spencer5f016e22007-07-11 17:01:13 +00001068}
1069
Mike Stump5f28a1e2009-07-24 02:49:01 +00001070/// CheckFallThrough - Check that we don't fall off the end of a
1071/// Statement that should return a value.
1072///
1073/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
Mike Stumpcf57d612009-10-27 02:07:23 +00001074/// MaybeFallThrough iff we might or might not fall off the end,
1075/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
1076/// return. We assume NeverFallThrough iff we never fall off the end of the
1077/// statement but we may return. We assume that functions not marked noreturn
1078/// will return.
Mike Stumpb1682c52009-07-22 23:56:57 +00001079Sema::ControlFlowKind Sema::CheckFallThrough(Stmt *Root) {
Ted Kremenekcd6cdeb2009-10-20 23:48:29 +00001080 // FIXME: Eventually share this CFG object when we have other warnings based
1081 // of the CFG. This can be done using AnalysisContext.
Mike Stumpb1682c52009-07-22 23:56:57 +00001082 llvm::OwningPtr<CFG> cfg (CFG::buildCFG(Root, &Context));
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Mike Stumpb1682c52009-07-22 23:56:57 +00001084 // FIXME: They should never return 0, fix that, delete this code.
1085 if (cfg == 0)
Mike Stump1d7e7672009-10-27 01:59:05 +00001086 // FIXME: This should be NeverFallThrough
1087 return NeverFallThroughOrReturn;
Mike Stump79a14112009-07-23 22:40:11 +00001088 // The CFG leaves in dead things, and we don't want to dead code paths to
1089 // confuse us, so we mark all live things first.
Mike Stumpb1682c52009-07-22 23:56:57 +00001090 std::queue<CFGBlock*> workq;
Daniel Dunbar1f15e762009-07-23 05:01:54 +00001091 llvm::BitVector live(cfg->getNumBlockIDs());
Mike Stumpb1682c52009-07-22 23:56:57 +00001092 // Prep work queue
1093 workq.push(&cfg->getEntry());
1094 // Solve
1095 while (!workq.empty()) {
1096 CFGBlock *item = workq.front();
1097 workq.pop();
Daniel Dunbar1f15e762009-07-23 05:01:54 +00001098 live.set(item->getBlockID());
Mike Stump79a14112009-07-23 22:40:11 +00001099 for (CFGBlock::succ_iterator I=item->succ_begin(),
1100 E=item->succ_end();
1101 I != E;
1102 ++I) {
1103 if ((*I) && !live[(*I)->getBlockID()]) {
1104 live.set((*I)->getBlockID());
1105 workq.push(*I);
Mike Stumpb1682c52009-07-22 23:56:57 +00001106 }
1107 }
1108 }
1109
Mike Stump79a14112009-07-23 22:40:11 +00001110 // Now we know what is live, we check the live precessors of the exit block
1111 // and look for fall through paths, being careful to ignore normal returns,
1112 // and exceptional paths.
Mike Stumpb1682c52009-07-22 23:56:57 +00001113 bool HasLiveReturn = false;
1114 bool HasFakeEdge = false;
1115 bool HasPlainEdge = false;
Ted Kremenek77622912009-10-27 01:07:53 +00001116 for (CFGBlock::pred_iterator I=cfg->getExit().pred_begin(),
Mike Stump79a14112009-07-23 22:40:11 +00001117 E = cfg->getExit().pred_end();
1118 I != E;
1119 ++I) {
1120 CFGBlock& B = **I;
1121 if (!live[B.getBlockID()])
Mike Stumpb1682c52009-07-22 23:56:57 +00001122 continue;
Mike Stump79a14112009-07-23 22:40:11 +00001123 if (B.size() == 0) {
Mike Stumpb1682c52009-07-22 23:56:57 +00001124 // A labeled empty statement, or the entry block...
1125 HasPlainEdge = true;
1126 continue;
1127 }
Mike Stump79a14112009-07-23 22:40:11 +00001128 Stmt *S = B[B.size()-1];
Mike Stumpb1682c52009-07-22 23:56:57 +00001129 if (isa<ReturnStmt>(S)) {
1130 HasLiveReturn = true;
1131 continue;
1132 }
1133 if (isa<ObjCAtThrowStmt>(S)) {
1134 HasFakeEdge = true;
1135 continue;
1136 }
1137 if (isa<CXXThrowExpr>(S)) {
1138 HasFakeEdge = true;
1139 continue;
1140 }
1141 bool NoReturnEdge = false;
Mike Stump79a14112009-07-23 22:40:11 +00001142 if (CallExpr *C = dyn_cast<CallExpr>(S)) {
1143 Expr *CEE = C->getCallee()->IgnoreParenCasts();
Mike Stump24556362009-07-25 21:26:53 +00001144 if (CEE->getType().getNoReturnAttr()) {
1145 NoReturnEdge = true;
1146 HasFakeEdge = true;
1147 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
Mike Stump79a14112009-07-23 22:40:11 +00001148 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1149 if (FD->hasAttr<NoReturnAttr>()) {
1150 NoReturnEdge = true;
1151 HasFakeEdge = true;
Mike Stumpb1682c52009-07-22 23:56:57 +00001152 }
1153 }
1154 }
Mike Stump79a14112009-07-23 22:40:11 +00001155 }
1156 // FIXME: Add noreturn message sends.
Mike Stumpb1682c52009-07-22 23:56:57 +00001157 if (NoReturnEdge == false)
1158 HasPlainEdge = true;
1159 }
Mike Stump1d7e7672009-10-27 01:59:05 +00001160 if (!HasPlainEdge) {
1161 if (HasLiveReturn)
1162 return NeverFallThrough;
1163 return NeverFallThroughOrReturn;
1164 }
Mike Stump79a14112009-07-23 22:40:11 +00001165 if (HasFakeEdge || HasLiveReturn)
1166 return MaybeFallThrough;
1167 // This says AlwaysFallThrough for calls to functions that are not marked
1168 // noreturn, that don't return. If people would like this warning to be more
1169 // accurate, such functions should be marked as noreturn.
1170 return AlwaysFallThrough;
Mike Stumpb1682c52009-07-22 23:56:57 +00001171}
1172
1173/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
Mike Stump5f28a1e2009-07-24 02:49:01 +00001174/// function that should return a value. Check that we don't fall off the end
Mike Stump56925862009-07-28 22:04:01 +00001175/// of a noreturn function. We assume that functions and blocks not marked
1176/// noreturn will return.
Mike Stumpb1682c52009-07-22 23:56:57 +00001177void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body) {
Mike Stump79a14112009-07-23 22:40:11 +00001178 // FIXME: Would be nice if we had a better way to control cascading errors,
1179 // but for now, avoid them. The problem is that when Parse sees:
1180 // int foo() { return a; }
1181 // The return is eaten and the Sema code sees just:
1182 // int foo() { }
1183 // which this code would then warn about.
Mike Stumpb1682c52009-07-22 23:56:57 +00001184 if (getDiagnostics().hasErrorOccurred())
1185 return;
Chris Lattner7a128e82009-10-25 22:43:07 +00001186
Mike Stump5f28a1e2009-07-24 02:49:01 +00001187 bool ReturnsVoid = false;
1188 bool HasNoReturn = false;
1189 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1be8aee2009-10-01 23:25:31 +00001190 // If the result type of the function is a dependent type, we don't know
1191 // whether it will be void or not, so don't
1192 if (FD->getResultType()->isDependentType())
1193 return;
Mike Stump5f28a1e2009-07-24 02:49:01 +00001194 if (FD->getResultType()->isVoidType())
1195 ReturnsVoid = true;
1196 if (FD->hasAttr<NoReturnAttr>())
1197 HasNoReturn = true;
1198 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
1199 if (MD->getResultType()->isVoidType())
1200 ReturnsVoid = true;
1201 if (MD->hasAttr<NoReturnAttr>())
1202 HasNoReturn = true;
1203 }
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Mike Stump4d9d51a2009-07-28 23:11:12 +00001205 // Short circuit for compilation speed.
Mike Stump5f28a1e2009-07-24 02:49:01 +00001206 if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function)
1207 == Diagnostic::Ignored || ReturnsVoid)
1208 && (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr)
Mike Stump4d9d51a2009-07-28 23:11:12 +00001209 == Diagnostic::Ignored || !HasNoReturn)
1210 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
1211 == Diagnostic::Ignored || !ReturnsVoid))
Mike Stumpb1682c52009-07-22 23:56:57 +00001212 return;
Douglas Gregor1be8aee2009-10-01 23:25:31 +00001213 // FIXME: Function try block
Mike Stumpb1682c52009-07-22 23:56:57 +00001214 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
1215 switch (CheckFallThrough(Body)) {
1216 case MaybeFallThrough:
Mike Stump5f28a1e2009-07-24 02:49:01 +00001217 if (HasNoReturn)
1218 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
1219 else if (!ReturnsVoid)
1220 Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function);
Mike Stumpb1682c52009-07-22 23:56:57 +00001221 break;
1222 case AlwaysFallThrough:
Mike Stump5f28a1e2009-07-24 02:49:01 +00001223 if (HasNoReturn)
1224 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
1225 else if (!ReturnsVoid)
1226 Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function);
Mike Stumpb1682c52009-07-22 23:56:57 +00001227 break;
Mike Stump1d7e7672009-10-27 01:59:05 +00001228 case NeverFallThroughOrReturn:
Chris Lattner7a128e82009-10-25 22:43:07 +00001229 if (ReturnsVoid && !HasNoReturn)
Mike Stump4d9d51a2009-07-28 23:11:12 +00001230 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function);
Mike Stumpb1682c52009-07-22 23:56:57 +00001231 break;
Mike Stump1d7e7672009-10-27 01:59:05 +00001232 case NeverFallThrough:
1233 break;
Mike Stumpb1682c52009-07-22 23:56:57 +00001234 }
1235 }
1236}
1237
Mike Stump56925862009-07-28 22:04:01 +00001238/// CheckFallThroughForBlock - Check that we don't fall off the end of a block
1239/// that should return a value. Check that we don't fall off the end of a
1240/// noreturn block. We assume that functions and blocks not marked noreturn
1241/// will return.
1242void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body) {
1243 // FIXME: Would be nice if we had a better way to control cascading errors,
1244 // but for now, avoid them. The problem is that when Parse sees:
1245 // int foo() { return a; }
1246 // The return is eaten and the Sema code sees just:
1247 // int foo() { }
1248 // which this code would then warn about.
1249 if (getDiagnostics().hasErrorOccurred())
1250 return;
1251 bool ReturnsVoid = false;
1252 bool HasNoReturn = false;
Chris Lattner7a128e82009-10-25 22:43:07 +00001253 if (const FunctionType *FT =BlockTy->getPointeeType()->getAs<FunctionType>()){
Mike Stump56925862009-07-28 22:04:01 +00001254 if (FT->getResultType()->isVoidType())
1255 ReturnsVoid = true;
1256 if (FT->getNoReturnAttr())
1257 HasNoReturn = true;
1258 }
Mike Stump1eb44332009-09-09 15:08:12 +00001259
Mike Stump4d9d51a2009-07-28 23:11:12 +00001260 // Short circuit for compilation speed.
1261 if (ReturnsVoid
1262 && !HasNoReturn
1263 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
1264 == Diagnostic::Ignored || !ReturnsVoid))
Mike Stump56925862009-07-28 22:04:01 +00001265 return;
1266 // FIXME: Funtion try block
1267 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
1268 switch (CheckFallThrough(Body)) {
1269 case MaybeFallThrough:
1270 if (HasNoReturn)
1271 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
1272 else if (!ReturnsVoid)
1273 Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block);
1274 break;
1275 case AlwaysFallThrough:
1276 if (HasNoReturn)
1277 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
1278 else if (!ReturnsVoid)
1279 Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block);
1280 break;
Mike Stump1d7e7672009-10-27 01:59:05 +00001281 case NeverFallThroughOrReturn:
Mike Stump4d9d51a2009-07-28 23:11:12 +00001282 if (ReturnsVoid)
1283 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block);
Mike Stump56925862009-07-28 22:04:01 +00001284 break;
Mike Stump1d7e7672009-10-27 01:59:05 +00001285 case NeverFallThrough:
1286 break;
Mike Stump56925862009-07-28 22:04:01 +00001287 }
1288 }
1289}
1290
Chris Lattner04421082008-04-08 04:40:51 +00001291/// CheckParmsForFunctionDef - Check that the parameters of the given
1292/// function are appropriate for the definition of a function. This
1293/// takes care of any checks that cannot be performed on the
1294/// declaration itself, e.g., that the types of each of the function
1295/// parameters are complete.
1296bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
1297 bool HasInvalidParm = false;
1298 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1299 ParmVarDecl *Param = FD->getParamDecl(p);
1300
1301 // C99 6.7.5.3p4: the parameters in a parameter type list in a
1302 // function declarator that is part of a function definition of
1303 // that function shall not have incomplete type.
Douglas Gregore7450f52009-03-24 19:52:54 +00001304 //
1305 // This is also C++ [dcl.fct]p6.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00001306 if (!Param->isInvalidDecl() &&
Douglas Gregor86447ec2009-03-09 16:13:40 +00001307 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00001308 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattner04421082008-04-08 04:40:51 +00001309 Param->setInvalidDecl();
1310 HasInvalidParm = true;
1311 }
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Chris Lattner777f07b2008-12-17 07:32:46 +00001313 // C99 6.9.1p5: If the declarator includes a parameter type list, the
1314 // declaration of each parameter shall include an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00001315 if (Param->getIdentifier() == 0 &&
Douglas Gregor450da982009-02-16 20:58:07 +00001316 !Param->isImplicit() &&
1317 !getLangOptions().CPlusPlus)
Chris Lattner777f07b2008-12-17 07:32:46 +00001318 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +00001319 }
1320
1321 return HasInvalidParm;
1322}
1323
Reid Spencer5f016e22007-07-11 17:01:13 +00001324/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1325/// no declarator (e.g. "struct foo;") is parsed.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001326Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Eli Friedmand2968362009-04-09 21:26:42 +00001327 // FIXME: Error on auto/register at file scope
1328 // FIXME: Error on inline/virtual/explicit
1329 // FIXME: Error on invalid restrict
Eli Friedman63054b32009-04-19 20:27:55 +00001330 // FIXME: Warn on useless __thread
Eli Friedmand2968362009-04-09 21:26:42 +00001331 // FIXME: Warn on useless const/volatile
1332 // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1333 // FIXME: Warn on useless attributes
John McCalle3af0232009-10-07 23:34:25 +00001334 Decl *TagD = 0;
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001335 TagDecl *Tag = 0;
1336 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1337 DS.getTypeSpecType() == DeclSpec::TST_struct ||
1338 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00001339 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCalle3af0232009-10-07 23:34:25 +00001340 TagD = static_cast<Decl *>(DS.getTypeRep());
1341
1342 if (!TagD) // We probably had an error
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00001343 return DeclPtrTy();
1344
John McCall67d1a672009-08-06 02:15:43 +00001345 // Note that the above type specs guarantee that the
1346 // type rep is a Decl, whereas in many of the others
1347 // it's a Type.
John McCalle3af0232009-10-07 23:34:25 +00001348 Tag = dyn_cast<TagDecl>(TagD);
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00001349 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001350
Douglas Gregord85bea22009-09-26 06:47:28 +00001351 if (DS.isFriendSpecified()) {
John McCalle3af0232009-10-07 23:34:25 +00001352 // If we're dealing with a class template decl, assume that the
1353 // template routines are handling it.
1354 if (TagD && isa<ClassTemplateDecl>(TagD))
Douglas Gregord85bea22009-09-26 06:47:28 +00001355 return DeclPtrTy();
John McCalle3af0232009-10-07 23:34:25 +00001356 return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
Douglas Gregord85bea22009-09-26 06:47:28 +00001357 }
1358
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001359 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
Chris Lattnerd451f832009-10-25 22:21:57 +00001360 // If there are attributes in the DeclSpec, apply them to the record.
1361 if (const AttributeList *AL = DS.getAttributes())
1362 ProcessDeclAttributeList(S, Record, AL);
1363
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001364 if (!Record->getDeclName() && Record->isDefinition() &&
Douglas Gregora71c1292009-03-06 23:06:59 +00001365 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1366 if (getLangOptions().CPlusPlus ||
1367 Record->getDeclContext()->isRecord())
1368 return BuildAnonymousStructOrUnion(S, DS, Record);
1369
1370 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1371 << DS.getSourceRange();
1372 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001373
1374 // Microsoft allows unnamed struct/union fields. Don't complain
1375 // about them.
1376 // FIXME: Should we support Microsoft's extensions in this area?
1377 if (Record->getDeclName() && getLangOptions().Microsoft)
Chris Lattnerb28317a2009-03-28 19:18:32 +00001378 return DeclPtrTy::make(Tag);
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001379 }
Douglas Gregord85bea22009-09-26 06:47:28 +00001380
Mike Stump1eb44332009-09-09 15:08:12 +00001381 if (!DS.isMissingDeclaratorOk() &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00001382 DS.getTypeSpecType() != DeclSpec::TST_error) {
Douglas Gregor21282df2009-01-22 16:23:54 +00001383 // Warn about typedefs of enums without names, since this is an
1384 // extension in both Microsoft an GNU.
Douglas Gregor8158f692009-01-17 02:55:50 +00001385 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1386 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregor21282df2009-01-22 16:23:54 +00001387 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregoree159c12009-01-13 23:10:51 +00001388 << DS.getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00001389 return DeclPtrTy::make(Tag);
Douglas Gregoree159c12009-01-13 23:10:51 +00001390 }
1391
Sebastian Redla4ed0d82008-12-28 15:28:59 +00001392 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1393 << DS.getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00001394 return DeclPtrTy();
Sebastian Redla4ed0d82008-12-28 15:28:59 +00001395 }
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Chris Lattnerb28317a2009-03-28 19:18:32 +00001397 return DeclPtrTy::make(Tag);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001398}
1399
1400/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1401/// anonymous struct or union AnonRecord into the owning context Owner
1402/// and scope S. This routine will be invoked just after we realize
1403/// that an unnamed union or struct is actually an anonymous union or
1404/// struct, e.g.,
1405///
1406/// @code
1407/// union {
1408/// int i;
1409/// float f;
1410/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1411/// // f into the surrounding scope.x
1412/// @endcode
1413///
1414/// This routine is recursive, injecting the names of nested anonymous
1415/// structs/unions into the owning context and scope as well.
1416bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
1417 RecordDecl *AnonRecord) {
1418 bool Invalid = false;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001419 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
1420 FEnd = AnonRecord->field_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001421 F != FEnd; ++F) {
1422 if ((*F)->getDeclName()) {
John McCalla24dc2e2009-11-17 02:14:36 +00001423 LookupResult R(*this, (*F)->getDeclName(), SourceLocation(),
1424 LookupOrdinaryName, LookupResult::ForRedeclaration);
1425 LookupQualifiedName(R, Owner);
John McCallf36e02d2009-10-09 21:13:30 +00001426 NamedDecl *PrevDecl = R.getAsSingleDecl(Context);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001427 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
1428 // C++ [class.union]p2:
1429 // The names of the members of an anonymous union shall be
1430 // distinct from the names of any other entity in the
1431 // scope in which the anonymous union is declared.
Mike Stump1eb44332009-09-09 15:08:12 +00001432 unsigned diagKind
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001433 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
1434 : diag::err_anonymous_struct_member_redecl;
1435 Diag((*F)->getLocation(), diagKind)
1436 << (*F)->getDeclName();
1437 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
1438 Invalid = true;
1439 } else {
1440 // C++ [class.union]p2:
1441 // For the purpose of name lookup, after the anonymous union
1442 // definition, the members of the anonymous union are
1443 // considered to have been defined in the scope in which the
1444 // anonymous union is declared.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001445 Owner->makeDeclVisibleInContext(*F);
Chris Lattnerb28317a2009-03-28 19:18:32 +00001446 S->AddDecl(DeclPtrTy::make(*F));
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001447 IdResolver.AddDecl(*F);
1448 }
1449 } else if (const RecordType *InnerRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001450 = (*F)->getType()->getAs<RecordType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001451 RecordDecl *InnerRecord = InnerRecordType->getDecl();
1452 if (InnerRecord->isAnonymousStructOrUnion())
Mike Stump1eb44332009-09-09 15:08:12 +00001453 Invalid = Invalid ||
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001454 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
1455 }
1456 }
1457
1458 return Invalid;
1459}
1460
1461/// ActOnAnonymousStructOrUnion - Handle the declaration of an
1462/// anonymous structure or union. Anonymous unions are a C++ feature
1463/// (C++ [class.union]) and a GNU C extension; anonymous structures
Mike Stump1eb44332009-09-09 15:08:12 +00001464/// are a GNU C and GNU C++ extension.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001465Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1466 RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001467 DeclContext *Owner = Record->getDeclContext();
1468
1469 // Diagnose whether this anonymous struct/union is an extension.
1470 if (Record->isUnion() && !getLangOptions().CPlusPlus)
1471 Diag(Record->getLocation(), diag::ext_anonymous_union);
1472 else if (!Record->isUnion())
1473 Diag(Record->getLocation(), diag::ext_anonymous_struct);
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001475 // C and C++ require different kinds of checks for anonymous
1476 // structs/unions.
1477 bool Invalid = false;
1478 if (getLangOptions().CPlusPlus) {
1479 const char* PrevSpec = 0;
John McCallfec54012009-08-03 20:12:06 +00001480 unsigned DiagID;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001481 // C++ [class.union]p3:
1482 // Anonymous unions declared in a named namespace or in the
1483 // global namespace shall be declared static.
1484 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1485 (isa<TranslationUnitDecl>(Owner) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001486 (isa<NamespaceDecl>(Owner) &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001487 cast<NamespaceDecl>(Owner)->getDeclName()))) {
1488 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1489 Invalid = true;
1490
1491 // Recover by adding 'static'.
John McCallfec54012009-08-03 20:12:06 +00001492 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1493 PrevSpec, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +00001494 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001495 // C++ [class.union]p3:
1496 // A storage class is not allowed in a declaration of an
1497 // anonymous union in a class scope.
1498 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1499 isa<RecordDecl>(Owner)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001500 Diag(DS.getStorageClassSpecLoc(),
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001501 diag::err_anonymous_union_with_storage_spec);
1502 Invalid = true;
1503
1504 // Recover by removing the storage specifier.
1505 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
John McCallfec54012009-08-03 20:12:06 +00001506 PrevSpec, DiagID);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001507 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001508
Mike Stump1eb44332009-09-09 15:08:12 +00001509 // C++ [class.union]p2:
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001510 // The member-specification of an anonymous union shall only
1511 // define non-static data members. [Note: nested types and
1512 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001513 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1514 MemEnd = Record->decls_end();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001515 Mem != MemEnd; ++Mem) {
1516 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1517 // C++ [class.union]p3:
1518 // An anonymous union shall not have private or protected
1519 // members (clause 11).
1520 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
1521 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1522 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1523 Invalid = true;
1524 }
1525 } else if ((*Mem)->isImplicit()) {
1526 // Any implicit members are fine.
Douglas Gregor1931b442009-02-03 00:34:39 +00001527 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1528 // This is a type that showed up in an
1529 // elaborated-type-specifier inside the anonymous struct or
1530 // union, but which actually declares a type outside of the
1531 // anonymous struct or union. It's okay.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001532 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1533 if (!MemRecord->isAnonymousStructOrUnion() &&
1534 MemRecord->getDeclName()) {
1535 // This is a nested type declaration.
1536 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1537 << (int)Record->isUnion();
1538 Invalid = true;
1539 }
1540 } else {
1541 // We have something that isn't a non-static data
1542 // member. Complain about it.
1543 unsigned DK = diag::err_anonymous_record_bad_member;
1544 if (isa<TypeDecl>(*Mem))
1545 DK = diag::err_anonymous_record_with_type;
1546 else if (isa<FunctionDecl>(*Mem))
1547 DK = diag::err_anonymous_record_with_function;
1548 else if (isa<VarDecl>(*Mem))
1549 DK = diag::err_anonymous_record_with_static;
1550 Diag((*Mem)->getLocation(), DK)
1551 << (int)Record->isUnion();
1552 Invalid = true;
1553 }
1554 }
Mike Stump1eb44332009-09-09 15:08:12 +00001555 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001556
1557 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001558 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1559 << (int)getLangOptions().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001560 Invalid = true;
1561 }
1562
John McCalleb692e02009-10-22 23:31:08 +00001563 // Mock up a declarator.
1564 Declarator Dc(DS, Declarator::TypeNameContext);
1565 DeclaratorInfo *DInfo = 0;
1566 GetTypeForDeclarator(Dc, S, &DInfo);
1567 assert(DInfo && "couldn't build declarator info for anonymous struct/union");
1568
Mike Stump1eb44332009-09-09 15:08:12 +00001569 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001570 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001571 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1572 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001573 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001574 Context.getTypeDeclType(Record),
John McCalleb692e02009-10-22 23:31:08 +00001575 DInfo,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001576 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001577 Anon->setAccess(AS_public);
1578 if (getLangOptions().CPlusPlus)
1579 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001580 } else {
1581 VarDecl::StorageClass SC;
1582 switch (DS.getStorageClassSpec()) {
1583 default: assert(0 && "Unknown storage class!");
1584 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1585 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1586 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1587 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1588 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1589 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1590 case DeclSpec::SCS_mutable:
1591 // mutable can only appear on non-static class members, so it's always
1592 // an error here
1593 Diag(Record->getLocation(), diag::err_mutable_nonmember);
1594 Invalid = true;
1595 SC = VarDecl::None;
1596 break;
1597 }
1598
1599 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001600 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001601 Context.getTypeDeclType(Record),
John McCalleb692e02009-10-22 23:31:08 +00001602 DInfo,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001603 SC);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001604 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001605 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001606
1607 // Add the anonymous struct/union object to the current
1608 // context. We'll be referencing this object when we refer to one of
1609 // its members.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001610 Owner->addDecl(Anon);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001611
1612 // Inject the members of the anonymous struct/union into the owning
1613 // context and into the identifier resolver chain for name lookup
1614 // purposes.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001615 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1616 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001617
1618 // Mark this as an anonymous struct/union type. Note that we do not
1619 // do this until after we have already checked and injected the
1620 // members of this anonymous struct/union type, because otherwise
1621 // the members could be injected twice: once by DeclContext when it
1622 // builds its lookup table, and once by
Mike Stump1eb44332009-09-09 15:08:12 +00001623 // InjectAnonymousStructOrUnionMembers.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001624 Record->setAnonymousStructOrUnion(true);
1625
1626 if (Invalid)
1627 Anon->setInvalidDecl();
1628
Chris Lattnerb28317a2009-03-28 19:18:32 +00001629 return DeclPtrTy::make(Anon);
Reid Spencer5f016e22007-07-11 17:01:13 +00001630}
1631
Steve Narofff0090632007-09-02 02:04:30 +00001632
Douglas Gregor10bd3682008-11-17 22:58:34 +00001633/// GetNameForDeclarator - Determine the full declaration name for the
1634/// given Declarator.
1635DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001636 return GetNameFromUnqualifiedId(D.getName());
1637}
1638
1639/// \brief Retrieves the canonicalized name from a parsed unqualified-id.
1640DeclarationName Sema::GetNameFromUnqualifiedId(UnqualifiedId &Name) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001641 switch (Name.getKind()) {
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001642 case UnqualifiedId::IK_Identifier:
1643 return DeclarationName(Name.Identifier);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001644
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001645 case UnqualifiedId::IK_OperatorFunctionId:
1646 return Context.DeclarationNames.getCXXOperatorName(
1647 Name.OperatorFunctionId.Operator);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001648
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001649 case UnqualifiedId::IK_ConversionFunctionId: {
1650 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId);
1651 if (Ty.isNull())
1652 return DeclarationName();
Douglas Gregordb422df2009-09-25 21:45:23 +00001653
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001654 return Context.DeclarationNames.getCXXConversionFunctionName(
1655 Context.getCanonicalType(Ty));
1656 }
1657
1658 case UnqualifiedId::IK_ConstructorName: {
1659 QualType Ty = GetTypeFromParser(Name.ConstructorName);
1660 if (Ty.isNull())
1661 return DeclarationName();
1662
1663 return Context.DeclarationNames.getCXXConstructorName(
1664 Context.getCanonicalType(Ty));
1665 }
1666
1667 case UnqualifiedId::IK_DestructorName: {
1668 QualType Ty = GetTypeFromParser(Name.DestructorName);
1669 if (Ty.isNull())
1670 return DeclarationName();
1671
1672 return Context.DeclarationNames.getCXXDestructorName(
1673 Context.getCanonicalType(Ty));
1674 }
1675
1676 case UnqualifiedId::IK_TemplateId: {
1677 TemplateName TName
Douglas Gregor314b97f2009-11-10 19:49:08 +00001678 = TemplateName::getFromVoidPointer(Name.TemplateId->Template);
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001679 if (TemplateDecl *Template = TName.getAsTemplateDecl())
1680 return Template->getDeclName();
1681 if (OverloadedFunctionDecl *Ovl = TName.getAsOverloadedFunctionDecl())
1682 return Ovl->getDeclName();
1683
1684 return DeclarationName();
1685 }
Douglas Gregordb422df2009-09-25 21:45:23 +00001686 }
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001687
Douglas Gregor10bd3682008-11-17 22:58:34 +00001688 assert(false && "Unknown name kind");
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001689 return DeclarationName();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001690}
1691
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001692/// isNearlyMatchingFunction - Determine whether the C++ functions
1693/// Declaration and Definition are "nearly" matching. This heuristic
1694/// is used to improve diagnostics in the case where an out-of-line
1695/// function definition doesn't match any declaration within
1696/// the class or namespace.
1697static bool isNearlyMatchingFunction(ASTContext &Context,
1698 FunctionDecl *Declaration,
1699 FunctionDecl *Definition) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001700 if (Declaration->param_size() != Definition->param_size())
1701 return false;
1702 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1703 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1704 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1705
Douglas Gregora4923eb2009-11-16 21:35:15 +00001706 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
1707 DefParamTy.getNonReferenceType()))
Douglas Gregor584049d2008-12-15 23:53:10 +00001708 return false;
1709 }
1710
1711 return true;
1712}
1713
Mike Stump1eb44332009-09-09 15:08:12 +00001714Sema::DeclPtrTy
1715Sema::HandleDeclarator(Scope *S, Declarator &D,
Douglas Gregore542c862009-06-23 23:11:28 +00001716 MultiTemplateParamsArg TemplateParamLists,
1717 bool IsFunctionDefinition) {
Douglas Gregor10bd3682008-11-17 22:58:34 +00001718 DeclarationName Name = GetNameForDeclarator(D);
1719
Chris Lattnere80a59c2007-07-25 00:24:17 +00001720 // All of these full declarators require an identifier. If it doesn't have
1721 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001722 if (!Name) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00001723 if (!D.isInvalidType()) // Reject this if we think it is valid.
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001724 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001725 diag::err_declarator_need_ident)
1726 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00001727 return DeclPtrTy();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001728 }
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Chris Lattner31e05722007-08-26 06:24:45 +00001730 // The scope passed in may not be a decl scope. Zip up the scope tree until
1731 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001732 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregoraaba5e32009-02-04 19:02:06 +00001733 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001734 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001735
Douglas Gregor4a959d82009-08-06 16:20:37 +00001736 // If this is an out-of-line definition of a member of a class template
1737 // or class template partial specialization, we may need to rebuild the
1738 // type specifier in the declarator. See RebuildTypeInCurrentInstantiation()
1739 // for more information.
1740 // FIXME: cope with decltype(expr) and typeof(expr) once the rebuilder can
1741 // handle expressions properly.
1742 DeclSpec &DS = const_cast<DeclSpec&>(D.getDeclSpec());
1743 if (D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid() &&
1744 isDependentScopeSpecifier(D.getCXXScopeSpec()) &&
1745 (DS.getTypeSpecType() == DeclSpec::TST_typename ||
1746 DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
1747 DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
1748 DS.getTypeSpecType() == DeclSpec::TST_decltype)) {
1749 if (DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(), true)) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001750 // FIXME: Preserve type source info.
1751 QualType T = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor4a959d82009-08-06 16:20:37 +00001752 EnterDeclaratorContext(S, DC);
1753 T = RebuildTypeInCurrentInstantiation(T, D.getIdentifierLoc(), Name);
1754 ExitDeclaratorContext(S);
1755 if (T.isNull())
1756 return DeclPtrTy();
1757 DS.UpdateTypeRep(T.getAsOpaquePtr());
1758 }
1759 }
Mike Stump1eb44332009-09-09 15:08:12 +00001760
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001761 DeclContext *DC;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001762 NamedDecl *PrevDecl;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001763 NamedDecl *New;
Douglas Gregorcda9c672009-02-16 17:45:42 +00001764
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001765 DeclaratorInfo *DInfo = 0;
1766 QualType R = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001767
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001768 // See if this is a redefinition of a variable in the same scope.
Douglas Gregor9fa14a52009-03-06 19:06:37 +00001769 if (D.getCXXScopeSpec().isInvalid()) {
1770 DC = CurContext;
1771 PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +00001772 D.setInvalidType();
Douglas Gregor9fa14a52009-03-06 19:06:37 +00001773 } else if (!D.getCXXScopeSpec().isSet()) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001774 LookupNameKind NameKind = LookupOrdinaryName;
1775
1776 // If the declaration we're planning to build will be a function
1777 // or object with linkage, then look for another declaration with
1778 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
1779 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1780 /* Do nothing*/;
1781 else if (R->isFunctionType()) {
Douglas Gregor6bec78d2009-07-07 17:00:05 +00001782 if (CurContext->isFunctionOrMethod() ||
1783 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001784 NameKind = LookupRedeclarationWithLinkage;
1785 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
1786 NameKind = LookupRedeclarationWithLinkage;
Douglas Gregor6bec78d2009-07-07 17:00:05 +00001787 else if (CurContext->getLookupContext()->isTranslationUnit() &&
1788 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1789 NameKind = LookupRedeclarationWithLinkage;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001790
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001791 DC = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +00001792 LookupResult R(*this, Name, D.getIdentifierLoc(), NameKind,
1793 LookupResult::ForRedeclaration);
1794
1795 LookupName(R, S, NameKind == LookupRedeclarationWithLinkage);
John McCallf36e02d2009-10-09 21:13:30 +00001796 PrevDecl = R.getAsSingleDecl(Context);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001797 } else { // Something like "int foo::x;"
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001798 DC = computeDeclContext(D.getCXXScopeSpec(), true);
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Douglas Gregordacd4342009-08-26 00:04:55 +00001800 if (!DC) {
1801 // If we could not compute the declaration context, it's because the
1802 // declaration context is dependent but does not refer to a class,
1803 // class template, or class template partial specialization. Complain
1804 // and return early, to avoid the coming semantic disaster.
Mike Stump1eb44332009-09-09 15:08:12 +00001805 Diag(D.getIdentifierLoc(),
Douglas Gregordacd4342009-08-26 00:04:55 +00001806 diag::err_template_qualified_declarator_no_match)
1807 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
1808 << D.getCXXScopeSpec().getRange();
1809 return DeclPtrTy();
1810 }
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Douglas Gregorfd056bc2009-10-13 16:30:37 +00001812 if (!DC->isDependentContext() &&
1813 RequireCompleteDeclContext(D.getCXXScopeSpec()))
1814 return DeclPtrTy();
1815
John McCalla24dc2e2009-11-17 02:14:36 +00001816 LookupResult Res(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
1817 LookupResult::ForRedeclaration);
1818 LookupQualifiedName(Res, DC);
John McCallf36e02d2009-10-09 21:13:30 +00001819 PrevDecl = Res.getAsSingleDecl(Context);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001820
1821 // C++ 7.3.1.2p2:
1822 // Members (including explicit specializations of templates) of a named
1823 // namespace can also be defined outside that namespace by explicit
1824 // qualification of the name being defined, provided that the entity being
1825 // defined was already declared in the namespace and the definition appears
1826 // after the point of declaration in a namespace that encloses the
1827 // declarations namespace.
1828 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001829 // Note that we only check the context at this point. We don't yet
1830 // have enough information to make sure that PrevDecl is actually
1831 // the declaration we want to match. For example, given:
1832 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001833 // class X {
1834 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001835 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001836 // };
1837 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001838 // void X::f(int) { } // ill-formed
1839 //
1840 // In this case, PrevDecl will point to the overload set
1841 // containing the two f's declared in X, but neither of them
Mike Stump1eb44332009-09-09 15:08:12 +00001842 // matches.
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001843
1844 // First check whether we named the global scope.
1845 if (isa<TranslationUnitDecl>(DC)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001846 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001847 << Name << D.getCXXScopeSpec().getRange();
Sebastian Redl9770ef02009-11-08 11:36:54 +00001848 } else {
1849 DeclContext *Cur = CurContext;
1850 while (isa<LinkageSpecDecl>(Cur))
1851 Cur = Cur->getParent();
1852 if (!Cur->Encloses(DC)) {
1853 // The qualifying scope doesn't enclose the original declaration.
1854 // Emit diagnostic based on current scope.
1855 SourceLocation L = D.getIdentifierLoc();
1856 SourceRange R = D.getCXXScopeSpec().getRange();
1857 if (isa<FunctionDecl>(Cur))
1858 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
1859 else
1860 Diag(L, diag::err_invalid_declarator_scope)
1861 << Name << cast<NamedDecl>(DC) << R;
1862 D.setInvalidType();
1863 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001864 }
1865 }
1866
Douglas Gregorf57172b2008-12-08 18:40:42 +00001867 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001868 // Maybe we will complain about the shadowed template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00001869 if (!D.isInvalidType())
Chris Lattnereaaebc72009-04-25 08:06:05 +00001870 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl))
1871 D.setInvalidType();
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Douglas Gregor72c3f312008-12-05 18:15:24 +00001873 // Just pretend that we didn't see the previous declaration.
1874 PrevDecl = 0;
1875 }
1876
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001877 // In C++, the previous declaration we find might be a tag type
1878 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00001879 // tag type. Note that this does does not apply if we're declaring a
1880 // typedef (C++ [dcl.typedef]p4).
1881 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1882 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001883 PrevDecl = 0;
1884
Douglas Gregorcda9c672009-02-16 17:45:42 +00001885 bool Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001886 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregore542c862009-06-23 23:11:28 +00001887 if (TemplateParamLists.size()) {
1888 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
1889 return DeclPtrTy();
1890 }
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001892 New = ActOnTypedefDeclarator(S, D, DC, R, DInfo, PrevDecl, Redeclaration);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001893 } else if (R->isFunctionType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001894 New = ActOnFunctionDeclarator(S, D, DC, R, DInfo, PrevDecl,
Douglas Gregore542c862009-06-23 23:11:28 +00001895 move(TemplateParamLists),
Chris Lattnereaaebc72009-04-25 08:06:05 +00001896 IsFunctionDefinition, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +00001897 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001898 New = ActOnVariableDeclarator(S, D, DC, R, DInfo, PrevDecl,
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00001899 move(TemplateParamLists),
1900 Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +00001901 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001902
1903 if (New == 0)
Chris Lattnerb28317a2009-03-28 19:18:32 +00001904 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00001906 // If this has an identifier and is not an invalid redeclaration or
1907 // function template specialization, add it to the scope stack.
1908 if (Name && !(Redeclaration && New->isInvalidDecl()) &&
1909 !(isa<FunctionDecl>(New) &&
1910 cast<FunctionDecl>(New)->isFunctionTemplateSpecialization()))
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001911 PushOnScopeChains(New, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001912
Chris Lattnerb28317a2009-03-28 19:18:32 +00001913 return DeclPtrTy::make(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00001914}
1915
Eli Friedman1ca48132009-02-21 00:44:51 +00001916/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
1917/// types into constant array types in certain situations which would otherwise
1918/// be errors (for GCC compatibility).
1919static QualType TryToFixInvalidVariablyModifiedType(QualType T,
1920 ASTContext &Context,
1921 bool &SizeIsNegative) {
1922 // This method tries to turn a variable array into a constant
1923 // array even when the size isn't an ICE. This is necessary
1924 // for compatibility with code that depends on gcc's buggy
1925 // constant expression folding, like struct {char x[(int)(char*)2];}
1926 SizeIsNegative = false;
1927
John McCall0953e762009-09-24 19:53:00 +00001928 QualifierCollector Qs;
1929 const Type *Ty = Qs.strip(T);
1930
1931 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedman1ca48132009-02-21 00:44:51 +00001932 QualType Pointee = PTy->getPointeeType();
1933 QualType FixedType =
1934 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
1935 if (FixedType.isNull()) return FixedType;
Eli Friedman61125c82009-02-21 00:58:02 +00001936 FixedType = Context.getPointerType(FixedType);
John McCall0953e762009-09-24 19:53:00 +00001937 return Qs.apply(FixedType);
Eli Friedman1ca48132009-02-21 00:44:51 +00001938 }
1939
1940 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanbc592e62009-02-26 03:58:54 +00001941 if (!VLATy)
1942 return QualType();
1943 // FIXME: We should probably handle this case
1944 if (VLATy->getElementType()->isVariablyModifiedType())
1945 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Eli Friedman1ca48132009-02-21 00:44:51 +00001947 Expr::EvalResult EvalResult;
1948 if (!VLATy->getSizeExpr() ||
Eli Friedmanbc592e62009-02-26 03:58:54 +00001949 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
1950 !EvalResult.Val.isInt())
Eli Friedman1ca48132009-02-21 00:44:51 +00001951 return QualType();
Eli Friedmanbc592e62009-02-26 03:58:54 +00001952
Eli Friedman1ca48132009-02-21 00:44:51 +00001953 llvm::APSInt &Res = EvalResult.Val.getInt();
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001954 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
John McCall46a617a2009-10-16 00:14:28 +00001955 // TODO: preserve the size expression in declarator info
1956 return Context.getConstantArrayType(VLATy->getElementType(),
1957 Res, ArrayType::Normal, 0);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001958 }
Eli Friedman1ca48132009-02-21 00:44:51 +00001959
1960 SizeIsNegative = true;
1961 return QualType();
1962}
1963
Douglas Gregor63935192009-03-02 00:19:53 +00001964/// \brief Register the given locally-scoped external C declaration so
1965/// that it can be found later for redeclarations
Mike Stump1eb44332009-09-09 15:08:12 +00001966void
Douglas Gregor63935192009-03-02 00:19:53 +00001967Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, NamedDecl *PrevDecl,
1968 Scope *S) {
1969 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
1970 "Decl is not a locally-scoped decl!");
1971 // Note that we have a locally-scoped external with this name.
1972 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
1973
1974 if (!PrevDecl)
1975 return;
1976
1977 // If there was a previous declaration of this variable, it may be
1978 // in our identifier chain. Update the identifier chain with the new
1979 // declaration.
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001980 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
Douglas Gregor63935192009-03-02 00:19:53 +00001981 // The previous declaration was found on the identifer resolver
1982 // chain, so remove it from its scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001983 while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
Douglas Gregor63935192009-03-02 00:19:53 +00001984 S = S->getParent();
1985
1986 if (S)
Chris Lattnerb28317a2009-03-28 19:18:32 +00001987 S->RemoveDecl(DeclPtrTy::make(PrevDecl));
Douglas Gregor63935192009-03-02 00:19:53 +00001988 }
1989}
1990
Eli Friedman85a53192009-04-07 19:37:57 +00001991/// \brief Diagnose function specifiers on a declaration of an identifier that
1992/// does not identify a function.
1993void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
1994 // FIXME: We should probably indicate the identifier in question to avoid
1995 // confusion for constructs like "inline int a(), b;"
1996 if (D.getDeclSpec().isInlineSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00001997 Diag(D.getDeclSpec().getInlineSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00001998 diag::err_inline_non_function);
1999
2000 if (D.getDeclSpec().isVirtualSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00002001 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00002002 diag::err_virtual_non_function);
2003
2004 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00002005 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00002006 diag::err_explicit_non_function);
2007}
2008
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002009NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002010Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002011 QualType R, DeclaratorInfo *DInfo,
Douglas Gregor2531c2d2009-09-28 00:47:05 +00002012 NamedDecl* PrevDecl, bool &Redeclaration) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002013 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2014 if (D.getCXXScopeSpec().isSet()) {
2015 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2016 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00002017 D.setInvalidType();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002018 // Pretend we didn't see the scope specifier.
2019 DC = 0;
2020 }
2021
Douglas Gregor021c3b32009-03-11 23:00:04 +00002022 if (getLangOptions().CPlusPlus) {
2023 // Check that there are no default arguments (C++ only).
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002024 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +00002025 }
2026
Eli Friedman85a53192009-04-07 19:37:57 +00002027 DiagnoseFunctionSpecifiers(D);
2028
Eli Friedman63054b32009-04-19 20:27:55 +00002029 if (D.getDeclSpec().isThreadSpecified())
2030 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2031
John McCallba6a9bd2009-10-24 08:00:42 +00002032 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, DInfo);
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002033 if (!NewTD) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002035 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002036 ProcessDeclAttributes(S, NewTD, D);
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002037 // Merge the decl with the existing one if appropriate. If the decl is
2038 // in an outer scope, it isn't the same thing.
2039 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00002040 Redeclaration = true;
Chris Lattnereaaebc72009-04-25 08:06:05 +00002041 MergeTypeDefDecl(NewTD, PrevDecl);
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002042 }
2043
Chris Lattner38c5ebd2009-04-19 05:21:20 +00002044 // C99 6.7.7p2: If a typedef name specifies a variably modified type
2045 // then it shall have block scope.
2046 QualType T = NewTD->getUnderlyingType();
2047 if (T->isVariablyModifiedType()) {
2048 CurFunctionNeedsScopeChecking = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Chris Lattner38c5ebd2009-04-19 05:21:20 +00002050 if (S->getFnParent() == 0) {
Eli Friedman1ca48132009-02-21 00:44:51 +00002051 bool SizeIsNegative;
2052 QualType FixedTy =
2053 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2054 if (!FixedTy.isNull()) {
2055 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
John McCallba6a9bd2009-10-24 08:00:42 +00002056 NewTD->setTypeDeclaratorInfo(Context.getTrivialDeclaratorInfo(FixedTy));
Eli Friedman1ca48132009-02-21 00:44:51 +00002057 } else {
2058 if (SizeIsNegative)
2059 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2060 else if (T->isVariableArrayType())
2061 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
2062 else
2063 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002064 NewTD->setInvalidDecl();
Eli Friedman1ca48132009-02-21 00:44:51 +00002065 }
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002066 }
2067 }
Douglas Gregorc29f77b2009-07-07 16:35:42 +00002068
2069 // If this is the C FILE type, notify the AST context.
2070 if (IdentifierInfo *II = NewTD->getIdentifier())
2071 if (!NewTD->isInvalidDecl() &&
Mike Stump782fa302009-07-28 02:25:19 +00002072 NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
2073 if (II->isStr("FILE"))
2074 Context.setFILEDecl(NewTD);
2075 else if (II->isStr("jmp_buf"))
2076 Context.setjmp_bufDecl(NewTD);
2077 else if (II->isStr("sigjmp_buf"))
2078 Context.setsigjmp_bufDecl(NewTD);
2079 }
2080
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002081 return NewTD;
2082}
2083
Douglas Gregor8f301052009-02-24 19:23:27 +00002084/// \brief Determines whether the given declaration is an out-of-scope
2085/// previous declaration.
2086///
2087/// This routine should be invoked when name lookup has found a
2088/// previous declaration (PrevDecl) that is not in the scope where a
2089/// new declaration by the same name is being introduced. If the new
2090/// declaration occurs in a local scope, previous declarations with
2091/// linkage may still be considered previous declarations (C99
2092/// 6.2.2p4-5, C++ [basic.link]p6).
2093///
2094/// \param PrevDecl the previous declaration found by name
2095/// lookup
Mike Stump1eb44332009-09-09 15:08:12 +00002096///
Douglas Gregor8f301052009-02-24 19:23:27 +00002097/// \param DC the context in which the new declaration is being
2098/// declared.
2099///
2100/// \returns true if PrevDecl is an out-of-scope previous declaration
2101/// for a new delcaration with the same name.
Mike Stump1eb44332009-09-09 15:08:12 +00002102static bool
Douglas Gregor8f301052009-02-24 19:23:27 +00002103isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2104 ASTContext &Context) {
2105 if (!PrevDecl)
2106 return 0;
2107
2108 // FIXME: PrevDecl could be an OverloadedFunctionDecl, in which
2109 // case we need to check each of the overloaded functions.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002110 if (!PrevDecl->hasLinkage())
2111 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00002112
2113 if (Context.getLangOptions().CPlusPlus) {
2114 // C++ [basic.link]p6:
2115 // If there is a visible declaration of an entity with linkage
2116 // having the same name and type, ignoring entities declared
2117 // outside the innermost enclosing namespace scope, the block
2118 // scope declaration declares that same entity and receives the
2119 // linkage of the previous declaration.
2120 DeclContext *OuterContext = DC->getLookupContext();
2121 if (!OuterContext->isFunctionOrMethod())
2122 // This rule only applies to block-scope declarations.
2123 return false;
2124 else {
2125 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2126 if (PrevOuterContext->isRecord())
2127 // We found a member function: ignore it.
2128 return false;
2129 else {
2130 // Find the innermost enclosing namespace for the new and
2131 // previous declarations.
2132 while (!OuterContext->isFileContext())
2133 OuterContext = OuterContext->getParent();
2134 while (!PrevOuterContext->isFileContext())
2135 PrevOuterContext = PrevOuterContext->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Douglas Gregor8f301052009-02-24 19:23:27 +00002137 // The previous declaration is in a different namespace, so it
2138 // isn't the same function.
Mike Stump1eb44332009-09-09 15:08:12 +00002139 if (OuterContext->getPrimaryContext() !=
Douglas Gregor8f301052009-02-24 19:23:27 +00002140 PrevOuterContext->getPrimaryContext())
2141 return false;
2142 }
2143 }
2144 }
2145
Douglas Gregor8f301052009-02-24 19:23:27 +00002146 return true;
2147}
2148
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002149NamedDecl*
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002150Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002151 QualType R, DeclaratorInfo *DInfo,
2152 NamedDecl* PrevDecl,
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002153 MultiTemplateParamsArg TemplateParamLists,
Douglas Gregorcda9c672009-02-16 17:45:42 +00002154 bool &Redeclaration) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002155 DeclarationName Name = GetNameForDeclarator(D);
2156
2157 // Check that there are no default arguments (C++ only).
2158 if (getLangOptions().CPlusPlus)
2159 CheckExtraCXXDefaultArguments(D);
2160
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002161 VarDecl *NewVD;
2162 VarDecl::StorageClass SC;
2163 switch (D.getDeclSpec().getStorageClassSpec()) {
2164 default: assert(0 && "Unknown storage class!");
2165 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
2166 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
2167 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
2168 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
2169 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
2170 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
2171 case DeclSpec::SCS_mutable:
2172 // mutable can only appear on non-static class members, so it's always
2173 // an error here
2174 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002175 D.setInvalidType();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002176 SC = VarDecl::None;
2177 break;
2178 }
2179
2180 IdentifierInfo *II = Name.getAsIdentifierInfo();
2181 if (!II) {
2182 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2183 << Name.getAsString();
2184 return 0;
2185 }
2186
Eli Friedman85a53192009-04-07 19:37:57 +00002187 DiagnoseFunctionSpecifiers(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +00002188
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00002189 if (!DC->isRecord() && S->getFnParent() == 0) {
2190 // C99 6.9p2: The storage-class specifiers auto and register shall not
2191 // appear in the declaration specifiers in an external declaration.
2192 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Chris Lattnerd4b19d52009-05-12 21:44:00 +00002194 // If this is a register variable with an asm label specified, then this
2195 // is a GNU extension.
2196 if (SC == VarDecl::Register && D.getAsmLabel())
2197 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2198 else
2199 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002200 D.setInvalidType();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002201 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002202 }
Douglas Gregor656de632009-03-11 23:52:16 +00002203 if (DC->isRecord() && !CurContext->isRecord()) {
2204 // This is an out-of-line definition of a static data member.
2205 if (SC == VarDecl::Static) {
Mike Stump1eb44332009-09-09 15:08:12 +00002206 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor656de632009-03-11 23:52:16 +00002207 diag::err_static_out_of_line)
2208 << CodeModificationHint::CreateRemoval(
2209 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
2210 } else if (SC == VarDecl::None)
2211 SC = VarDecl::Static;
2212 }
Anders Carlssone98da2e2009-06-24 00:28:53 +00002213 if (SC == VarDecl::Static) {
2214 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2215 if (RD->isLocalClass())
Mike Stump1eb44332009-09-09 15:08:12 +00002216 Diag(D.getIdentifierLoc(),
Anders Carlssone98da2e2009-06-24 00:28:53 +00002217 diag::err_static_data_member_not_allowed_in_local_class)
2218 << Name << RD->getDeclName();
2219 }
2220 }
Mike Stump1eb44332009-09-09 15:08:12 +00002221
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002222 // Match up the template parameter lists with the scope specifier, then
2223 // determine whether we have a template or a template specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002224 bool isExplicitSpecialization = false;
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002225 if (TemplateParameterList *TemplateParams
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002226 = MatchTemplateParametersToScopeSpecifier(
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002227 D.getDeclSpec().getSourceRange().getBegin(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002228 D.getCXXScopeSpec(),
Douglas Gregor27eeb5e2009-07-22 22:05:02 +00002229 (TemplateParameterList**)TemplateParamLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002230 TemplateParamLists.size(),
2231 isExplicitSpecialization)) {
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002232 if (TemplateParams->size() > 0) {
2233 // There is no such thing as a variable template.
2234 Diag(D.getIdentifierLoc(), diag::err_template_variable)
2235 << II
2236 << SourceRange(TemplateParams->getTemplateLoc(),
2237 TemplateParams->getRAngleLoc());
2238 return 0;
2239 } else {
2240 // There is an extraneous 'template<>' for this variable. Complain
2241 // about it, but allow the declaration of the variable.
Mike Stump1eb44332009-09-09 15:08:12 +00002242 Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor7cdbc582009-07-22 23:48:44 +00002243 diag::err_template_variable_noparams)
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002244 << II
2245 << SourceRange(TemplateParams->getTemplateLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +00002246 TemplateParams->getRAngleLoc());
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002247
2248 isExplicitSpecialization = true;
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002249 }
Mike Stump1eb44332009-09-09 15:08:12 +00002250 }
2251
2252 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00002253 II, R, DInfo, SC);
Eli Friedman63054b32009-04-19 20:27:55 +00002254
Chris Lattnereaaebc72009-04-25 08:06:05 +00002255 if (D.isInvalidType())
2256 NewVD->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002257
Eli Friedman63054b32009-04-19 20:27:55 +00002258 if (D.getDeclSpec().isThreadSpecified()) {
2259 if (NewVD->hasLocalStorage())
2260 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
Eli Friedman4fb71b02009-04-19 21:48:33 +00002261 else if (!Context.Target.isTLSSupported())
2262 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
Eli Friedman63054b32009-04-19 20:27:55 +00002263 else
2264 NewVD->setThreadSpecified(true);
2265 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002266
Douglas Gregor656de632009-03-11 23:52:16 +00002267 // Set the lexical context. If the declarator has a C++ scope specifier, the
2268 // lexical context will be different from the semantic context.
2269 NewVD->setLexicalDeclContext(CurContext);
2270
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002271 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002272 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002273
2274 // Handle GNU asm-label extension (encoded as an attribute).
2275 if (Expr *E = (Expr*) D.getAsmLabel()) {
2276 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00002277 StringLiteral *SE = cast<StringLiteral>(E);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002278 NewVD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
Chris Lattner0b2b6e12009-03-04 06:34:08 +00002279 SE->getByteLength())));
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002280 }
2281
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002282 // If name lookup finds a previous declaration that is not in the
2283 // same scope as the new declaration, this may still be an
2284 // acceptable redeclaration.
2285 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
2286 !(NewVD->hasLinkage() &&
2287 isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
Mike Stump1eb44332009-09-09 15:08:12 +00002288 PrevDecl = 0;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002289
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002290 // Merge the decl with the existing one if appropriate.
2291 if (PrevDecl) {
2292 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
2293 // The user tried to define a non-static data member
2294 // out-of-line (C++ [dcl.meaning]p1).
2295 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
2296 << D.getCXXScopeSpec().getRange();
2297 PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +00002298 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002299 }
2300 } else if (D.getCXXScopeSpec().isSet()) {
2301 // No previous declaration in the qualifying scope.
Douglas Gregor3f093272009-10-13 21:16:44 +00002302 Diag(D.getIdentifierLoc(), diag::err_no_member)
2303 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
2304 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00002305 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002306 }
2307
Chris Lattnereaaebc72009-04-25 08:06:05 +00002308 CheckVariableDeclaration(NewVD, PrevDecl, Redeclaration);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002309
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002310 // This is an explicit specialization of a static data member. Check it.
2311 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
2312 CheckMemberSpecialization(NewVD, PrevDecl))
2313 NewVD->setInvalidDecl();
2314
Ryan Flynn478fbc62009-07-25 22:29:44 +00002315 // attributes declared post-definition are currently ignored
2316 if (PrevDecl) {
2317 const VarDecl *Def = 0, *PrevVD = dyn_cast<VarDecl>(PrevDecl);
2318 if (PrevVD->getDefinition(Def) && D.hasAttributes()) {
2319 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
2320 Diag(Def->getLocation(), diag::note_previous_definition);
2321 }
2322 }
2323
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002324 // If this is a locally-scoped extern C variable, update the map of
2325 // such variables.
Douglas Gregor48a83b52009-09-12 00:17:51 +00002326 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
Chris Lattnereaaebc72009-04-25 08:06:05 +00002327 !NewVD->isInvalidDecl())
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002328 RegisterLocallyScopedExternCDecl(NewVD, PrevDecl, S);
2329
2330 return NewVD;
2331}
2332
2333/// \brief Perform semantic checking on a newly-created variable
2334/// declaration.
2335///
2336/// This routine performs all of the type-checking required for a
Douglas Gregor180bb632009-05-01 15:47:09 +00002337/// variable declaration once it has been built. It is used both to
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002338/// check variables after they have been parsed and their declarators
Douglas Gregor180bb632009-05-01 15:47:09 +00002339/// have been translated into a declaration, and to check variables
2340/// that have been instantiated from a template.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002341///
Chris Lattnereaaebc72009-04-25 08:06:05 +00002342/// Sets NewVD->isInvalidDecl() if an error was encountered.
2343void Sema::CheckVariableDeclaration(VarDecl *NewVD, NamedDecl *PrevDecl,
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002344 bool &Redeclaration) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00002345 // If the decl is already known invalid, don't check it.
2346 if (NewVD->isInvalidDecl())
2347 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002348
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002349 QualType T = NewVD->getType();
2350
2351 if (T->isObjCInterfaceType()) {
2352 Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002353 return NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002354 }
Mike Stump1eb44332009-09-09 15:08:12 +00002355
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002356 // The variable can not have an abstract class type.
2357 if (RequireNonAbstractType(NewVD->getLocation(), T,
Mike Stump1eb44332009-09-09 15:08:12 +00002358 diag::err_abstract_type_in_decl,
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002359 AbstractVariableType))
Chris Lattnereaaebc72009-04-25 08:06:05 +00002360 return NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002361
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002362 // Emit an error if an address space was applied to decl with local storage.
2363 // This includes arrays of objects with address space qualifiers, but not
2364 // automatic variables that point to other address spaces.
2365 // ISO/IEC TR 18037 S5.1.2
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002366 if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
2367 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002368 return NewVD->setInvalidDecl();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002369 }
Fariborz Jahanian7b5b3172009-02-21 19:44:02 +00002370
Mike Stumpf33651c2009-04-14 00:57:29 +00002371 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002372 && !NewVD->hasAttr<BlocksAttr>())
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002373 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Fariborz Jahanian7b5b3172009-02-21 19:44:02 +00002374
Chris Lattner38c5ebd2009-04-19 05:21:20 +00002375 bool isVM = T->isVariablyModifiedType();
Chris Lattnerbe6d2592009-07-19 20:17:11 +00002376 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
2377 NewVD->hasAttr<BlocksAttr>())
Chris Lattner38c5ebd2009-04-19 05:21:20 +00002378 CurFunctionNeedsScopeChecking = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002379
Chris Lattner38c5ebd2009-04-19 05:21:20 +00002380 if ((isVM && NewVD->hasLinkage()) ||
2381 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002382 bool SizeIsNegative;
2383 QualType FixedTy =
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002384 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
Mike Stump1eb44332009-09-09 15:08:12 +00002385
Chris Lattnereaaebc72009-04-25 08:06:05 +00002386 if (FixedTy.isNull() && T->isVariableArrayType()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002387 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002388 // FIXME: This won't give the correct result for
2389 // int a[10][n];
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002390 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002391
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002392 if (NewVD->isFileVarDecl())
2393 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnereaaebc72009-04-25 08:06:05 +00002394 << SizeRange;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002395 else if (NewVD->getStorageClass() == VarDecl::Static)
2396 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00002397 << SizeRange;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002398 else
2399 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00002400 << SizeRange;
2401 return NewVD->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002402 }
2403
Chris Lattnereaaebc72009-04-25 08:06:05 +00002404 if (FixedTy.isNull()) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002405 if (NewVD->isFileVarDecl())
2406 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
2407 else
2408 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002409 return NewVD->setInvalidDecl();
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002410 }
Mike Stump1eb44332009-09-09 15:08:12 +00002411
Chris Lattnereaaebc72009-04-25 08:06:05 +00002412 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
2413 NewVD->setType(FixedTy);
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002414 }
2415
Douglas Gregor48a83b52009-09-12 00:17:51 +00002416 if (!PrevDecl && NewVD->isExternC()) {
Douglas Gregor63935192009-03-02 00:19:53 +00002417 // Since we did not find anything by this name and we're declaring
2418 // an extern "C" variable, look for a non-visible extern "C"
2419 // declaration with the same name.
2420 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002421 = LocallyScopedExternalDecls.find(NewVD->getDeclName());
Douglas Gregor63935192009-03-02 00:19:53 +00002422 if (Pos != LocallyScopedExternalDecls.end())
2423 PrevDecl = Pos->second;
2424 }
2425
Chris Lattnereaaebc72009-04-25 08:06:05 +00002426 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002427 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
2428 << T;
Chris Lattnereaaebc72009-04-25 08:06:05 +00002429 return NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002430 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002431
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002432 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00002433 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
2434 return NewVD->setInvalidDecl();
2435 }
Mike Stump1eb44332009-09-09 15:08:12 +00002436
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002437 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpc975bb02009-05-01 23:41:47 +00002438 Diag(NewVD->getLocation(), diag::err_block_on_vm);
2439 return NewVD->setInvalidDecl();
2440 }
2441
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002442 if (PrevDecl) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00002443 Redeclaration = true;
Chris Lattnereaaebc72009-04-25 08:06:05 +00002444 MergeVarDecl(NewVD, PrevDecl);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002445 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002446}
2447
Anders Carlsson203cb712009-08-29 00:56:38 +00002448static bool isUsingDecl(Decl *D) {
2449 return isa<UsingDecl>(D) || isa<UnresolvedUsingDecl>(D);
2450}
2451
Douglas Gregora8f32e02009-10-06 17:59:45 +00002452/// \brief Data used with FindOverriddenMethod
2453struct FindOverriddenMethodData {
2454 Sema *S;
2455 CXXMethodDecl *Method;
2456};
2457
2458/// \brief Member lookup function that determines whether a given C++
2459/// method overrides a method in a base class, to be used with
2460/// CXXRecordDecl::lookupInBases().
John McCallaf8e6ed2009-11-12 03:15:40 +00002461static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002462 CXXBasePath &Path,
2463 void *UserData) {
2464 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2465
2466 FindOverriddenMethodData *Data
2467 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
2468 for (Path.Decls = BaseRecord->lookup(Data->Method->getDeclName());
2469 Path.Decls.first != Path.Decls.second;
2470 ++Path.Decls.first) {
2471 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*Path.Decls.first)) {
2472 OverloadedFunctionDecl::function_iterator MatchedDecl;
2473 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, MatchedDecl))
2474 return true;
2475 }
2476 }
2477
2478 return false;
2479}
2480
Mike Stump1eb44332009-09-09 15:08:12 +00002481NamedDecl*
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002482Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002483 QualType R, DeclaratorInfo *DInfo,
2484 NamedDecl* PrevDecl,
Douglas Gregore542c862009-06-23 23:11:28 +00002485 MultiTemplateParamsArg TemplateParamLists,
Chris Lattnereaaebc72009-04-25 08:06:05 +00002486 bool IsFunctionDefinition, bool &Redeclaration) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002487 assert(R.getTypePtr()->isFunctionType());
2488
2489 DeclarationName Name = GetNameForDeclarator(D);
2490 FunctionDecl::StorageClass SC = FunctionDecl::None;
2491 switch (D.getDeclSpec().getStorageClassSpec()) {
2492 default: assert(0 && "Unknown storage class!");
2493 case DeclSpec::SCS_auto:
2494 case DeclSpec::SCS_register:
2495 case DeclSpec::SCS_mutable:
Mike Stump1eb44332009-09-09 15:08:12 +00002496 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor04495c82009-02-24 01:23:02 +00002497 diag::err_typecheck_sclass_func);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002498 D.setInvalidType();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002499 break;
2500 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
2501 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
Douglas Gregor04495c82009-02-24 01:23:02 +00002502 case DeclSpec::SCS_static: {
Douglas Gregor656de632009-03-11 23:52:16 +00002503 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor04495c82009-02-24 01:23:02 +00002504 // C99 6.7.1p5:
2505 // The declaration of an identifier for a function that has
2506 // block scope shall have no explicit storage-class specifier
2507 // other than extern
2508 // See also (C++ [dcl.stc]p4).
Mike Stump1eb44332009-09-09 15:08:12 +00002509 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor04495c82009-02-24 01:23:02 +00002510 diag::err_static_block_func);
2511 SC = FunctionDecl::None;
2512 } else
Mike Stump1eb44332009-09-09 15:08:12 +00002513 SC = FunctionDecl::Static;
Douglas Gregor04495c82009-02-24 01:23:02 +00002514 break;
2515 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002516 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
2517 }
2518
Eli Friedman63054b32009-04-19 20:27:55 +00002519 if (D.getDeclSpec().isThreadSpecified())
2520 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2521
John McCall3f9a8a62009-08-11 06:59:38 +00002522 bool isFriend = D.getDeclSpec().isFriendSpecified();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002523 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor021c3b32009-03-11 23:00:04 +00002524 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002525 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
2526
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002527 // Check that the return type is not an abstract class type.
Anders Carlsson8211eff2009-03-24 01:19:16 +00002528 // For record types, this is done by the AbstractClassUsageDiagnoser once
Mike Stump1eb44332009-09-09 15:08:12 +00002529 // the class has been completely parsed.
Anders Carlsson8211eff2009-03-24 01:19:16 +00002530 if (!DC->isRecord() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002531 RequireNonAbstractType(D.getIdentifierLoc(),
John McCall183700f2009-09-21 23:43:11 +00002532 R->getAs<FunctionType>()->getResultType(),
Mike Stump1eb44332009-09-09 15:08:12 +00002533 diag::err_abstract_type_in_decl,
Anders Carlsson8211eff2009-03-24 01:19:16 +00002534 AbstractReturnType))
Chris Lattnereaaebc72009-04-25 08:06:05 +00002535 D.setInvalidType();
Mike Stump1eb44332009-09-09 15:08:12 +00002536
Chris Lattnerbb749822009-04-11 19:17:25 +00002537 // Do not allow returning a objc interface by-value.
John McCall183700f2009-09-21 23:43:11 +00002538 if (R->getAs<FunctionType>()->getResultType()->isObjCInterfaceType()) {
Chris Lattnerbb749822009-04-11 19:17:25 +00002539 Diag(D.getIdentifierLoc(),
2540 diag::err_object_cannot_be_passed_returned_by_value) << 0
John McCall183700f2009-09-21 23:43:11 +00002541 << R->getAs<FunctionType>()->getResultType();
Chris Lattnereaaebc72009-04-25 08:06:05 +00002542 D.setInvalidType();
Chris Lattnerbb749822009-04-11 19:17:25 +00002543 }
Douglas Gregore542c862009-06-23 23:11:28 +00002544
Douglas Gregor021c3b32009-03-11 23:00:04 +00002545 bool isVirtualOkay = false;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002546 FunctionDecl *NewFD;
John McCall02cace72009-08-28 07:59:38 +00002547
John McCall3f9a8a62009-08-11 06:59:38 +00002548 if (isFriend) {
2549 // DC is the namespace in which the function is being declared.
John McCall91cf4192009-08-25 17:53:59 +00002550 assert((DC->isFileContext() || PrevDecl) && "previously-undeclared "
2551 "friend function being created in a non-namespace context");
John McCall3f9a8a62009-08-11 06:59:38 +00002552
2553 // C++ [class.friend]p5
2554 // A function can be defined in a friend declaration of a
2555 // class . . . . Such a function is implicitly inline.
2556 isInline |= IsFunctionDefinition;
John McCall02cace72009-08-28 07:59:38 +00002557 }
John McCall3f9a8a62009-08-11 06:59:38 +00002558
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002559 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002560 // This is a C++ constructor declaration.
2561 assert(DC->isRecord() &&
2562 "Constructors can only be declared in a member context");
2563
Chris Lattner65401802009-04-25 08:28:21 +00002564 R = CheckConstructorDeclarator(D, R, SC);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002565
2566 // Create the new declaration
Mike Stump1eb44332009-09-09 15:08:12 +00002567 NewFD = CXXConstructorDecl::Create(Context,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002568 cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002569 D.getIdentifierLoc(), Name, R, DInfo,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002570 isExplicit, isInline,
2571 /*isImplicitlyDeclared=*/false);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002572 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002573 // This is a C++ destructor declaration.
2574 if (DC->isRecord()) {
Chris Lattner65401802009-04-25 08:28:21 +00002575 R = CheckDestructorDeclarator(D, SC);
Mike Stump1eb44332009-09-09 15:08:12 +00002576
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002577 NewFD = CXXDestructorDecl::Create(Context,
2578 cast<CXXRecordDecl>(DC),
Mike Stump1eb44332009-09-09 15:08:12 +00002579 D.getIdentifierLoc(), Name, R,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002580 isInline,
2581 /*isImplicitlyDeclared=*/false);
2582
Douglas Gregor021c3b32009-03-11 23:00:04 +00002583 isVirtualOkay = true;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002584 } else {
2585 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
2586
2587 // Create a FunctionDecl to satisfy the function definition parsing
2588 // code path.
2589 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +00002590 Name, R, DInfo, SC, isInline,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00002591 /*hasPrototype=*/true);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002592 D.setInvalidType();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002593 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002594 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002595 if (!DC->isRecord()) {
2596 Diag(D.getIdentifierLoc(),
2597 diag::err_conv_function_not_member);
2598 return 0;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002599 }
Mike Stump1eb44332009-09-09 15:08:12 +00002600
Chris Lattner6e475012009-04-25 08:35:12 +00002601 CheckConversionDeclarator(D, R, SC);
2602 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002603 D.getIdentifierLoc(), Name, R, DInfo,
Chris Lattner6e475012009-04-25 08:35:12 +00002604 isInline, isExplicit);
Mike Stump1eb44332009-09-09 15:08:12 +00002605
Chris Lattner6e475012009-04-25 08:35:12 +00002606 isVirtualOkay = true;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002607 } else if (DC->isRecord()) {
Anders Carlsson4649cac2009-04-30 22:41:11 +00002608 // If the of the function is the same as the name of the record, then this
Mike Stump1eb44332009-09-09 15:08:12 +00002609 // must be an invalid constructor that has a return type.
2610 // (The parser checks for a return type and makes the declarator a
Anders Carlsson4649cac2009-04-30 22:41:11 +00002611 // constructor if it has no return type).
Mike Stump1eb44332009-09-09 15:08:12 +00002612 // must have an invalid constructor that has a return type
Anders Carlsson4649cac2009-04-30 22:41:11 +00002613 if (Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
2614 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
2615 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2616 << SourceRange(D.getIdentifierLoc());
2617 return 0;
2618 }
Mike Stump1eb44332009-09-09 15:08:12 +00002619
Anders Carlsson67bf2e72009-11-15 18:59:32 +00002620 bool isStatic = SC == FunctionDecl::Static;
2621
2622 // [class.free]p1:
2623 // Any allocation function for a class T is a static member
2624 // (even if not explicitly declared static).
2625 if (Name.getCXXOverloadedOperator() == OO_New ||
2626 Name.getCXXOverloadedOperator() == OO_Array_New)
2627 isStatic = true;
Anders Carlsson1f126bd2009-11-15 19:08:46 +00002628
2629 // [class.free]p6 Any deallocation function for a class X is a static member
2630 // (even if not explicitly declared static).
2631 if (Name.getCXXOverloadedOperator() == OO_Delete ||
2632 Name.getCXXOverloadedOperator() == OO_Array_Delete)
2633 isStatic = true;
Anders Carlsson67bf2e72009-11-15 18:59:32 +00002634
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002635 // This is a C++ method declaration.
2636 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002637 D.getIdentifierLoc(), Name, R, DInfo,
Anders Carlsson67bf2e72009-11-15 18:59:32 +00002638 isStatic, isInline);
Douglas Gregor021c3b32009-03-11 23:00:04 +00002639
Anders Carlsson1f126bd2009-11-15 19:08:46 +00002640 isVirtualOkay = !isStatic;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002641 } else {
Douglas Gregord874def2009-03-19 18:33:54 +00002642 // Determine whether the function was written with a
2643 // prototype. This true when:
2644 // - we're in C++ (where every function has a prototype),
2645 // - there is a prototype in the declarator, or
2646 // - the type R of the function is some kind of typedef or other reference
2647 // to a type name (which eventually refers to a function type).
Mike Stump1eb44332009-09-09 15:08:12 +00002648 bool HasPrototype =
Chris Lattner0d48bf92009-03-17 23:17:04 +00002649 getLangOptions().CPlusPlus ||
Douglas Gregor13d7a322009-03-19 18:14:46 +00002650 (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
Douglas Gregord1659a62009-03-23 16:26:51 +00002651 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
Mike Stump1eb44332009-09-09 15:08:12 +00002652
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002653 NewFD = FunctionDecl::Create(Context, DC,
2654 D.getIdentifierLoc(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00002655 Name, R, DInfo, SC, isInline, HasPrototype);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002656 }
2657
Chris Lattnereaaebc72009-04-25 08:06:05 +00002658 if (D.isInvalidType())
Chris Lattner584be452009-04-25 05:44:12 +00002659 NewFD->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002660
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002661 // Set the lexical context. If the declarator has a C++
John McCall02cace72009-08-28 07:59:38 +00002662 // scope specifier, or is the object of a friend declaration, the
2663 // lexical context will be different from the semantic context.
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002664 NewFD->setLexicalDeclContext(CurContext);
2665
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002666 // Match up the template parameter lists with the scope specifier, then
2667 // determine whether we have a template or a template specialization.
Douglas Gregorc5c903a2009-06-24 00:23:40 +00002668 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002669 bool isExplicitSpecialization = false;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002670 bool isFunctionTemplateSpecialization = false;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002671 if (TemplateParameterList *TemplateParams
2672 = MatchTemplateParametersToScopeSpecifier(
2673 D.getDeclSpec().getSourceRange().getBegin(),
2674 D.getCXXScopeSpec(),
Douglas Gregor27eeb5e2009-07-22 22:05:02 +00002675 (TemplateParameterList**)TemplateParamLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002676 TemplateParamLists.size(),
2677 isExplicitSpecialization)) {
Douglas Gregorc5c903a2009-06-24 00:23:40 +00002678 if (TemplateParams->size() > 0) {
2679 // This is a function template
Mike Stump1eb44332009-09-09 15:08:12 +00002680
Douglas Gregor05396e22009-08-25 17:23:04 +00002681 // Check that we can declare a template here.
2682 if (CheckTemplateDeclScope(S, TemplateParams))
2683 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002684
Douglas Gregord60e1052009-08-27 16:57:43 +00002685 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
Douglas Gregorc5c903a2009-06-24 00:23:40 +00002686 NewFD->getLocation(),
2687 Name, TemplateParams,
2688 NewFD);
Douglas Gregord60e1052009-08-27 16:57:43 +00002689 FunctionTemplate->setLexicalDeclContext(CurContext);
Douglas Gregorc5c903a2009-06-24 00:23:40 +00002690 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
2691 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002692 // This is a function template specialization.
2693 isFunctionTemplateSpecialization = true;
Douglas Gregorc5c903a2009-06-24 00:23:40 +00002694 }
Mike Stump1eb44332009-09-09 15:08:12 +00002695
Douglas Gregor27eeb5e2009-07-22 22:05:02 +00002696 // FIXME: Free this memory properly.
2697 TemplateParamLists.release();
Mike Stump1eb44332009-09-09 15:08:12 +00002698 }
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002699
Douglas Gregor021c3b32009-03-11 23:00:04 +00002700 // C++ [dcl.fct.spec]p5:
2701 // The virtual specifier shall only be used in declarations of
2702 // nonstatic class member functions that appear within a
2703 // member-specification of a class declaration; see 10.3.
2704 //
Chris Lattnereaaebc72009-04-25 08:06:05 +00002705 if (isVirtual && !NewFD->isInvalidDecl()) {
Douglas Gregor021c3b32009-03-11 23:00:04 +00002706 if (!isVirtualOkay) {
Mike Stump1eb44332009-09-09 15:08:12 +00002707 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Douglas Gregor021c3b32009-03-11 23:00:04 +00002708 diag::err_virtual_non_function);
2709 } else if (!CurContext->isRecord()) {
2710 // 'virtual' was specified outside of the class.
2711 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
2712 << CodeModificationHint::CreateRemoval(
2713 SourceRange(D.getDeclSpec().getVirtualSpecLoc()));
2714 } else {
2715 // Okay: Add virtual to the method.
Anders Carlsson77b7f1d2009-05-14 22:15:41 +00002716 cast<CXXMethodDecl>(NewFD)->setVirtualAsWritten(true);
Douglas Gregor021c3b32009-03-11 23:00:04 +00002717 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
2718 CurClass->setAggregate(false);
2719 CurClass->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +00002720 CurClass->setEmpty(false);
Douglas Gregor021c3b32009-03-11 23:00:04 +00002721 CurClass->setPolymorphic(true);
Anders Carlsson347ba892009-04-16 00:08:20 +00002722 CurClass->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002723 CurClass->setHasTrivialCopyConstructor(false);
2724 CurClass->setHasTrivialCopyAssignment(false);
Douglas Gregor021c3b32009-03-11 23:00:04 +00002725 }
2726 }
2727
Douglas Gregora735b202009-10-13 14:39:41 +00002728 if (isFriend) {
2729 if (FunctionTemplate) {
2730 FunctionTemplate->setObjectOfFriendDecl(
2731 /* PreviouslyDeclared= */ PrevDecl != NULL);
2732 FunctionTemplate->setAccess(AS_public);
2733 }
2734 else
2735 NewFD->setObjectOfFriendDecl(/* PreviouslyDeclared= */ PrevDecl != NULL);
2736
2737 NewFD->setAccess(AS_public);
2738 }
2739
2740
Anders Carlssond7ba27d2009-05-14 01:09:04 +00002741 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) {
2742 // Look for virtual methods in base classes that this method might override.
Douglas Gregora8f32e02009-10-06 17:59:45 +00002743 CXXBasePaths Paths;
2744 FindOverriddenMethodData Data;
2745 Data.Method = NewMD;
2746 Data.S = this;
2747 if (cast<CXXRecordDecl>(DC)->lookupInBases(&FindOverriddenMethod, &Data,
2748 Paths)) {
2749 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
Anders Carlssond7ba27d2009-05-14 01:09:04 +00002750 E = Paths.found_decls_end(); I != E; ++I) {
2751 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00002752 if (!CheckOverridingFunctionReturnType(NewMD, OldMD) &&
2753 !CheckOverridingFunctionExceptionSpec(NewMD, OldMD))
Anders Carlsson758a4222009-05-16 23:59:08 +00002754 NewMD->addOverriddenMethod(OldMD);
Anders Carlssond7ba27d2009-05-14 01:09:04 +00002755 }
2756 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00002757 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00002758 }
Mike Stump1eb44332009-09-09 15:08:12 +00002759
2760 if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
Douglas Gregor656de632009-03-11 23:52:16 +00002761 !CurContext->isRecord()) {
2762 // C++ [class.static]p1:
2763 // A data or function member of a class may be declared static
2764 // in a class definition, in which case it is a static member of
2765 // the class.
2766
2767 // Complain about the 'static' specifier if it's on an out-of-line
2768 // member function definition.
Mike Stump1eb44332009-09-09 15:08:12 +00002769 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor656de632009-03-11 23:52:16 +00002770 diag::err_static_out_of_line)
2771 << CodeModificationHint::CreateRemoval(
2772 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
2773 }
2774
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002775 // Handle GNU asm-label extension (encoded as an attribute).
2776 if (Expr *E = (Expr*) D.getAsmLabel()) {
2777 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00002778 StringLiteral *SE = cast<StringLiteral>(E);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002779 NewFD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
Chris Lattner0b2b6e12009-03-04 06:34:08 +00002780 SE->getByteLength())));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002781 }
2782
Chris Lattner2dbd2852009-04-25 06:12:16 +00002783 // Copy the parameter declarations from the declarator D to the function
2784 // declaration NewFD, if they are available. First scavenge them into Params.
2785 llvm::SmallVector<ParmVarDecl*, 16> Params;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002786 if (D.getNumTypeObjects() > 0) {
2787 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2788
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002789 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
2790 // function that takes no arguments, not a function that takes a
2791 // single void argument.
2792 // We let through "const void" here because Sema::GetTypeForDeclarator
2793 // already checks for that case.
2794 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2795 FTI.ArgInfo[0].Param &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00002796 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
Chris Lattner2dbd2852009-04-25 06:12:16 +00002797 // Empty arg list, don't push any params.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002798 ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002799
2800 // In C++, the empty parameter-type-list must be spelled "void"; a
2801 // typedef of void is not permitted.
2802 if (getLangOptions().CPlusPlus &&
Chris Lattner584be452009-04-25 05:44:12 +00002803 Param->getType().getUnqualifiedType() != Context.VoidTy)
Douglas Gregora3a83512009-04-01 23:51:29 +00002804 Diag(Param->getLocation(), diag::err_param_typedef_of_void);
Chris Lattner2dbd2852009-04-25 06:12:16 +00002805 // FIXME: Leaks decl?
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002806 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00002807 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2808 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
2809 assert(Param->getDeclContext() != NewFD && "Was set before ?");
2810 Param->setDeclContext(NewFD);
2811 Params.push_back(Param);
2812 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002813 }
Mike Stump1eb44332009-09-09 15:08:12 +00002814
John McCall183700f2009-09-21 23:43:11 +00002815 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner1ad9b282009-04-25 06:03:53 +00002816 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002817 // following example, we'll need to synthesize (unnamed)
2818 // parameters for use in the declaration.
2819 //
2820 // @code
2821 // typedef void fn(int);
2822 // fn f;
2823 // @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00002824
Chris Lattner1ad9b282009-04-25 06:03:53 +00002825 // Synthesize a parameter for each argument type.
Chris Lattner1ad9b282009-04-25 06:03:53 +00002826 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
2827 AE = FT->arg_type_end(); AI != AE; ++AI) {
2828 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC,
2829 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002830 *AI, /*DInfo=*/0,
2831 VarDecl::None, 0);
Chris Lattner1ad9b282009-04-25 06:03:53 +00002832 Param->setImplicit();
2833 Params.push_back(Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002834 }
Chris Lattner84bb9442009-04-25 18:38:18 +00002835 } else {
2836 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
2837 "Should not need args for typedef of non-prototype fn");
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002838 }
Chris Lattner2dbd2852009-04-25 06:12:16 +00002839 // Finally, we know we have the right number of parameters, install them.
Jay Foadbeaaccd2009-05-21 09:52:38 +00002840 NewFD->setParams(Context, Params.data(), Params.size());
Mike Stump1eb44332009-09-09 15:08:12 +00002841
Douglas Gregor8f301052009-02-24 19:23:27 +00002842 // If name lookup finds a previous declaration that is not in the
2843 // same scope as the new declaration, this may still be an
2844 // acceptable redeclaration.
2845 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002846 !(NewFD->hasLinkage() &&
2847 isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
Douglas Gregor8f301052009-02-24 19:23:27 +00002848 PrevDecl = 0;
Douglas Gregor04495c82009-02-24 01:23:02 +00002849
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00002850 // If the declarator is a template-id, translate the parser's template
2851 // argument list into our AST format.
2852 bool HasExplicitTemplateArgs = false;
John McCall833ca992009-10-29 08:12:44 +00002853 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00002854 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002855 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
2856 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00002857 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2858 TemplateId->getTemplateArgs(),
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00002859 TemplateId->NumArgs);
2860 translateTemplateArguments(TemplateArgsPtr,
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00002861 TemplateArgs);
2862 TemplateArgsPtr.release();
2863
2864 HasExplicitTemplateArgs = true;
2865 LAngleLoc = TemplateId->LAngleLoc;
2866 RAngleLoc = TemplateId->RAngleLoc;
2867
2868 if (FunctionTemplate) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002869 // FIXME: Diagnose function template with explicit template
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00002870 // arguments.
2871 HasExplicitTemplateArgs = false;
2872 } else if (!isFunctionTemplateSpecialization &&
2873 !D.getDeclSpec().isFriendSpecified()) {
2874 // We have encountered something that the user meant to be a
2875 // specialization (because it has explicitly-specified template
2876 // arguments) but that was not introduced with a "template<>" (or had
2877 // too few of them).
2878 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
2879 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
2880 << CodeModificationHint::CreateInsertion(
2881 D.getDeclSpec().getSourceRange().getBegin(),
2882 "template<> ");
2883 isFunctionTemplateSpecialization = true;
2884 }
2885 }
2886
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002887 if (isFunctionTemplateSpecialization) {
2888 if (CheckFunctionTemplateSpecialization(NewFD, HasExplicitTemplateArgs,
2889 LAngleLoc, TemplateArgs.data(),
2890 TemplateArgs.size(), RAngleLoc,
2891 PrevDecl))
2892 NewFD->setInvalidDecl();
2893 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD) &&
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002894 CheckMemberSpecialization(NewFD, PrevDecl))
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002895 NewFD->setInvalidDecl();
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002896
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002897 // Perform semantic checking on the function declaration.
2898 bool OverloadableAttrRequired = false; // FIXME: HACK!
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002899 CheckFunctionDeclaration(NewFD, PrevDecl, isExplicitSpecialization,
2900 Redeclaration, /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002901
Chris Lattnereaaebc72009-04-25 08:06:05 +00002902 if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002903 // An out-of-line member function declaration must also be a
2904 // definition (C++ [dcl.meaning]p1).
Douglas Gregor741fab62009-10-08 15:54:21 +00002905 // Note that this is not the case for explicit specializations of
2906 // function templates or member functions of class templates, per
2907 // C++ [temp.expl.spec]p2.
Douglas Gregord85cef52009-09-17 19:51:30 +00002908 if (!IsFunctionDefinition && !isFriend &&
Douglas Gregor37d681852009-10-12 22:27:17 +00002909 !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002910 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
2911 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00002912 NewFD->setInvalidDecl();
Anders Carlsson203cb712009-08-29 00:56:38 +00002913 } else if (!Redeclaration && (!PrevDecl || !isUsingDecl(PrevDecl))) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002914 // The user tried to provide an out-of-line definition for a
2915 // function that is a member of a class or namespace, but there
Mike Stump1eb44332009-09-09 15:08:12 +00002916 // was no such member function declared (C++ [class.mfct]p2,
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002917 // C++ [namespace.memdef]p2). For example:
Mike Stump1eb44332009-09-09 15:08:12 +00002918 //
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002919 // class X {
2920 // void f() const;
Mike Stump1eb44332009-09-09 15:08:12 +00002921 // };
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002922 //
2923 // void X::f() { } // ill-formed
2924 //
2925 // Complain about this problem, and attempt to suggest close
2926 // matches (e.g., those that differ only in cv-qualifiers and
2927 // whether the parameter types are references).
2928 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
Douglas Gregor3f093272009-10-13 21:16:44 +00002929 << Name << DC << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00002930 NewFD->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002931
John McCalla24dc2e2009-11-17 02:14:36 +00002932 LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
2933 LookupResult::ForRedeclaration);
2934 LookupQualifiedName(Prev, DC);
Mike Stump1eb44332009-09-09 15:08:12 +00002935 assert(!Prev.isAmbiguous() &&
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002936 "Cannot have an ambiguity in previous-declaration lookup");
2937 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
2938 Func != FuncEnd; ++Func) {
2939 if (isa<FunctionDecl>(*Func) &&
2940 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
2941 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
2942 }
Mike Stump1eb44332009-09-09 15:08:12 +00002943
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002944 PrevDecl = 0;
2945 }
2946 }
2947
2948 // Handle attributes. We need to have merged decls when handling attributes
2949 // (for example to check for conflicts, etc).
2950 // FIXME: This needs to happen before we merge declarations. Then,
2951 // let attribute merging cope with attribute conflicts.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002952 ProcessDeclAttributes(S, NewFD, D);
Ryan Flynn478fbc62009-07-25 22:29:44 +00002953
2954 // attributes declared post-definition are currently ignored
Douglas Gregorfdc39192009-08-28 22:54:55 +00002955 if (Redeclaration && PrevDecl) {
Ryan Flynn478fbc62009-07-25 22:29:44 +00002956 const FunctionDecl *Def, *PrevFD = dyn_cast<FunctionDecl>(PrevDecl);
2957 if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) {
2958 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
2959 Diag(Def->getLocation(), diag::note_previous_definition);
2960 }
2961 }
2962
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002963 AddKnownFunctionAttributes(NewFD);
2964
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002965 if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002966 // If a function name is overloadable in C, then every function
2967 // with that name must be marked "overloadable".
2968 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
2969 << Redeclaration << NewFD;
2970 if (PrevDecl)
Mike Stump1eb44332009-09-09 15:08:12 +00002971 Diag(PrevDecl->getLocation(),
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002972 diag::note_attribute_overloadable_prev_overload);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002973 NewFD->addAttr(::new (Context) OverloadableAttr());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002974 }
2975
2976 // If this is a locally-scoped extern C function, update the
2977 // map of such names.
Douglas Gregor48a83b52009-09-12 00:17:51 +00002978 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
Chris Lattnereaaebc72009-04-25 08:06:05 +00002979 && !NewFD->isInvalidDecl())
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002980 RegisterLocallyScopedExternCDecl(NewFD, PrevDecl, S);
2981
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00002982 // Set this FunctionDecl's range up to the right paren.
2983 NewFD->setLocEnd(D.getSourceRange().getEnd());
2984
Douglas Gregore53060f2009-06-25 22:08:12 +00002985 if (FunctionTemplate && NewFD->isInvalidDecl())
2986 FunctionTemplate->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002987
Douglas Gregore53060f2009-06-25 22:08:12 +00002988 if (FunctionTemplate)
2989 return FunctionTemplate;
Mike Stump1eb44332009-09-09 15:08:12 +00002990
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002991 return NewFD;
2992}
2993
2994/// \brief Perform semantic checking of a new function declaration.
2995///
2996/// Performs semantic analysis of the new function declaration
2997/// NewFD. This routine performs all semantic checking that does not
2998/// require the actual declarator involved in the declaration, and is
2999/// used both for the declaration of functions as they are parsed
3000/// (called via ActOnDeclarator) and for the declaration of functions
3001/// that have been instantiated via C++ template instantiation (called
3002/// via InstantiateDecl).
3003///
Douglas Gregorfd056bc2009-10-13 16:30:37 +00003004/// \param IsExplicitSpecialiation whether this new function declaration is
3005/// an explicit specialization of the previous declaration.
3006///
Chris Lattnereaaebc72009-04-25 08:06:05 +00003007/// This sets NewFD->isInvalidDecl() to true if there was an error.
3008void Sema::CheckFunctionDeclaration(FunctionDecl *NewFD, NamedDecl *&PrevDecl,
Douglas Gregorfd056bc2009-10-13 16:30:37 +00003009 bool IsExplicitSpecialization,
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003010 bool &Redeclaration,
3011 bool &OverloadableAttrRequired) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00003012 // If NewFD is already known erroneous, don't do any of this checking.
3013 if (NewFD->isInvalidDecl())
3014 return;
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003015
Eli Friedman88f7b572009-05-16 12:15:55 +00003016 if (NewFD->getResultType()->isVariablyModifiedType()) {
3017 // Functions returning a variably modified type violate C99 6.7.5.2p2
3018 // because all functions have linkage.
3019 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
3020 return NewFD->setInvalidDecl();
3021 }
3022
Douglas Gregor48a83b52009-09-12 00:17:51 +00003023 if (NewFD->isMain())
3024 CheckMain(NewFD);
John McCall8c4859a2009-07-24 03:03:21 +00003025
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003026 // Check for a previous declaration of this name.
Douglas Gregor48a83b52009-09-12 00:17:51 +00003027 if (!PrevDecl && NewFD->isExternC()) {
Douglas Gregor63935192009-03-02 00:19:53 +00003028 // Since we did not find anything by this name and we're declaring
3029 // an extern "C" function, look for a non-visible extern "C"
3030 // declaration with the same name.
3031 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003032 = LocallyScopedExternalDecls.find(NewFD->getDeclName());
Douglas Gregor63935192009-03-02 00:19:53 +00003033 if (Pos != LocallyScopedExternalDecls.end())
3034 PrevDecl = Pos->second;
3035 }
3036
Douglas Gregor04495c82009-02-24 01:23:02 +00003037 // Merge or overload the declaration with an existing declaration of
3038 // the same name, if appropriate.
Douglas Gregor04495c82009-02-24 01:23:02 +00003039 if (PrevDecl) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00003040 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003041 // a declaration that requires merging. If it's an overload,
3042 // there's no more work to do here; we'll just add the new
3043 // function to the scope.
3044 OverloadedFunctionDecl::function_iterator MatchedDecl;
Douglas Gregorae170942009-02-13 00:26:38 +00003045
3046 if (!getLangOptions().CPlusPlus &&
Douglas Gregorc6666f82009-02-18 06:34:51 +00003047 AllowOverloadingOfFunction(PrevDecl, Context)) {
Douglas Gregorae170942009-02-13 00:26:38 +00003048 OverloadableAttrRequired = true;
3049
Douglas Gregorc6666f82009-02-18 06:34:51 +00003050 // Functions marked "overloadable" must have a prototype (that
3051 // we can't get through declaration merging).
John McCall183700f2009-09-21 23:43:11 +00003052 if (!NewFD->getType()->getAs<FunctionProtoType>()) {
Douglas Gregorc6666f82009-02-18 06:34:51 +00003053 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_no_prototype)
3054 << NewFD;
Douglas Gregorc6666f82009-02-18 06:34:51 +00003055 Redeclaration = true;
3056
3057 // Turn this into a variadic function with no parameters.
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003058 QualType R = Context.getFunctionType(
John McCall183700f2009-09-21 23:43:11 +00003059 NewFD->getType()->getAs<FunctionType>()->getResultType(),
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003060 0, 0, true, 0);
Douglas Gregorc6666f82009-02-18 06:34:51 +00003061 NewFD->setType(R);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003062 return NewFD->setInvalidDecl();
Douglas Gregorc6666f82009-02-18 06:34:51 +00003063 }
3064 }
3065
Anders Carlsson203cb712009-08-29 00:56:38 +00003066 if (PrevDecl &&
Mike Stump1eb44332009-09-09 15:08:12 +00003067 (!AllowOverloadingOfFunction(PrevDecl, Context) ||
Anders Carlsson203cb712009-08-29 00:56:38 +00003068 !IsOverload(NewFD, PrevDecl, MatchedDecl)) && !isUsingDecl(PrevDecl)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00003069 Redeclaration = true;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003070 Decl *OldDecl = PrevDecl;
3071
3072 // If PrevDecl was an overloaded function, extract the
3073 // FunctionDecl that matched.
3074 if (isa<OverloadedFunctionDecl>(PrevDecl))
3075 OldDecl = *MatchedDecl;
3076
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003077 // NewFD and OldDecl represent declarations that need to be
Mike Stump1eb44332009-09-09 15:08:12 +00003078 // merged.
Douglas Gregorcda9c672009-02-16 17:45:42 +00003079 if (MergeFunctionDecl(NewFD, OldDecl))
Chris Lattnereaaebc72009-04-25 08:06:05 +00003080 return NewFD->setInvalidDecl();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003081
Douglas Gregore53060f2009-06-25 22:08:12 +00003082 if (FunctionTemplateDecl *OldTemplateDecl
Douglas Gregor37d681852009-10-12 22:27:17 +00003083 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
Douglas Gregorfd056bc2009-10-13 16:30:37 +00003084 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
Douglas Gregor37d681852009-10-12 22:27:17 +00003085 FunctionTemplateDecl *NewTemplateDecl
3086 = NewFD->getDescribedFunctionTemplate();
3087 assert(NewTemplateDecl && "Template/non-template mismatch");
3088 if (CXXMethodDecl *Method
3089 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
3090 Method->setAccess(OldTemplateDecl->getAccess());
3091 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
3092 }
Douglas Gregorfd056bc2009-10-13 16:30:37 +00003093
3094 // If this is an explicit specialization of a member that is a function
3095 // template, mark it as a member specialization.
3096 if (IsExplicitSpecialization &&
3097 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
3098 NewTemplateDecl->setMemberSpecialization();
3099 assert(OldTemplateDecl->isMemberSpecialization());
3100 }
Douglas Gregor37d681852009-10-12 22:27:17 +00003101 } else {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00003102 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
3103 NewFD->setAccess(OldDecl->getAccess());
Douglas Gregore53060f2009-06-25 22:08:12 +00003104 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00003105 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003106 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00003107 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003108
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003109 // Semantic checking for this function declaration (in isolation).
3110 if (getLangOptions().CPlusPlus) {
3111 // C++-specific checks.
3112 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
3113 CheckConstructor(Constructor);
Anders Carlsson6d701392009-11-15 22:49:34 +00003114 } else if (CXXDestructorDecl *Destructor =
3115 dyn_cast<CXXDestructorDecl>(NewFD)) {
3116 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003117 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson6d701392009-11-15 22:49:34 +00003118
3119 // FIXME: Shouldn't we be able to perform thisc heck even when the class
3120 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003121 if (!ClassType->isDependentType()) {
3122 DeclarationName Name
3123 = Context.DeclarationNames.getCXXDestructorName(
3124 Context.getCanonicalType(ClassType));
3125 if (NewFD->getDeclName() != Name) {
3126 Diag(NewFD->getLocation(), diag::err_destructor_name);
3127 return NewFD->setInvalidDecl();
3128 }
Anders Carlsson6d701392009-11-15 22:49:34 +00003129
3130 CheckDestructor(Destructor);
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003131 }
Anders Carlsson6d701392009-11-15 22:49:34 +00003132
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003133 Record->setUserDeclaredDestructor(true);
3134 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
3135 // user-defined destructor.
3136 Record->setPOD(false);
3137
3138 // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
3139 // declared destructor.
3140 // FIXME: C++0x: don't do this for "= default" destructors
3141 Record->setHasTrivialDestructor(false);
3142 } else if (CXXConversionDecl *Conversion
3143 = dyn_cast<CXXConversionDecl>(NewFD))
3144 ActOnConversionDeclarator(Conversion);
3145
3146 // Extra checking for C++ overloaded operators (C++ [over.oper]).
3147 if (NewFD->isOverloadedOperator() &&
3148 CheckOverloadedOperatorDeclaration(NewFD))
3149 return NewFD->setInvalidDecl();
3150
3151 // In C++, check default arguments now that we have merged decls. Unless
3152 // the lexical context is the class, because in this case this is done
3153 // during delayed parsing anyway.
3154 if (!CurContext->isRecord())
3155 CheckCXXDefaultArguments(NewFD);
3156 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003157}
3158
John McCall8c4859a2009-07-24 03:03:21 +00003159void Sema::CheckMain(FunctionDecl* FD) {
John McCall13591ed2009-07-25 04:36:53 +00003160 // C++ [basic.start.main]p3: A program that declares main to be inline
3161 // or static is ill-formed.
3162 // C99 6.7.4p4: In a hosted environment, the inline function specifier
3163 // shall not appear in a declaration of main.
3164 // static main is not an error under C99, but we should warn about it.
Douglas Gregor0130f3c2009-10-27 21:01:01 +00003165 bool isInline = FD->isInlineSpecified();
John McCall13591ed2009-07-25 04:36:53 +00003166 bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
3167 if (isInline || isStatic) {
3168 unsigned diagID = diag::warn_unusual_main_decl;
3169 if (isInline || getLangOptions().CPlusPlus)
3170 diagID = diag::err_unusual_main_decl;
3171
3172 int which = isStatic + (isInline << 1) - 1;
3173 Diag(FD->getLocation(), diagID) << which;
3174 }
3175
3176 QualType T = FD->getType();
3177 assert(T->isFunctionType() && "function decl is not of function type");
John McCall183700f2009-09-21 23:43:11 +00003178 const FunctionType* FT = T->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003179
John McCall13591ed2009-07-25 04:36:53 +00003180 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
3181 // TODO: add a replacement fixit to turn the return type into 'int'.
3182 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
3183 FD->setInvalidDecl(true);
3184 }
3185
3186 // Treat protoless main() as nullary.
3187 if (isa<FunctionNoProtoType>(FT)) return;
3188
3189 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
3190 unsigned nparams = FTP->getNumArgs();
3191 assert(FD->getNumParams() == nparams);
3192
3193 if (nparams > 3) {
3194 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
3195 FD->setInvalidDecl(true);
3196 nparams = 3;
3197 }
3198
3199 // FIXME: a lot of the following diagnostics would be improved
3200 // if we had some location information about types.
3201
3202 QualType CharPP =
3203 Context.getPointerType(Context.getPointerType(Context.CharTy));
3204 QualType Expected[] = { Context.IntTy, CharPP, CharPP };
3205
3206 for (unsigned i = 0; i < nparams; ++i) {
3207 QualType AT = FTP->getArgType(i);
3208
3209 bool mismatch = true;
3210
3211 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
3212 mismatch = false;
3213 else if (Expected[i] == CharPP) {
3214 // As an extension, the following forms are okay:
3215 // char const **
3216 // char const * const *
3217 // char * const *
3218
John McCall0953e762009-09-24 19:53:00 +00003219 QualifierCollector qs;
John McCall13591ed2009-07-25 04:36:53 +00003220 const PointerType* PT;
Ted Kremenek6217b802009-07-29 21:53:49 +00003221 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
3222 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
John McCall13591ed2009-07-25 04:36:53 +00003223 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
3224 qs.removeConst();
3225 mismatch = !qs.empty();
3226 }
3227 }
3228
3229 if (mismatch) {
3230 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
3231 // TODO: suggest replacing given type with expected type
3232 FD->setInvalidDecl(true);
3233 }
3234 }
3235
3236 if (nparams == 1 && !FD->isInvalidDecl()) {
3237 Diag(FD->getLocation(), diag::warn_main_one_arg);
3238 }
John McCall8c4859a2009-07-24 03:03:21 +00003239}
3240
Eli Friedmanc594b322008-05-20 13:48:25 +00003241bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman3b8a36a2009-02-27 04:17:12 +00003242 // FIXME: Need strict checking. In C89, we need to check for
3243 // any assignment, increment, decrement, function-calls, or
3244 // commas outside of a sizeof. In C99, it's the same list,
3245 // except that the aforementioned are allowed in unevaluated
3246 // expressions. Everything else falls under the
3247 // "may accept other forms of constant expressions" exception.
3248 // (We never end up here for C++, so the constant expression
3249 // rules there don't matter.)
Chris Lattner111c2ee2009-02-24 21:54:33 +00003250 if (Init->isConstantInitializer(Context))
Eli Friedman578a9722009-02-22 06:45:27 +00003251 return false;
Eli Friedman21298282009-02-26 04:47:58 +00003252 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
3253 << Init->getSourceRange();
Eli Friedmanc594b322008-05-20 13:48:25 +00003254 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00003255}
3256
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003257void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
3258 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003259}
3260
3261/// AddInitializerToDecl - Adds the initializer Init to the
3262/// declaration dcl. If DirectInit is true, this is C++ direct
3263/// initialization rather than copy initialization.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003264void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
3265 Decl *RealDecl = dcl.getAs<Decl>();
Chris Lattner9a11b9a2007-10-19 20:10:30 +00003266 // If there is no declaration, there was an error parsing it. Just ignore
3267 // the initializer.
Eli Friedman3b8a36a2009-02-27 04:17:12 +00003268 if (RealDecl == 0)
Chris Lattner9a11b9a2007-10-19 20:10:30 +00003269 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003270
Douglas Gregor021c3b32009-03-11 23:00:04 +00003271 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
3272 // With declarators parsed the way they are, the parser cannot
3273 // distinguish between a normal initializer and a pure-specifier.
3274 // Thus this grotesque test.
3275 IntegerLiteral *IL;
3276 Expr *Init = static_cast<Expr *>(init.get());
3277 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
3278 Context.getCanonicalType(IL->getType()) == Context.IntTy) {
Anders Carlsson77b7f1d2009-05-14 22:15:41 +00003279 if (Method->isVirtualAsWritten()) {
Douglas Gregor021c3b32009-03-11 23:00:04 +00003280 Method->setPure();
Anders Carlsson67e4dd22009-03-22 01:52:17 +00003281
3282 // A class is abstract if at least one function is pure virtual.
3283 cast<CXXRecordDecl>(CurContext)->setAbstract(true);
Douglas Gregor33297562009-03-27 04:38:56 +00003284 } else if (!Method->isInvalidDecl()) {
Douglas Gregor021c3b32009-03-11 23:00:04 +00003285 Diag(Method->getLocation(), diag::err_non_virtual_pure)
3286 << Method->getDeclName() << Init->getSourceRange();
3287 Method->setInvalidDecl();
3288 }
3289 } else {
3290 Diag(Method->getLocation(), diag::err_member_function_initialization)
3291 << Method->getDeclName() << Init->getSourceRange();
3292 Method->setInvalidDecl();
3293 }
3294 return;
3295 }
3296
Steve Naroff410e3e22007-09-12 20:13:48 +00003297 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3298 if (!VDecl) {
Douglas Gregor021c3b32009-03-11 23:00:04 +00003299 if (getLangOptions().CPlusPlus &&
3300 RealDecl->getLexicalDeclContext()->isRecord() &&
3301 isa<NamedDecl>(RealDecl))
3302 Diag(RealDecl->getLocation(), diag::err_member_initialization)
3303 << cast<NamedDecl>(RealDecl)->getDeclName();
3304 else
3305 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00003306 RealDecl->setInvalidDecl();
3307 return;
Eli Friedman3b8a36a2009-02-27 04:17:12 +00003308 }
3309
Eli Friedman49e2b8e2009-11-14 03:40:14 +00003310 // A definition must end up with a complete type, which means it must be
3311 // complete with the restriction that an array type might be completed by the
3312 // initializer; note that later code assumes this restriction.
3313 QualType BaseDeclType = VDecl->getType();
3314 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
3315 BaseDeclType = Array->getElementType();
3316 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
Eli Friedmana31feca2009-04-13 21:28:54 +00003317 diag::err_typecheck_decl_incomplete_type)) {
3318 RealDecl->setInvalidDecl();
3319 return;
3320 }
3321
Douglas Gregor275a3692009-03-10 23:43:53 +00003322 const VarDecl *Def = 0;
3323 if (VDecl->getDefinition(Def)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003324 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor275a3692009-03-10 23:43:53 +00003325 << VDecl->getDeclName();
3326 Diag(Def->getLocation(), diag::note_previous_definition);
3327 VDecl->setInvalidDecl();
3328 return;
3329 }
3330
Eli Friedman3b8a36a2009-02-27 04:17:12 +00003331 // Take ownership of the expression, now that we're sure we have somewhere
3332 // to put it.
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003333 Expr *Init = init.takeAs<Expr>();
Eli Friedman3b8a36a2009-02-27 04:17:12 +00003334 assert(Init && "missing initializer");
3335
Steve Naroffbb204692007-09-12 14:07:44 +00003336 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00003337 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00003338 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00003339 if (VDecl->isBlockVarDecl()) {
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003340 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00003341 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00003342 VDecl->setInvalidDecl();
3343 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003344 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Anders Carlsson0f5f2c62009-05-30 20:41:30 +00003345 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00003346 VDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003347
Anders Carlssonc5eb7312008-08-22 05:00:02 +00003348 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmanda153232009-02-20 01:34:21 +00003349 // Don't check invalid declarations to avoid emitting useless diagnostics.
3350 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003351 if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
Anders Carlssonc5eb7312008-08-22 05:00:02 +00003352 CheckForConstantInitializer(Init, DclT);
3353 }
Steve Naroffbb204692007-09-12 14:07:44 +00003354 }
Mike Stump1eb44332009-09-09 15:08:12 +00003355 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor021c3b32009-03-11 23:00:04 +00003356 VDecl->getLexicalDeclContext()->isRecord()) {
3357 // This is an in-class initialization for a static data member, e.g.,
3358 //
3359 // struct S {
3360 // static const int value = 17;
3361 // };
3362
3363 // Attach the initializer
Douglas Gregor78d15832009-05-26 18:54:04 +00003364 VDecl->setInit(Context, Init);
Douglas Gregor021c3b32009-03-11 23:00:04 +00003365
3366 // C++ [class.mem]p4:
3367 // A member-declarator can contain a constant-initializer only
3368 // if it declares a static member (9.4) of const integral or
3369 // const enumeration type, see 9.4.2.
3370 QualType T = VDecl->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003371 if (!T->isDependentType() &&
Douglas Gregor021c3b32009-03-11 23:00:04 +00003372 (!Context.getCanonicalType(T).isConstQualified() ||
3373 !T->isIntegralType())) {
3374 Diag(VDecl->getLocation(), diag::err_member_initialization)
3375 << VDecl->getDeclName() << Init->getSourceRange();
3376 VDecl->setInvalidDecl();
3377 } else {
3378 // C++ [class.static.data]p4:
3379 // If a static data member is of const integral or const
3380 // enumeration type, its declaration in the class definition
3381 // can specify a constant-initializer which shall be an
3382 // integral constant expression (5.19).
3383 if (!Init->isTypeDependent() &&
3384 !Init->getType()->isIntegralType()) {
3385 // We have a non-dependent, non-integral or enumeration type.
Mike Stump1eb44332009-09-09 15:08:12 +00003386 Diag(Init->getSourceRange().getBegin(),
Douglas Gregor021c3b32009-03-11 23:00:04 +00003387 diag::err_in_class_initializer_non_integral_type)
3388 << Init->getType() << Init->getSourceRange();
3389 VDecl->setInvalidDecl();
3390 } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
3391 // Check whether the expression is a constant expression.
3392 llvm::APSInt Value;
3393 SourceLocation Loc;
3394 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
3395 Diag(Loc, diag::err_in_class_initializer_non_constant)
3396 << Init->getSourceRange();
3397 VDecl->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003398 } else if (!VDecl->getType()->isDependentType())
Eli Friedman73c39ab2009-10-20 08:27:19 +00003399 ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
Douglas Gregor021c3b32009-03-11 23:00:04 +00003400 }
3401 }
Steve Naroff248a7532008-04-15 22:42:06 +00003402 } else if (VDecl->isFileVarDecl()) {
Steve Naroffee3899e2009-04-15 15:20:03 +00003403 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00003404 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00003405 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003406 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003407 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00003408 VDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003409
Anders Carlssonc5eb7312008-08-22 05:00:02 +00003410 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmanda153232009-02-20 01:34:21 +00003411 // Don't check invalid declarations to avoid emitting useless diagnostics.
3412 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Anders Carlssonc5eb7312008-08-22 05:00:02 +00003413 // C99 6.7.8p4. All file scoped initializers need to be constant.
3414 CheckForConstantInitializer(Init, DclT);
3415 }
Steve Naroffbb204692007-09-12 14:07:44 +00003416 }
3417 // If the type changed, it means we had an incomplete type that was
Mike Stump1eb44332009-09-09 15:08:12 +00003418 // completed by the initializer. For example:
Steve Naroffbb204692007-09-12 14:07:44 +00003419 // int ary[] = { 1, 3, 5 };
3420 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00003421 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00003422 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00003423 Init->setType(DclT);
3424 }
Mike Stump1eb44332009-09-09 15:08:12 +00003425
3426 Init = MaybeCreateCXXExprWithTemporaries(Init,
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003427 /*ShouldDestroyTemporaries=*/true);
Steve Naroffbb204692007-09-12 14:07:44 +00003428 // Attach the initializer to the decl.
Douglas Gregor78d15832009-05-26 18:54:04 +00003429 VDecl->setInit(Context, Init);
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00003430
3431 // If the previous declaration of VDecl was a tentative definition,
3432 // remove it from the set of tentative definitions.
3433 if (VDecl->getPreviousDeclaration() &&
3434 VDecl->getPreviousDeclaration()->isTentativeDefinition(Context)) {
Chris Lattner63d65f82009-09-08 18:19:27 +00003435 bool Deleted = TentativeDefinitions.erase(VDecl->getDeclName());
3436 assert(Deleted && "Unrecorded tentative definition?"); Deleted=Deleted;
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00003437 }
3438
Steve Naroffbb204692007-09-12 14:07:44 +00003439 return;
3440}
3441
Mike Stump1eb44332009-09-09 15:08:12 +00003442void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
Anders Carlsson6a75cd92009-07-11 00:34:39 +00003443 bool TypeContainsUndeducedAuto) {
Chris Lattnerb28317a2009-03-28 19:18:32 +00003444 Decl *RealDecl = dcl.getAs<Decl>();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003445
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00003446 // If there is no declaration, there was an error parsing it. Just ignore it.
3447 if (RealDecl == 0)
3448 return;
3449
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003450 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
3451 QualType Type = Var->getType();
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00003452
3453 // Record tentative definitions.
Chris Lattner63d65f82009-09-08 18:19:27 +00003454 if (Var->isTentativeDefinition(Context)) {
3455 std::pair<llvm::DenseMap<DeclarationName, VarDecl *>::iterator, bool>
Mike Stump1eb44332009-09-09 15:08:12 +00003456 InsertPair =
Chris Lattner63d65f82009-09-08 18:19:27 +00003457 TentativeDefinitions.insert(std::make_pair(Var->getDeclName(), Var));
Mike Stump1eb44332009-09-09 15:08:12 +00003458
Chris Lattner63d65f82009-09-08 18:19:27 +00003459 // Keep the latest definition in the map. If we see 'int i; int i;' we
3460 // want the second one in the map.
3461 InsertPair.first->second = Var;
3462
3463 // However, for the list, we don't care about the order, just make sure
3464 // that there are no dupes for a given declaration name.
3465 if (InsertPair.second)
3466 TentativeDefinitionList.push_back(Var->getDeclName());
3467 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00003468
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003469 // C++ [dcl.init.ref]p3:
3470 // The initializer can be omitted for a reference only in a
3471 // parameter declaration (8.3.5), in the declaration of a
3472 // function return type, in the declaration of a class member
3473 // within its class declaration (9.2), and where the extern
3474 // specifier is explicitly used.
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003475 if (Type->isReferenceType() && !Var->hasExternalStorage()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003476 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003477 << Var->getDeclName()
3478 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00003479 Var->setInvalidDecl();
3480 return;
3481 }
3482
Anders Carlsson6a75cd92009-07-11 00:34:39 +00003483 // C++0x [dcl.spec.auto]p3
3484 if (TypeContainsUndeducedAuto) {
3485 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
3486 << Var->getDeclName() << Type;
3487 Var->setInvalidDecl();
3488 return;
3489 }
Mike Stump1eb44332009-09-09 15:08:12 +00003490
Sebastian Redl6e824752009-11-05 19:47:47 +00003491 // An array without size is an incomplete type, and there are no special
3492 // rules in C++ to make such a definition acceptable.
3493 if (getLangOptions().CPlusPlus && Type->isIncompleteArrayType() &&
3494 !Var->hasExternalStorage()) {
3495 Diag(Var->getLocation(),
3496 diag::err_typecheck_incomplete_array_needs_initializer);
3497 Var->setInvalidDecl();
3498 return;
3499 }
3500
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003501 // C++ [temp.expl.spec]p15:
3502 // An explicit specialization of a static data member of a template is a
3503 // definition if the declaration includes an initializer; otherwise, it
3504 // is a declaration.
3505 if (Var->isStaticDataMember() &&
3506 Var->getInstantiatedFromStaticDataMember() &&
3507 Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3508 return;
3509
Douglas Gregor18fe5682008-11-03 20:45:27 +00003510 // C++ [dcl.init]p9:
Douglas Gregor18fe5682008-11-03 20:45:27 +00003511 // If no initializer is specified for an object, and the object
3512 // is of (possibly cv-qualified) non-POD class type (or array
3513 // thereof), the object shall be default-initialized; if the
3514 // object is of const-qualified type, the underlying class type
3515 // shall have a user-declared default constructor.
Douglas Gregorf8d8d1a2009-09-09 23:58:28 +00003516 //
3517 // FIXME: Diagnose the "user-declared default constructor" bit.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003518 if (getLangOptions().CPlusPlus) {
3519 QualType InitType = Type;
3520 if (const ArrayType *Array = Context.getAsArrayType(Type))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00003521 InitType = Context.getBaseElementType(Array);
Douglas Gregor48a83b52009-09-12 00:17:51 +00003522 if ((!Var->hasExternalStorage() && !Var->isExternC()) &&
Douglas Gregor8e92bf32009-05-29 14:25:00 +00003523 InitType->isRecordType() && !InitType->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003524 if (!RequireCompleteType(Var->getLocation(), InitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003525 diag::err_invalid_incomplete_type_use)) {
3526 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3527
3528 CXXConstructorDecl *Constructor
3529 = PerformInitializationByConstructor(InitType,
3530 MultiExprArg(*this, 0, 0),
Douglas Gregor2943aed2009-03-03 04:44:36 +00003531 Var->getLocation(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003532 SourceRange(Var->getLocation(),
3533 Var->getLocation()),
Douglas Gregor2943aed2009-03-03 04:44:36 +00003534 Var->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +00003535 IK_Default,
3536 ConstructorArgs);
3537
Douglas Gregorf8d8d1a2009-09-09 23:58:28 +00003538 // FIXME: Location info for the variable initialization?
3539 if (!Constructor)
Douglas Gregor39da0b82009-09-09 23:08:42 +00003540 Var->setInvalidDecl();
Douglas Gregorf8d8d1a2009-09-09 23:58:28 +00003541 else {
3542 // FIXME: Cope with initialization of arrays
3543 if (!Constructor->isTrivial() &&
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003544 InitializeVarWithConstructor(Var, Constructor,
Douglas Gregorf8d8d1a2009-09-09 23:58:28 +00003545 move_arg(ConstructorArgs)))
3546 Var->setInvalidDecl();
3547
Douglas Gregor39da0b82009-09-09 23:08:42 +00003548 FinalizeVarWithDestructor(Var, InitType);
Douglas Gregorf8d8d1a2009-09-09 23:58:28 +00003549 }
Douglas Gregor9916a042009-10-08 16:41:22 +00003550 } else {
3551 Var->setInvalidDecl();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003552 }
Douglas Gregor18fe5682008-11-03 20:45:27 +00003553 }
3554 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003555
Douglas Gregor818ce482008-10-29 13:50:18 +00003556#if 0
3557 // FIXME: Temporarily disabled because we are not properly parsing
Mike Stump1eb44332009-09-09 15:08:12 +00003558 // linkage specifications on declarations, e.g.,
Douglas Gregor818ce482008-10-29 13:50:18 +00003559 //
3560 // extern "C" const CGPoint CGPointerZero;
3561 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003562 // C++ [dcl.init]p9:
3563 //
3564 // If no initializer is specified for an object, and the
3565 // object is of (possibly cv-qualified) non-POD class type (or
3566 // array thereof), the object shall be default-initialized; if
3567 // the object is of const-qualified type, the underlying class
3568 // type shall have a user-declared default
3569 // constructor. Otherwise, if no initializer is specified for
3570 // an object, the object and its subobjects, if any, have an
3571 // indeterminate initial value; if the object or any of its
3572 // subobjects are of const-qualified type, the program is
3573 // ill-formed.
3574 //
3575 // This isn't technically an error in C, so we don't diagnose it.
3576 //
3577 // FIXME: Actually perform the POD/user-defined default
3578 // constructor check.
3579 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00003580 Context.getCanonicalType(Type).isConstQualified() &&
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003581 !Var->hasExternalStorage())
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003582 Diag(Var->getLocation(), diag::err_const_var_requires_init)
3583 << Var->getName()
3584 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00003585#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003586 }
3587}
3588
Eli Friedmanc1dc6532009-05-29 01:49:24 +00003589Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
3590 DeclPtrTy *Group,
Chris Lattner682bf922009-03-29 16:50:03 +00003591 unsigned NumDecls) {
3592 llvm::SmallVector<Decl*, 8> Decls;
Eli Friedmanc1dc6532009-05-29 01:49:24 +00003593
3594 if (DS.isTypeSpecOwned())
3595 Decls.push_back((Decl*)DS.getTypeRep());
3596
Chris Lattner682bf922009-03-29 16:50:03 +00003597 for (unsigned i = 0; i != NumDecls; ++i)
3598 if (Decl *D = Group[i].getAs<Decl>())
3599 Decls.push_back(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003600
Steve Naroffbb204692007-09-12 14:07:44 +00003601 // Perform semantic analysis that depends on having fully processed both
3602 // the declarator and initializer.
Chris Lattner682bf922009-03-29 16:50:03 +00003603 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
3604 VarDecl *IDecl = dyn_cast<VarDecl>(Decls[i]);
Steve Naroffbb204692007-09-12 14:07:44 +00003605 if (!IDecl)
3606 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00003607 QualType T = IDecl->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003608
Steve Naroffbb204692007-09-12 14:07:44 +00003609 // Block scope. C99 6.7p7: If an identifier for an object is declared with
3610 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003611 if (IDecl->isBlockVarDecl() && !IDecl->hasExternalStorage()) {
Sebastian Redld75191f2009-10-17 19:37:06 +00003612 if (T->isDependentType()) {
3613 // If T is dependent, we should not require a complete type.
3614 // (RequireCompleteType shouldn't be called with dependent types.)
3615 // But we still can at least check if we've got an array of unspecified
3616 // size without an initializer.
3617 if (!IDecl->isInvalidDecl() && T->isIncompleteArrayType() &&
3618 !IDecl->getInit()) {
3619 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
3620 << T;
3621 IDecl->setInvalidDecl();
3622 }
3623 } else if (!IDecl->isInvalidDecl()) {
3624 // If T is an incomplete array type with an initializer list that is
3625 // dependent on something, its size has not been fixed. We could attempt
3626 // to fix the size for such arrays, but we would still have to check
3627 // here for initializers containing a C++0x vararg expansion, e.g.
3628 // template <typename... Args> void f(Args... args) {
3629 // int vals[] = { args };
3630 // }
Douglas Gregor89c49f02009-11-09 22:08:55 +00003631 const IncompleteArrayType *IAT = Context.getAsIncompleteArrayType(T);
Sebastian Redld75191f2009-10-17 19:37:06 +00003632 Expr *Init = IDecl->getInit();
3633 if (IAT && Init &&
3634 (Init->isTypeDependent() || Init->isValueDependent())) {
3635 // Check that the member type of the array is complete, at least.
3636 if (RequireCompleteType(IDecl->getLocation(), IAT->getElementType(),
3637 diag::err_typecheck_decl_incomplete_type))
3638 IDecl->setInvalidDecl();
3639 } else if (RequireCompleteType(IDecl->getLocation(), T,
3640 diag::err_typecheck_decl_incomplete_type))
3641 IDecl->setInvalidDecl();
3642 }
Steve Naroffbb204692007-09-12 14:07:44 +00003643 }
Douglas Gregorec8b59f2009-07-20 18:46:59 +00003644 // File scope. C99 6.9.2p2: A declaration of an identifier for an
Steve Naroffbb204692007-09-12 14:07:44 +00003645 // object that has file scope without an initializer, and without a
3646 // storage-class specifier or with the storage-class specifier "static",
3647 // constitutes a tentative definition. Note: A tentative definition with
3648 // external linkage is valid (C99 6.2.2p5).
Douglas Gregorec8b59f2009-07-20 18:46:59 +00003649 if (IDecl->isTentativeDefinition(Context) && !IDecl->isInvalidDecl()) {
3650 if (const IncompleteArrayType *ArrayT
3651 = Context.getAsIncompleteArrayType(T)) {
3652 if (RequireCompleteType(IDecl->getLocation(),
3653 ArrayT->getElementType(),
3654 diag::err_illegal_decl_array_incomplete_type))
3655 IDecl->setInvalidDecl();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003656 } else if (IDecl->getStorageClass() == VarDecl::Static) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00003657 // C99 6.9.2p3: If the declaration of an identifier for an object is
Douglas Gregorec8b59f2009-07-20 18:46:59 +00003658 // a tentative definition and has internal linkage (C99 6.2.2p3), the
Steve Naroff9a75f8a2008-01-18 20:40:52 +00003659 // declared type shall not be an incomplete type.
Douglas Gregorec8b59f2009-07-20 18:46:59 +00003660 // NOTE: code such as the following
3661 // static struct s;
3662 // struct s { int a; };
3663 // is accepted by gcc. Hence here we issue a warning instead of
3664 // an error and we do not invalidate the static declaration.
3665 // NOTE: to avoid multiple warnings, only check the first declaration.
3666 if (IDecl->getPreviousDeclaration() == 0)
3667 RequireCompleteType(IDecl->getLocation(), T,
3668 diag::ext_typecheck_decl_incomplete_type);
Douglas Gregora03aca82009-03-10 21:58:27 +00003669 }
Steve Naroffbb204692007-09-12 14:07:44 +00003670 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003671 }
Chris Lattner682bf922009-03-29 16:50:03 +00003672 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
Jay Foadbeaaccd2009-05-21 09:52:38 +00003673 Decls.data(), Decls.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00003674}
Steve Naroffe1223f72007-08-28 03:03:08 +00003675
Chris Lattner682bf922009-03-29 16:50:03 +00003676
Chris Lattner04421082008-04-08 04:40:51 +00003677/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
3678/// to introduce parameters into function prototype scope.
Mike Stump1eb44332009-09-09 15:08:12 +00003679Sema::DeclPtrTy
Chris Lattner04421082008-04-08 04:40:51 +00003680Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00003681 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00003682
Chris Lattner04421082008-04-08 04:40:51 +00003683 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00003684 VarDecl::StorageClass StorageClass = VarDecl::None;
3685 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3686 StorageClass = VarDecl::Register;
3687 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00003688 Diag(DS.getStorageClassSpecLoc(),
3689 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00003690 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00003691 }
Eli Friedman63054b32009-04-19 20:27:55 +00003692
3693 if (D.getDeclSpec().isThreadSpecified())
3694 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3695
Eli Friedman85a53192009-04-07 19:37:57 +00003696 DiagnoseFunctionSpecifiers(D);
3697
Douglas Gregor6d6eb572008-05-07 04:49:29 +00003698 // Check that there are no default arguments inside the type of this
3699 // parameter (C++ only).
3700 if (getLangOptions().CPlusPlus)
3701 CheckExtraCXXDefaultArguments(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003702
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003703 DeclaratorInfo *DInfo = 0;
Douglas Gregor402abb52009-05-28 23:31:59 +00003704 TagDecl *OwnedDecl = 0;
Sebastian Redl8ce35b02009-10-25 21:45:37 +00003705 QualType parmDeclType = GetTypeForDeclarator(D, S, &DInfo, &OwnedDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00003706
Douglas Gregor402abb52009-05-28 23:31:59 +00003707 if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
3708 // C++ [dcl.fct]p6:
3709 // Types shall not be defined in return or parameter types.
3710 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
3711 << Context.getTypeDeclType(OwnedDecl);
3712 }
3713
Reid Spencer5f016e22007-07-11 17:01:13 +00003714 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
3715 // Can this happen for params? We already checked that they don't conflict
3716 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00003717 IdentifierInfo *II = D.getIdentifier();
Chris Lattnercf79b012009-01-21 02:38:50 +00003718 if (II) {
John McCallf36e02d2009-10-09 21:13:30 +00003719 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Chris Lattnercf79b012009-01-21 02:38:50 +00003720 if (PrevDecl->isTemplateParameter()) {
3721 // Maybe we will complain about the shadowed template parameter.
3722 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
3723 // Just pretend that we didn't see the previous declaration.
3724 PrevDecl = 0;
Chris Lattnerb28317a2009-03-28 19:18:32 +00003725 } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
Chris Lattnercf79b012009-01-21 02:38:50 +00003726 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00003727
Chris Lattnercf79b012009-01-21 02:38:50 +00003728 // Recover by removing the name
3729 II = 0;
3730 D.SetIdentifier(0, D.getIdentifierLoc());
3731 }
Chris Lattner04421082008-04-08 04:40:51 +00003732 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003733 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00003734
Anders Carlsson11f21a02009-03-23 19:10:31 +00003735 // Parameters can not be abstract class types.
Anders Carlsson8211eff2009-03-24 01:19:16 +00003736 // For record types, this is done by the AbstractClassUsageDiagnoser once
Mike Stump1eb44332009-09-09 15:08:12 +00003737 // the class has been completely parsed.
3738 if (!CurContext->isRecord() &&
3739 RequireNonAbstractType(D.getIdentifierLoc(), parmDeclType,
Anders Carlsson11f21a02009-03-23 19:10:31 +00003740 diag::err_abstract_type_in_decl,
Anders Carlsson8211eff2009-03-24 01:19:16 +00003741 AbstractParamType))
Anders Carlsson11f21a02009-03-23 19:10:31 +00003742 D.setInvalidType(true);
Douglas Gregor44b43212008-12-11 16:49:14 +00003743
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003744 QualType T = adjustParameterType(parmDeclType);
Mike Stump1eb44332009-09-09 15:08:12 +00003745
John McCall58e46772009-10-23 21:48:59 +00003746 ParmVarDecl *New
3747 = ParmVarDecl::Create(Context, CurContext, D.getIdentifierLoc(), II,
3748 T, DInfo, StorageClass, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003749
Chris Lattnereaaebc72009-04-25 08:06:05 +00003750 if (D.isInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00003751 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003752
Steve Naroffccef3712009-02-20 22:59:16 +00003753 // Parameter declarators cannot be interface types. All ObjC objects are
3754 // passed by reference.
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003755 if (T->isObjCInterfaceType()) {
Chris Lattner2dd979f2009-04-11 19:08:56 +00003756 Diag(D.getIdentifierLoc(),
3757 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
Steve Naroffccef3712009-02-20 22:59:16 +00003758 New->setInvalidDecl();
3759 }
Mike Stump1eb44332009-09-09 15:08:12 +00003760
Chris Lattnerf97e8fa2009-04-11 19:34:56 +00003761 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3762 if (D.getCXXScopeSpec().isSet()) {
3763 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
3764 << D.getCXXScopeSpec().getRange();
3765 New->setInvalidDecl();
3766 }
Tanya Lattner27a84d02009-09-30 20:47:43 +00003767
3768 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
3769 // duration shall not be qualified by an address-space qualifier."
3770 // Since all parameters have automatic store duration, they can not have
3771 // an address space.
3772 if (T.getAddressSpace() != 0) {
3773 Diag(D.getIdentifierLoc(),
3774 diag::err_arg_with_address_space);
3775 New->setInvalidDecl();
3776 }
3777
3778
Douglas Gregor44b43212008-12-11 16:49:14 +00003779 // Add the parameter declaration into this scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003780 S->AddDecl(DeclPtrTy::make(New));
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003781 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00003782 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00003783
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003784 ProcessDeclAttributes(S, New, D);
Mike Stumpea000bf2009-04-30 00:19:40 +00003785
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003786 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00003787 Diag(New->getLocation(), diag::err_block_on_nonlocal);
3788 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003789 return DeclPtrTy::make(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00003790}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00003791
Douglas Gregora3a83512009-04-01 23:51:29 +00003792void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
3793 SourceLocation LocAfterDecls) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003794 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3795 "Not a function declarator!");
3796 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00003797
Reid Spencer5f016e22007-07-11 17:01:13 +00003798 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
3799 // for a K&R function.
3800 if (!FTI.hasPrototype) {
Douglas Gregor26103482009-04-02 03:14:12 +00003801 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
3802 --i;
Chris Lattner04421082008-04-08 04:40:51 +00003803 if (FTI.ArgInfo[i].Param == 0) {
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00003804 llvm::SmallString<256> Code;
3805 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003806 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00003807 << ";\n";
Chris Lattner3c73c412008-11-19 08:23:25 +00003808 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregora3a83512009-04-01 23:51:29 +00003809 << FTI.ArgInfo[i].Ident
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00003810 << CodeModificationHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregora3a83512009-04-01 23:51:29 +00003811
Reid Spencer5f016e22007-07-11 17:01:13 +00003812 // Implicitly declare the argument as type 'int' for lack of a better
3813 // type.
Chris Lattner04421082008-04-08 04:40:51 +00003814 DeclSpec DS;
3815 const char* PrevSpec; // unused
John McCallfec54012009-08-03 20:12:06 +00003816 unsigned DiagID; // unused
Mike Stump1eb44332009-09-09 15:08:12 +00003817 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCallfec54012009-08-03 20:12:06 +00003818 PrevSpec, DiagID);
Chris Lattner04421082008-04-08 04:40:51 +00003819 Declarator ParamD(DS, Declarator::KNRTypeListContext);
3820 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00003821 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00003822 }
3823 }
Mike Stump1eb44332009-09-09 15:08:12 +00003824 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00003825}
3826
Chris Lattnerb28317a2009-03-28 19:18:32 +00003827Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
3828 Declarator &D) {
Douglas Gregorbe109b32009-01-23 16:23:13 +00003829 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3830 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3831 "Not a function declarator!");
3832 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3833
3834 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00003835 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00003836 }
Mike Stump1eb44332009-09-09 15:08:12 +00003837
Douglas Gregor584049d2008-12-15 23:53:10 +00003838 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00003839
Mike Stump1eb44332009-09-09 15:08:12 +00003840 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregore542c862009-06-23 23:11:28 +00003841 MultiTemplateParamsArg(*this),
3842 /*IsFunctionDefinition=*/true);
Chris Lattner682bf922009-03-29 16:50:03 +00003843 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003844}
3845
Chris Lattnerb28317a2009-03-28 19:18:32 +00003846Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00003847 // Clear the last template instantiation error context.
3848 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
3849
Douglas Gregor52591bf2009-06-24 00:54:41 +00003850 if (!D)
3851 return D;
Douglas Gregord83d0402009-08-22 00:34:47 +00003852 FunctionDecl *FD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003853
3854 if (FunctionTemplateDecl *FunTmpl
Douglas Gregord83d0402009-08-22 00:34:47 +00003855 = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
3856 FD = FunTmpl->getTemplatedDecl();
3857 else
3858 FD = cast<FunctionDecl>(D.getAs<Decl>());
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00003859
Chris Lattner38c5ebd2009-04-19 05:21:20 +00003860 CurFunctionNeedsScopeChecking = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003861
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00003862 // See if this is a redefinition.
3863 const FunctionDecl *Definition;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003864 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00003865 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003866 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00003867 }
3868
Douglas Gregorcda9c672009-02-16 17:45:42 +00003869 // Builtin functions cannot be defined.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003870 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor655753a2009-02-17 16:03:01 +00003871 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00003872 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor655753a2009-02-17 16:03:01 +00003873 FD->setInvalidDecl();
3874 }
Douglas Gregorcda9c672009-02-16 17:45:42 +00003875 }
3876
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00003877 // The return type of a function definition must be complete
Douglas Gregore7450f52009-03-24 19:52:54 +00003878 // (C99 6.9.1p3, C++ [dcl.fct]p6).
3879 QualType ResultType = FD->getResultType();
3880 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner65e6a092009-04-29 05:12:23 +00003881 !FD->isInvalidDecl() &&
Douglas Gregore7450f52009-03-24 19:52:54 +00003882 RequireCompleteType(FD->getLocation(), ResultType,
3883 diag::err_func_def_incomplete_result))
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00003884 FD->setInvalidDecl();
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00003885
Douglas Gregor8499f3f2009-03-31 16:35:03 +00003886 // GNU warning -Wmissing-prototypes:
3887 // Warn if a global function is defined without a previous
3888 // prototype declaration. This warning is issued even if the
3889 // definition itself provides a prototype. The aim is to detect
3890 // global functions that fail to be declared in header files.
Douglas Gregor2c2d9dc2009-04-08 15:21:36 +00003891 if (!FD->isInvalidDecl() && FD->isGlobal() && !isa<CXXMethodDecl>(FD) &&
Douglas Gregor48a83b52009-09-12 00:17:51 +00003892 !FD->isMain()) {
Douglas Gregor8499f3f2009-03-31 16:35:03 +00003893 bool MissingPrototype = true;
3894 for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
3895 Prev; Prev = Prev->getPreviousDeclaration()) {
3896 // Ignore any declarations that occur in function or method
3897 // scope, because they aren't visible from the header.
3898 if (Prev->getDeclContext()->isFunctionOrMethod())
3899 continue;
3900
3901 MissingPrototype = !Prev->getType()->isFunctionProtoType();
3902 break;
3903 }
3904
3905 if (MissingPrototype)
3906 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
3907 }
3908
Douglas Gregore2c31ff2009-05-15 17:59:04 +00003909 if (FnBodyScope)
3910 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00003911
Chris Lattner04421082008-04-08 04:40:51 +00003912 // Check the validity of our function parameters
3913 CheckParmsForFunctionDef(FD);
3914
3915 // Introduce our parameters into the function scope
3916 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
3917 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00003918 Param->setOwningFunction(FD);
3919
Chris Lattner04421082008-04-08 04:40:51 +00003920 // If this has an identifier, add it to the scope stack.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00003921 if (Param->getIdentifier() && FnBodyScope)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003922 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00003923 }
Chris Lattner04421082008-04-08 04:40:51 +00003924
Anton Korobeynikov2f402702008-12-26 00:52:02 +00003925 // Checking attributes of current function definition
3926 // dllimport attribute.
Mike Stump1eb44332009-09-09 15:08:12 +00003927 if (FD->getAttr<DLLImportAttr>() &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003928 (!FD->getAttr<DLLExportAttr>())) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00003929 // dllimport attribute cannot be applied to definition.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003930 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00003931 Diag(FD->getLocation(),
3932 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
3933 << "dllimport";
3934 FD->setInvalidDecl();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003935 return DeclPtrTy::make(FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00003936 } else {
3937 // If a symbol previously declared dllimport is later defined, the
3938 // attribute is ignored in subsequent references, and a warning is
3939 // emitted.
3940 Diag(FD->getLocation(),
3941 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
3942 << FD->getNameAsCString() << "dllimport";
3943 }
3944 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003945 return DeclPtrTy::make(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00003946}
3947
Chris Lattnerb28317a2009-03-28 19:18:32 +00003948Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
Douglas Gregore2c31ff2009-05-15 17:59:04 +00003949 return ActOnFinishFunctionBody(D, move(BodyArg), false);
3950}
3951
3952Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
3953 bool IsInstantiation) {
Chris Lattnerb28317a2009-03-28 19:18:32 +00003954 Decl *dcl = D.getAs<Decl>();
Sebastian Redld3a413d2009-04-26 20:35:05 +00003955 Stmt *Body = BodyArg.takeAs<Stmt>();
Douglas Gregord83d0402009-08-22 00:34:47 +00003956
3957 FunctionDecl *FD = 0;
3958 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
3959 if (FunTmpl)
3960 FD = FunTmpl->getTemplatedDecl();
3961 else
3962 FD = dyn_cast_or_null<FunctionDecl>(dcl);
3963
3964 if (FD) {
Chris Lattnera5251fc2009-04-18 09:36:27 +00003965 FD->setBody(Body);
Douglas Gregor48a83b52009-09-12 00:17:51 +00003966 if (FD->isMain())
Mike Stump5f28a1e2009-07-24 02:49:01 +00003967 // C and C++ allow for main to automagically return 0.
John McCall0cfeb632009-07-28 01:00:58 +00003968 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
3969 FD->setHasImplicitReturnZero(true);
3970 else
Mike Stumpb1682c52009-07-22 23:56:57 +00003971 CheckFallThroughForFunctionDef(FD, Body);
Mike Stump1eb44332009-09-09 15:08:12 +00003972
Douglas Gregore0762c92009-06-19 23:52:42 +00003973 if (!FD->isInvalidDecl())
3974 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Mike Stump1eb44332009-09-09 15:08:12 +00003975
Douglas Gregore0762c92009-06-19 23:52:42 +00003976 // C++ [basic.def.odr]p2:
3977 // [...] A virtual member function is used if it is not pure. [...]
3978 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
3979 if (Method->isVirtual() && !Method->isPure())
3980 MarkDeclarationReferenced(Method->getLocation(), Method);
Mike Stump1eb44332009-09-09 15:08:12 +00003981
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00003982 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00003983 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattnerffed1632009-02-16 19:27:54 +00003984 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattnera5251fc2009-04-18 09:36:27 +00003985 MD->setBody(Body);
Mike Stump5f28a1e2009-07-24 02:49:01 +00003986 CheckFallThroughForFunctionDef(MD, Body);
Argyrios Kyrtzidisa2e85ad2009-07-18 00:33:33 +00003987 MD->setEndLoc(Body->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003988
Douglas Gregore0762c92009-06-19 23:52:42 +00003989 if (!MD->isInvalidDecl())
3990 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Ted Kremenek8189cde2009-02-07 01:47:29 +00003991 } else {
3992 Body->Destroy(Context);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003993 return DeclPtrTy();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003994 }
Douglas Gregore2c31ff2009-05-15 17:59:04 +00003995 if (!IsInstantiation)
3996 PopDeclContext();
3997
Reid Spencer5f016e22007-07-11 17:01:13 +00003998 // Verify and clean out per-function state.
Eli Friedman8f17b662009-02-28 05:41:13 +00003999
Chris Lattner4f2aac32009-04-18 20:05:34 +00004000 assert(&getLabelMap() == &FunctionLabelMap && "Didn't pop block right?");
Mike Stump1eb44332009-09-09 15:08:12 +00004001
Reid Spencer5f016e22007-07-11 17:01:13 +00004002 // Check goto/label use.
Steve Naroffcaaacec2009-03-13 15:38:40 +00004003 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
Chris Lattnerea29a3a2009-04-18 20:01:55 +00004004 I = FunctionLabelMap.begin(), E = FunctionLabelMap.end(); I != E; ++I) {
Chris Lattnere32f74c2009-04-18 19:30:02 +00004005 LabelStmt *L = I->second;
Mike Stump1eb44332009-09-09 15:08:12 +00004006
Reid Spencer5f016e22007-07-11 17:01:13 +00004007 // Verify that we have no forward references left. If so, there was a goto
4008 // or address of a label taken, but no definition of it. Label fwd
4009 // definitions are indicated with a null substmt.
Chris Lattnere32f74c2009-04-18 19:30:02 +00004010 if (L->getSubStmt() != 0)
4011 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00004012
Chris Lattnere32f74c2009-04-18 19:30:02 +00004013 // Emit error.
4014 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004015
Chris Lattnere32f74c2009-04-18 19:30:02 +00004016 // At this point, we have gotos that use the bogus label. Stitch it into
4017 // the function body so that they aren't leaked and that the AST is well
4018 // formed.
4019 if (Body == 0) {
4020 // The whole function wasn't parsed correctly, just delete this.
4021 L->Destroy(Context);
4022 continue;
Reid Spencer5f016e22007-07-11 17:01:13 +00004023 }
Mike Stump1eb44332009-09-09 15:08:12 +00004024
Chris Lattnere32f74c2009-04-18 19:30:02 +00004025 // Otherwise, the body is valid: we want to stitch the label decl into the
4026 // function somewhere so that it is properly owned and so that the goto
4027 // has a valid target. Do this by creating a new compound stmt with the
4028 // label in it.
Sebastian Redld3a413d2009-04-26 20:35:05 +00004029
Chris Lattnere32f74c2009-04-18 19:30:02 +00004030 // Give the label a sub-statement.
4031 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
Sebastian Redld3a413d2009-04-26 20:35:05 +00004032
4033 CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
4034 cast<CXXTryStmt>(Body)->getTryBlock() :
4035 cast<CompoundStmt>(Body);
4036 std::vector<Stmt*> Elements(Compound->body_begin(), Compound->body_end());
Chris Lattnere32f74c2009-04-18 19:30:02 +00004037 Elements.push_back(L);
Sebastian Redld3a413d2009-04-26 20:35:05 +00004038 Compound->setStmts(Context, &Elements[0], Elements.size());
Reid Spencer5f016e22007-07-11 17:01:13 +00004039 }
Chris Lattnerea29a3a2009-04-18 20:01:55 +00004040 FunctionLabelMap.clear();
Eli Friedman8f17b662009-02-28 05:41:13 +00004041
4042 if (!Body) return D;
4043
Chris Lattnerb5659372009-04-18 21:00:42 +00004044 // Verify that that gotos and switch cases don't jump into scopes illegally.
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004045 if (CurFunctionNeedsScopeChecking)
4046 DiagnoseInvalidJumps(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00004047
4048 // C++ constructors that have function-try-blocks can't have return
4049 // statements in the handlers of that block. (C++ [except.handle]p14)
Fariborz Jahanian393612e2009-07-21 22:36:06 +00004050 // Verify this.
Douglas Gregord83d0402009-08-22 00:34:47 +00004051 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
Sebastian Redl13e88542009-04-27 21:33:24 +00004052 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00004053
Fariborz Jahanian393612e2009-07-21 22:36:06 +00004054 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
Anders Carlsson9f853df2009-11-17 04:44:12 +00004055 MarkBaseAndMemberDestructorsReferenced(Destructor);
Anders Carlssonf8a9a792009-11-13 19:21:49 +00004056
Douglas Gregord5b57282009-11-15 07:07:58 +00004057 // If any errors have occurred, clear out any temporaries that may have
4058 // been leftover. This ensures that these temporaries won't be picked up for
4059 // deletion in some later function.
4060 if (PP.getDiagnostics().hasErrorOccurred())
4061 ExprTemporaries.clear();
4062
Anders Carlssonf8a9a792009-11-13 19:21:49 +00004063 assert(ExprTemporaries.empty() && "Leftover temporaries in function");
Steve Naroffd6d054d2007-11-11 23:20:51 +00004064 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00004065}
4066
Reid Spencer5f016e22007-07-11 17:01:13 +00004067/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4068/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump1eb44332009-09-09 15:08:12 +00004069NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004070 IdentifierInfo &II, Scope *S) {
Douglas Gregor63935192009-03-02 00:19:53 +00004071 // Before we produce a declaration for an implicitly defined
4072 // function, see whether there was a locally-scoped declaration of
4073 // this name as a function or variable. If so, use that
4074 // (non-visible) declaration, and complain about it.
4075 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4076 = LocallyScopedExternalDecls.find(&II);
4077 if (Pos != LocallyScopedExternalDecls.end()) {
4078 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
4079 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
4080 return Pos->second;
4081 }
4082
Chris Lattner37d10842008-05-05 21:18:06 +00004083 // Extension in C99. Legal in C90, but warn about it.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004084 if (II.getName().startswith("__builtin_"))
Douglas Gregor9a8c9a22009-09-28 21:14:19 +00004085 Diag(Loc, diag::warn_builtin_unknown) << &II;
4086 else if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00004087 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00004088 else
Chris Lattner3c73c412008-11-19 08:23:25 +00004089 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Mike Stump1eb44332009-09-09 15:08:12 +00004090
Reid Spencer5f016e22007-07-11 17:01:13 +00004091 // Set a Declarator for the implicit definition: int foo();
4092 const char *Dummy;
4093 DeclSpec DS;
John McCallfec54012009-08-03 20:12:06 +00004094 unsigned DiagID;
4095 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +00004096 Error = Error; // Silence warning.
4097 assert(!Error && "Error setting up implicit decl!");
4098 Declarator D(DS, Declarator::BlockContext);
Sebastian Redl7dc81342009-04-29 17:30:04 +00004099 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
Sebastian Redl3cc97262009-05-31 11:47:27 +00004100 0, 0, false, SourceLocation(),
Argyrios Kyrtzidis82bf0102009-08-19 23:14:54 +00004101 false, 0,0,0, Loc, Loc, D),
Sebastian Redlab197ba2009-02-09 18:23:29 +00004102 SourceLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00004103 D.SetIdentifier(&II, Loc);
Sebastian Redlab197ba2009-02-09 18:23:29 +00004104
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00004105 // Insert this function into translation-unit scope.
4106
4107 DeclContext *PrevDC = CurContext;
4108 CurContext = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004109
4110 FunctionDecl *FD =
Douglas Gregor2e01cda2009-06-23 21:43:56 +00004111 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
Steve Naroffe2ef8152008-04-04 14:32:09 +00004112 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00004113
4114 CurContext = PrevDC;
4115
Douglas Gregor3c385e52009-02-14 18:57:46 +00004116 AddKnownFunctionAttributes(FD);
4117
Steve Naroffe2ef8152008-04-04 14:32:09 +00004118 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00004119}
4120
Douglas Gregor3c385e52009-02-14 18:57:46 +00004121/// \brief Adds any function attributes that we know a priori based on
4122/// the declaration of this function.
4123///
4124/// These attributes can apply both to implicitly-declared builtins
4125/// (like __builtin___printf_chk) or to library-declared functions
4126/// like NSLog or printf.
4127void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
4128 if (FD->isInvalidDecl())
4129 return;
4130
4131 // If this is a built-in function, map its builtin attributes to
4132 // actual attributes.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00004133 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00004134 // Handle printf-formatting attributes.
4135 unsigned FormatIdx;
4136 bool HasVAListArg;
4137 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004138 if (!FD->getAttr<FormatAttr>())
4139 FD->addAttr(::new (Context) FormatAttr("printf", FormatIdx + 1,
Eli Friedmand7dad722009-06-10 04:01:38 +00004140 HasVAListArg ? 0 : FormatIdx + 2));
Douglas Gregor3c385e52009-02-14 18:57:46 +00004141 }
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00004142
4143 // Mark const if we don't care about errno and that is the only
4144 // thing preventing the function from being const. This allows
4145 // IRgen to use LLVM intrinsics for such functions.
4146 if (!getLangOptions().MathErrno &&
4147 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004148 if (!FD->getAttr<ConstAttr>())
4149 FD->addAttr(::new (Context) ConstAttr());
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00004150 }
Mike Stump0feecbb2009-07-27 19:14:18 +00004151
4152 if (Context.BuiltinInfo.isNoReturn(BuiltinID))
4153 FD->addAttr(::new (Context) NoReturnAttr());
Douglas Gregor3c385e52009-02-14 18:57:46 +00004154 }
4155
4156 IdentifierInfo *Name = FD->getIdentifier();
4157 if (!Name)
4158 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004159 if ((!getLangOptions().CPlusPlus &&
Douglas Gregor3c385e52009-02-14 18:57:46 +00004160 FD->getDeclContext()->isTranslationUnit()) ||
4161 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00004162 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregor3c385e52009-02-14 18:57:46 +00004163 LinkageSpecDecl::lang_c)) {
4164 // Okay: this could be a libc/libm/Objective-C function we know
4165 // about.
4166 } else
4167 return;
4168
Douglas Gregor21e072b2009-04-22 20:56:09 +00004169 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
Mike Stump523a8fd2009-07-28 00:07:08 +00004170 // FIXME: NSLog and NSLogv should be target specific
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004171 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00004172 // FIXME: We known better than our headers.
4173 const_cast<FormatAttr *>(Format)->setType("printf");
Mike Stump1eb44332009-09-09 15:08:12 +00004174 } else
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004175 FD->addAttr(::new (Context) FormatAttr("printf", 1,
Eli Friedmand7dad722009-06-10 04:01:38 +00004176 Name->isStr("NSLogv") ? 0 : 2));
Douglas Gregor21e072b2009-04-22 20:56:09 +00004177 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump523a8fd2009-07-28 00:07:08 +00004178 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump1eb44332009-09-09 15:08:12 +00004179 // target-specific builtins, perhaps?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004180 if (!FD->getAttr<FormatAttr>())
4181 FD->addAttr(::new (Context) FormatAttr("printf", 2,
Eli Friedmand7dad722009-06-10 04:01:38 +00004182 Name->isStr("vasprintf") ? 0 : 3));
Mike Stump782fa302009-07-28 02:25:19 +00004183 }
Douglas Gregor3c385e52009-02-14 18:57:46 +00004184}
Reid Spencer5f016e22007-07-11 17:01:13 +00004185
John McCallba6a9bd2009-10-24 08:00:42 +00004186TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4187 DeclaratorInfo *DInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004188 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00004189 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump1eb44332009-09-09 15:08:12 +00004190
John McCallba6a9bd2009-10-24 08:00:42 +00004191 if (!DInfo) {
4192 assert(D.isInvalidType() && "no declarator info for valid type");
4193 DInfo = Context.getTrivialDeclaratorInfo(T);
4194 }
4195
Reid Spencer5f016e22007-07-11 17:01:13 +00004196 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00004197 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
4198 D.getIdentifierLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +00004199 D.getIdentifier(),
John McCallba6a9bd2009-10-24 08:00:42 +00004200 DInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004201
John McCall2191b202009-09-05 06:31:47 +00004202 if (const TagType *TT = T->getAs<TagType>()) {
Anders Carlsson4843e582009-03-10 17:07:44 +00004203 TagDecl *TD = TT->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004204
Anders Carlsson4843e582009-03-10 17:07:44 +00004205 // If the TagDecl that the TypedefDecl points to is an anonymous decl
4206 // keep track of the TypedefDecl.
4207 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
4208 TD->setTypedefForAnonDecl(NewTD);
4209 }
4210
Chris Lattnereaaebc72009-04-25 08:06:05 +00004211 if (D.isInvalidType())
Steve Naroff5912a352007-08-28 20:14:24 +00004212 NewTD->setInvalidDecl();
4213 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00004214}
4215
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004216
4217/// \brief Determine whether a tag with a given kind is acceptable
4218/// as a redeclaration of the given tag declaration.
4219///
4220/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00004221bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004222 TagDecl::TagKind NewTag,
4223 SourceLocation NewTagLoc,
4224 const IdentifierInfo &Name) {
4225 // C++ [dcl.type.elab]p3:
4226 // The class-key or enum keyword present in the
4227 // elaborated-type-specifier shall agree in kind with the
4228 // declaration to which the name in theelaborated-type-specifier
4229 // refers. This rule also applies to the form of
4230 // elaborated-type-specifier that declares a class-name or
4231 // friend class since it can be construed as referring to the
4232 // definition of the class. Thus, in any
4233 // elaborated-type-specifier, the enum keyword shall be used to
4234 // refer to an enumeration (7.2), the union class-keyshall be
4235 // used to refer to a union (clause 9), and either the class or
4236 // struct class-key shall be used to refer to a class (clause 9)
4237 // declared using the class or struct class-key.
4238 TagDecl::TagKind OldTag = Previous->getTagKind();
4239 if (OldTag == NewTag)
4240 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004241
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004242 if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) &&
4243 (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) {
4244 // Warn about the struct/class tag mismatch.
4245 bool isTemplate = false;
4246 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
4247 isTemplate = Record->getDescribedClassTemplate();
4248
4249 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
4250 << (NewTag == TagDecl::TK_class)
4251 << isTemplate << &Name
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004252 << CodeModificationHint::CreateReplacement(SourceRange(NewTagLoc),
4253 OldTag == TagDecl::TK_class? "class" : "struct");
4254 Diag(Previous->getLocation(), diag::note_previous_use);
4255 return true;
4256 }
4257 return false;
4258}
4259
Steve Naroff08d92e42007-09-15 18:49:24 +00004260/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00004261/// former case, Name will be non-null. In the later case, Name will be null.
John McCall0f434ec2009-07-31 02:45:11 +00004262/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +00004263/// reference/declaration/definition of a tag.
John McCall0f434ec2009-07-31 02:45:11 +00004264Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004265 SourceLocation KWLoc, const CXXScopeSpec &SS,
4266 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregor402abb52009-05-28 23:31:59 +00004267 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004268 MultiTemplateParamsArg TemplateParameterLists,
John McCallc4e70192009-09-11 04:59:25 +00004269 bool &OwnedDecl, bool &IsDependent) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004270 // If this is not a definition, it must have a name.
John McCall0f434ec2009-07-31 02:45:11 +00004271 assert((Name != 0 || TUK == TUK_Definition) &&
Reid Spencer5f016e22007-07-11 17:01:13 +00004272 "Nameless record must be a definition!");
Douglas Gregoraaba5e32009-02-04 19:02:06 +00004273
Douglas Gregor402abb52009-05-28 23:31:59 +00004274 OwnedDecl = false;
John McCallf1bbbb42009-09-04 01:14:41 +00004275 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00004276
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004277 // FIXME: Check explicit specializations more carefully.
4278 bool isExplicitSpecialization = false;
John McCall0f434ec2009-07-31 02:45:11 +00004279 if (TUK != TUK_Reference) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004280 if (TemplateParameterList *TemplateParams
4281 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
4282 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004283 TemplateParameterLists.size(),
4284 isExplicitSpecialization)) {
Douglas Gregord85bea22009-09-26 06:47:28 +00004285 if (TemplateParams->size() > 0) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004286 // This is a declaration or definition of a class template (which may
4287 // be a member of another template).
4288 OwnedDecl = false;
John McCall0f434ec2009-07-31 02:45:11 +00004289 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004290 SS, Name, NameLoc, Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00004291 TemplateParams,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004292 AS);
Douglas Gregor05396e22009-08-25 17:23:04 +00004293 TemplateParameterLists.release();
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004294 return Result.get();
4295 } else {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004296 // The "template<>" header is extraneous.
4297 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
4298 << ElaboratedType::getNameForTagKind(Kind) << Name;
4299 isExplicitSpecialization = true;
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004300 }
Mike Stump1eb44332009-09-09 15:08:12 +00004301 }
Douglas Gregorf6b11852009-10-08 15:14:33 +00004302
4303 TemplateParameterLists.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004304 }
4305
Douglas Gregor4920f1f2009-01-12 22:49:06 +00004306 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00004307 DeclContext *DC = CurContext;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00004308 NamedDecl *PrevDecl = 0;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004309 bool isStdBadAlloc = false;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00004310 bool Invalid = false;
4311
John McCalla24dc2e2009-11-17 02:14:36 +00004312 LookupResult::RedeclarationKind Redecl =
4313 (LookupResult::RedeclarationKind) (TUK != TUK_Reference);
John McCall6e247262009-10-10 05:48:19 +00004314
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00004315 if (Name && SS.isNotEmpty()) {
4316 // We have a nested-name tag ('struct foo::bar').
4317
4318 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00004319 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00004320 Name = 0;
4321 goto CreateNewDecl;
4322 }
4323
John McCallc4e70192009-09-11 04:59:25 +00004324 // If this is a friend or a reference to a class in a dependent
4325 // context, don't try to make a decl for it.
4326 if (TUK == TUK_Friend || TUK == TUK_Reference) {
4327 DC = computeDeclContext(SS, false);
4328 if (!DC) {
4329 IsDependent = true;
4330 return DeclPtrTy();
4331 }
4332 }
4333
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004334 if (RequireCompleteDeclContext(SS))
4335 return DeclPtrTy::make((Decl *)0);
4336
Douglas Gregorf59a56e2009-07-21 23:53:31 +00004337 DC = computeDeclContext(SS, true);
Douglas Gregor1931b442009-02-03 00:34:39 +00004338 SearchDC = DC;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00004339 // Look-up name inside 'foo::'.
John McCalla24dc2e2009-11-17 02:14:36 +00004340 LookupResult R(*this, Name, NameLoc, LookupTagName, Redecl);
4341 LookupQualifiedName(R, DC);
John McCall6e247262009-10-10 05:48:19 +00004342
John McCalla24dc2e2009-11-17 02:14:36 +00004343 if (R.isAmbiguous())
John McCall6e247262009-10-10 05:48:19 +00004344 return DeclPtrTy();
John McCall6e247262009-10-10 05:48:19 +00004345
John McCalla24dc2e2009-11-17 02:14:36 +00004346 if (R.getResultKind() == LookupResult::Found)
John McCall6e247262009-10-10 05:48:19 +00004347 PrevDecl = dyn_cast<TagDecl>(R.getFoundDecl());
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00004348
4349 // A tag 'foo::bar' must already exist.
John McCall6e247262009-10-10 05:48:19 +00004350 if (!PrevDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +00004351 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00004352 Name = 0;
Douglas Gregord0c87372009-05-27 17:30:49 +00004353 Invalid = true;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00004354 goto CreateNewDecl;
4355 }
Chris Lattnercf79b012009-01-21 02:38:50 +00004356 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00004357 // If this is a named struct, check to see if there was a previous forward
4358 // declaration or definition.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004359 // FIXME: We're looking into outer scopes here, even when we
4360 // shouldn't be. Doing so can result in ambiguities that we
4361 // shouldn't be diagnosing.
John McCalla24dc2e2009-11-17 02:14:36 +00004362 LookupResult R(*this, Name, NameLoc, LookupTagName, Redecl);
4363 LookupName(R, S);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004364 if (R.isAmbiguous()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004365 // FIXME: This is not best way to recover from case like:
4366 //
4367 // struct S s;
4368 //
Douglas Gregor31a19b62009-04-01 21:51:26 +00004369 // causes needless "incomplete type" error later.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004370 Name = 0;
4371 PrevDecl = 0;
4372 Invalid = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004373 } else
John McCallf36e02d2009-10-09 21:13:30 +00004374 PrevDecl = R.getAsSingleDecl(Context);
Douglas Gregor72de6672009-01-08 20:45:30 +00004375
John McCall0f434ec2009-07-31 02:45:11 +00004376 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor72de6672009-01-08 20:45:30 +00004377 // FIXME: This makes sure that we ignore the contexts associated
4378 // with C structs, unions, and enums when looking for a matching
4379 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +00004380 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +00004381 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
4382 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +00004383 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00004384 }
4385
Douglas Gregorf57172b2008-12-08 18:40:42 +00004386 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00004387 // Maybe we will complain about the shadowed template parameter.
4388 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
4389 // Just pretend that we didn't see the previous declaration.
4390 PrevDecl = 0;
4391 }
4392
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004393 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
4394 DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) {
4395 // This is a declaration of or a reference to "std::bad_alloc".
4396 isStdBadAlloc = true;
4397
4398 if (!PrevDecl && StdBadAlloc) {
4399 // std::bad_alloc has been implicitly declared (but made invisible to
4400 // name lookup). Fill in this implicit declaration as the previous
4401 // declaration, so that the declarations get chained appropriately.
4402 PrevDecl = StdBadAlloc;
4403 }
4404 }
4405
Chris Lattner22bd9052009-02-16 22:07:16 +00004406 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004407 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00004408 // If this is a use of a previous tag, or if the tag is already declared
4409 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004410 // rementions the tag), reuse the decl.
John McCall67d1a672009-08-06 02:15:43 +00004411 if (TUK == TUK_Reference || TUK == TUK_Friend ||
4412 isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00004413 // Make sure that this wasn't declared as an enum and now used as a
4414 // struct or something similar.
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004415 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004416 bool SafeToContinue
Douglas Gregora3a83512009-04-01 23:51:29 +00004417 = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
4418 Kind != TagDecl::TK_enum);
4419 if (SafeToContinue)
Mike Stump1eb44332009-09-09 15:08:12 +00004420 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00004421 << Name
4422 << CodeModificationHint::CreateReplacement(SourceRange(KWLoc),
4423 PrevTagDecl->getKindName());
4424 else
4425 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00004426 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +00004427
Mike Stump1eb44332009-09-09 15:08:12 +00004428 if (SafeToContinue)
Douglas Gregora3a83512009-04-01 23:51:29 +00004429 Kind = PrevTagDecl->getTagKind();
4430 else {
4431 // Recover by making this an anonymous redefinition.
4432 Name = 0;
4433 PrevDecl = 0;
4434 Invalid = true;
4435 }
4436 }
4437
4438 if (!Invalid) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004439 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00004440
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004441 // FIXME: In the future, return a variant or some other clue
4442 // for the consumer of this Decl to know it doesn't own it.
4443 // For our current ASTs this shouldn't be a problem, but will
4444 // need to be changed with DeclGroups.
John McCalle3af0232009-10-07 23:34:25 +00004445 if (TUK == TUK_Reference || TUK == TUK_Friend)
Chris Lattnerb28317a2009-03-28 19:18:32 +00004446 return DeclPtrTy::make(PrevDecl);
Douglas Gregoraaba5e32009-02-04 19:02:06 +00004447
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004448 // Diagnose attempts to redefine a tag.
John McCall0f434ec2009-07-31 02:45:11 +00004449 if (TUK == TUK_Definition) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004450 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004451 // If we're defining a specialization and the previous definition
4452 // is from an implicit instantiation, don't emit an error
4453 // here; we'll catch this in the general case below.
4454 if (!isExplicitSpecialization ||
4455 !isa<CXXRecordDecl>(Def) ||
4456 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
4457 == TSK_ExplicitSpecialization) {
4458 Diag(NameLoc, diag::err_redefinition) << Name;
4459 Diag(Def->getLocation(), diag::note_previous_definition);
4460 // If this is a redefinition, recover by making this
4461 // struct be anonymous, which will make any later
4462 // references get the previous definition.
4463 Name = 0;
4464 PrevDecl = 0;
4465 Invalid = true;
4466 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00004467 } else {
4468 // If the type is currently being defined, complain
4469 // about a nested redefinition.
4470 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
4471 if (Tag->isBeingDefined()) {
4472 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump1eb44332009-09-09 15:08:12 +00004473 Diag(PrevTagDecl->getLocation(),
Douglas Gregor0b7a1582009-01-17 00:42:38 +00004474 diag::note_previous_definition);
4475 Name = 0;
4476 PrevDecl = 0;
4477 Invalid = true;
4478 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004479 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00004480
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004481 // Okay, this is definition of a previously declared or referenced
4482 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00004483 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004484 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004485 // If we get here we have (another) forward declaration or we
John McCall67d1a672009-08-06 02:15:43 +00004486 // have a definition. Just create a new decl.
4487
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004488 } else {
4489 // If we get here, this is a definition of a new tag type in a nested
Mike Stump1eb44332009-09-09 15:08:12 +00004490 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004491 // new decl/type. We set PrevDecl to NULL so that the entities
4492 // have distinct types.
4493 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00004494 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004495 // If we get here, we're going to create a new Decl. If PrevDecl
4496 // is non-NULL, it's a definition of the tag declared by
4497 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004498 } else {
Douglas Gregor66973122009-01-28 17:15:10 +00004499 // PrevDecl is a namespace, template, or anything else
4500 // that lives in the IDNS_Tag identifier namespace.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00004501 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00004502 // The tag name clashes with a namespace name, issue an error and
4503 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00004504 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00004505 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00004506 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004507 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00004508 Invalid = true;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004509 } else {
4510 // The existing declaration isn't relevant to us; we're in a
4511 // new scope, so clear out the previous declaration.
4512 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00004513 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004514 }
John McCall0f434ec2009-07-31 02:45:11 +00004515 } else if (TUK == TUK_Reference && SS.isEmpty() && Name &&
Douglas Gregor80711a22009-03-06 18:34:03 +00004516 (Kind != TagDecl::TK_enum || !getLangOptions().CPlusPlus)) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00004517 // C++ [basic.scope.pdecl]p5:
Mike Stump1eb44332009-09-09 15:08:12 +00004518 // -- for an elaborated-type-specifier of the form
Douglas Gregor3218c4b2009-01-09 22:42:13 +00004519 //
4520 // class-key identifier
4521 //
4522 // if the elaborated-type-specifier is used in the
4523 // decl-specifier-seq or parameter-declaration-clause of a
4524 // function defined in namespace scope, the identifier is
4525 // declared as a class-name in the namespace that contains
4526 // the declaration; otherwise, except as a friend
4527 // declaration, the identifier is declared in the smallest
4528 // non-class, non-function-prototype scope that contains the
4529 // declaration.
4530 //
4531 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
4532 // C structs and unions.
Douglas Gregor80711a22009-03-06 18:34:03 +00004533 //
4534 // GNU C also supports this behavior as part of its incomplete
4535 // enum types extension, while GNU C++ does not.
4536 //
Douglas Gregor3218c4b2009-01-09 22:42:13 +00004537 // Find the context where we'll be declaring the tag.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00004538 // FIXME: We would like to maintain the current DeclContext as the
Mike Stump1eb44332009-09-09 15:08:12 +00004539 // lexical context,
Douglas Gregor1931b442009-02-03 00:34:39 +00004540 while (SearchDC->isRecord())
4541 SearchDC = SearchDC->getParent();
Douglas Gregor3218c4b2009-01-09 22:42:13 +00004542
4543 // Find the scope where we'll be declaring the tag.
Mike Stump1eb44332009-09-09 15:08:12 +00004544 while (S->isClassScope() ||
Douglas Gregor3218c4b2009-01-09 22:42:13 +00004545 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00004546 ((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004547 (S->getEntity() &&
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00004548 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregor3218c4b2009-01-09 22:42:13 +00004549 S = S->getParent();
John McCall67d1a672009-08-06 02:15:43 +00004550
4551 } else if (TUK == TUK_Friend && SS.isEmpty() && Name) {
4552 // C++ [namespace.memdef]p3:
4553 // If a friend declaration in a non-local class first declares a
4554 // class or function, the friend class or function is a member of
4555 // the innermost enclosing namespace.
John McCall3f9a8a62009-08-11 06:59:38 +00004556 while (!SearchDC->isFileContext())
John McCall67d1a672009-08-06 02:15:43 +00004557 SearchDC = SearchDC->getParent();
4558
4559 // The entity of a decl scope is a DeclContext; see PushDeclContext.
4560 while (S->getEntity() != SearchDC)
4561 S = S->getParent();
Reid Spencer5f016e22007-07-11 17:01:13 +00004562 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004563
Chris Lattnercc98eac2008-12-17 07:13:27 +00004564CreateNewDecl:
Mike Stump1eb44332009-09-09 15:08:12 +00004565
Reid Spencer5f016e22007-07-11 17:01:13 +00004566 // If there is an identifier, use the location of the identifier as the
4567 // location of the decl, otherwise use the location of the struct/union
4568 // keyword.
4569 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00004570
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004571 // Otherwise, create a new declaration. If there is a previous
4572 // declaration of the same entity, the two will be linked via
4573 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00004574 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00004575
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004576 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004577 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4578 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor741dd9a2009-07-21 14:46:17 +00004579 New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004580 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00004581 // If this is an undefined enum, warn.
John McCall0f434ec2009-07-31 02:45:11 +00004582 if (TUK != TUK_Definition && !Invalid) {
Douglas Gregor80711a22009-03-06 18:34:03 +00004583 unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
4584 : diag::ext_forward_ref_enum;
4585 Diag(Loc, DK);
4586 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004587 } else {
4588 // struct/union/class
4589
Reid Spencer5f016e22007-07-11 17:01:13 +00004590 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4591 // struct X { int A; } D; D should chain to X.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004592 if (getLangOptions().CPlusPlus) {
Ted Kremenek2b345eb2008-09-05 17:39:33 +00004593 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor741dd9a2009-07-21 14:46:17 +00004594 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004595 cast_or_null<CXXRecordDecl>(PrevDecl));
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004596
4597 if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit()))
4598 StdBadAlloc = cast<CXXRecordDecl>(New);
4599 } else
Douglas Gregor741dd9a2009-07-21 14:46:17 +00004600 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004601 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004602 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004603
4604 if (Kind != TagDecl::TK_enum) {
4605 // Handle #pragma pack: if the #pragma pack stack has non-default
4606 // alignment, make up a packed attribute for this decl. These
4607 // attributes are checked when the ASTContext lays out the
4608 // structure.
4609 //
4610 // It is important for implementing the correct semantics that this
4611 // happen here (in act on tag decl). The #pragma pack stack is
4612 // maintained as a result of parser callbacks which can occur at
4613 // many points during the parsing of a struct declaration (because
4614 // the #pragma tokens are effectively skipped over during the
4615 // parsing of the struct).
Chris Lattner574aa402009-02-17 01:09:29 +00004616 if (unsigned Alignment = getPragmaPackAlignment())
Anders Carlssona860e752009-08-08 18:23:56 +00004617 New->addAttr(::new (Context) PragmaPackAttr(Alignment * 8));
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004618 }
4619
Douglas Gregor66973122009-01-28 17:15:10 +00004620 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
4621 // C++ [dcl.typedef]p3:
4622 // [...] Similarly, in a given scope, a class or enumeration
4623 // shall not be declared with the same name as a typedef-name
4624 // that is declared in that scope and refers to a type other
4625 // than the class or enumeration itself.
John McCalla24dc2e2009-11-17 02:14:36 +00004626 LookupResult Lookup(*this, Name, NameLoc, LookupOrdinaryName,
4627 LookupResult::ForRedeclaration);
4628 LookupName(Lookup, S);
Douglas Gregor66973122009-01-28 17:15:10 +00004629 TypedefDecl *PrevTypedef = 0;
John McCallf36e02d2009-10-09 21:13:30 +00004630 if (NamedDecl *Prev = Lookup.getAsSingleDecl(Context))
4631 PrevTypedef = dyn_cast<TypedefDecl>(Prev);
Douglas Gregor66973122009-01-28 17:15:10 +00004632
Douglas Gregor2531c2d2009-09-28 00:47:05 +00004633 NamedDecl *PrevTypedefNamed = PrevTypedef;
4634 if (PrevTypedef && isDeclInScope(PrevTypedefNamed, SearchDC, S) &&
Douglas Gregor66973122009-01-28 17:15:10 +00004635 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
4636 Context.getCanonicalType(Context.getTypeDeclType(New))) {
4637 Diag(Loc, diag::err_tag_definition_of_typedef)
4638 << Context.getTypeDeclType(New)
4639 << PrevTypedef->getUnderlyingType();
4640 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
4641 Invalid = true;
4642 }
4643 }
4644
Douglas Gregorf6b11852009-10-08 15:14:33 +00004645 // If this is a specialization of a member class (of a class template),
4646 // check the specialization.
4647 if (isExplicitSpecialization && CheckMemberSpecialization(New, PrevDecl))
4648 Invalid = true;
4649
Douglas Gregor0b7a1582009-01-17 00:42:38 +00004650 if (Invalid)
4651 New->setInvalidDecl();
4652
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004653 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004654 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004655
Douglas Gregor0b7a1582009-01-17 00:42:38 +00004656 // If we're declaring or defining a tag in function prototype scope
4657 // in C, note that this type can only be used within the function.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00004658 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
4659 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
4660
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00004661 // Set the lexical context. If the tag has a C++ scope specifier, the
4662 // lexical context will be different from the semantic context.
Douglas Gregor1931b442009-02-03 00:34:39 +00004663 New->setLexicalDeclContext(CurContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00004664
John McCall02cace72009-08-28 07:59:38 +00004665 // Mark this as a friend decl if applicable.
4666 if (TUK == TUK_Friend)
4667 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ PrevDecl != NULL);
4668
Anders Carlsson0cf88302009-03-26 01:19:02 +00004669 // Set the access specifier.
Eli Friedman56bea432009-08-27 18:44:04 +00004670 if (!Invalid && TUK != TUK_Friend)
Douglas Gregord0c87372009-05-27 17:30:49 +00004671 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor06c0fec2009-03-25 22:00:53 +00004672
John McCall0f434ec2009-07-31 02:45:11 +00004673 if (TUK == TUK_Definition)
Douglas Gregor0b7a1582009-01-17 00:42:38 +00004674 New->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00004675
Reid Spencer5f016e22007-07-11 17:01:13 +00004676 // If this has an identifier, add it to the scope stack.
John McCalld7eff682009-09-02 00:55:30 +00004677 if (TUK == TUK_Friend) {
John McCall82b9fb82009-09-02 19:32:14 +00004678 // We might be replacing an existing declaration in the lookup tables;
4679 // if so, borrow its access specifier.
4680 if (PrevDecl)
4681 New->setAccess(PrevDecl->getAccess());
4682
John McCalld7eff682009-09-02 00:55:30 +00004683 // Friend tag decls are visible in fairly strange ways.
4684 if (!CurContext->isDependentContext()) {
4685 DeclContext *DC = New->getDeclContext()->getLookupContext();
4686 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
4687 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4688 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
4689 }
4690 } else if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00004691 S = getNonFieldDeclScope(S);
Douglas Gregor1931b442009-02-03 00:34:39 +00004692 PushOnScopeChains(New, S);
Douglas Gregor4920f1f2009-01-12 22:49:06 +00004693 } else {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004694 CurContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00004695 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00004696
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004697 // If this is the C FILE type, notify the AST context.
4698 if (IdentifierInfo *II = New->getIdentifier())
4699 if (!New->isInvalidDecl() &&
Mike Stump782fa302009-07-28 02:25:19 +00004700 New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004701 II->isStr("FILE"))
4702 Context.setFILEDecl(New);
Mike Stump1eb44332009-09-09 15:08:12 +00004703
Douglas Gregor402abb52009-05-28 23:31:59 +00004704 OwnedDecl = true;
Chris Lattnerb28317a2009-03-28 19:18:32 +00004705 return DeclPtrTy::make(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00004706}
4707
Chris Lattnerb28317a2009-03-28 19:18:32 +00004708void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +00004709 AdjustDeclIfTemplate(TagD);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004710 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
Douglas Gregor72de6672009-01-08 20:45:30 +00004711
4712 // Enter the tag context.
4713 PushDeclContext(S, Tag);
4714
4715 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
4716 FieldCollector->StartClass();
4717
4718 if (Record->getIdentifier()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004719 // C++ [class]p2:
Douglas Gregor72de6672009-01-08 20:45:30 +00004720 // [...] The class-name is also inserted into the scope of the
4721 // class itself; this is known as the injected-class-name. For
4722 // purposes of access checking, the injected-class-name is treated
4723 // as if it were a public member name.
Douglas Gregord475b8d2009-03-25 21:17:03 +00004724 CXXRecordDecl *InjectedClassName
Douglas Gregor72de6672009-01-08 20:45:30 +00004725 = CXXRecordDecl::Create(Context, Record->getTagKind(),
4726 CurContext, Record->getLocation(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +00004727 Record->getIdentifier(),
4728 Record->getTagKeywordLoc(),
4729 Record);
Douglas Gregor72de6672009-01-08 20:45:30 +00004730 InjectedClassName->setImplicit();
Douglas Gregord475b8d2009-03-25 21:17:03 +00004731 InjectedClassName->setAccess(AS_public);
Douglas Gregorbefc20e2009-03-26 00:10:35 +00004732 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
4733 InjectedClassName->setDescribedClassTemplate(Template);
Douglas Gregor72de6672009-01-08 20:45:30 +00004734 PushOnScopeChains(InjectedClassName, S);
Mike Stump1eb44332009-09-09 15:08:12 +00004735 assert(InjectedClassName->isInjectedClassName() &&
Douglas Gregorc9b5b402009-03-25 15:59:44 +00004736 "Broken injected-class-name");
Douglas Gregor72de6672009-01-08 20:45:30 +00004737 }
4738 }
4739}
4740
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +00004741void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
4742 SourceLocation RBraceLoc) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +00004743 AdjustDeclIfTemplate(TagD);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004744 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +00004745 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor72de6672009-01-08 20:45:30 +00004746
4747 if (isa<CXXRecordDecl>(Tag))
4748 FieldCollector->FinishClass();
4749
4750 // Exit this scope of this tag's definition.
4751 PopDeclContext();
4752
4753 // Notify the consumer that we've defined a tag.
4754 Consumer.HandleTagDeclDefinition(Tag);
4755}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00004756
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00004757// Note that FieldName may be null for anonymous bitfields.
Mike Stump1eb44332009-09-09 15:08:12 +00004758bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Eli Friedman1d954f62009-08-15 21:55:26 +00004759 QualType FieldTy, const Expr *BitWidth,
4760 bool *ZeroWidth) {
4761 // Default to true; that shouldn't confuse checks for emptiness
4762 if (ZeroWidth)
4763 *ZeroWidth = true;
4764
Chris Lattner24793662009-03-05 22:45:59 +00004765 // C99 6.7.2.1p4 - verify the field type.
Chris Lattner8b963ef2009-03-05 23:01:03 +00004766 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregor3cf538d2009-03-11 18:59:21 +00004767 if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
Chris Lattner24793662009-03-05 22:45:59 +00004768 // Handle incomplete types with specific error.
Douglas Gregora03aca82009-03-10 21:58:27 +00004769 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
4770 return true;
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00004771 if (FieldName)
4772 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
4773 << FieldName << FieldTy << BitWidth->getSourceRange();
4774 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
4775 << FieldTy << BitWidth->getSourceRange();
Chris Lattner24793662009-03-05 22:45:59 +00004776 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +00004777
4778 // If the bit-width is type- or value-dependent, don't try to check
4779 // it now.
4780 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
4781 return false;
4782
Anders Carlsson9f1e5722008-12-06 20:33:04 +00004783 llvm::APSInt Value;
4784 if (VerifyIntegerConstantExpression(BitWidth, &Value))
4785 return true;
4786
Eli Friedman1d954f62009-08-15 21:55:26 +00004787 if (Value != 0 && ZeroWidth)
4788 *ZeroWidth = false;
4789
Chris Lattnercd087072008-12-12 04:56:04 +00004790 // Zero-width bitfield is ok for anonymous field.
4791 if (Value == 0 && FieldName)
4792 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00004793
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00004794 if (Value.isSigned() && Value.isNegative()) {
4795 if (FieldName)
Mike Stump1eb44332009-09-09 15:08:12 +00004796 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00004797 << FieldName << Value.toString(10);
4798 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
4799 << Value.toString(10);
4800 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00004801
Douglas Gregor3cf538d2009-03-11 18:59:21 +00004802 if (!FieldTy->isDependentType()) {
4803 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00004804 if (Value.getZExtValue() > TypeSize) {
4805 if (FieldName)
4806 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
4807 << FieldName << (unsigned)TypeSize;
4808 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
4809 << (unsigned)TypeSize;
4810 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +00004811 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00004812
4813 return false;
4814}
4815
Steve Naroff08d92e42007-09-15 18:49:24 +00004816/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00004817/// to create a FieldDecl object for it.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004818Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
Mike Stump1eb44332009-09-09 15:08:12 +00004819 SourceLocation DeclStart,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004820 Declarator &D, ExprTy *BitfieldWidth) {
4821 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
4822 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
4823 AS_public);
4824 return DeclPtrTy::make(Res);
Chris Lattner24793662009-03-05 22:45:59 +00004825}
4826
4827/// HandleField - Analyze a field of a C struct or a C++ data member.
4828///
4829FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
4830 SourceLocation DeclStart,
Douglas Gregor4dd55f52009-03-11 20:50:30 +00004831 Declarator &D, Expr *BitWidth,
4832 AccessSpecifier AS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004833 IdentifierInfo *II = D.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +00004834 SourceLocation Loc = DeclStart;
4835 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00004836
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004837 DeclaratorInfo *DInfo = 0;
4838 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Chris Lattner6491f472009-04-12 22:15:02 +00004839 if (getLangOptions().CPlusPlus)
Douglas Gregor3cf538d2009-03-11 18:59:21 +00004840 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +00004841
Eli Friedman85a53192009-04-07 19:37:57 +00004842 DiagnoseFunctionSpecifiers(D);
4843
Eli Friedman63054b32009-04-19 20:27:55 +00004844 if (D.getDeclSpec().isThreadSpecified())
4845 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4846
John McCalla24dc2e2009-11-17 02:14:36 +00004847 NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
4848 LookupResult::ForRedeclaration);
Douglas Gregorc19ee3e2009-06-17 23:37:01 +00004849
4850 if (PrevDecl && PrevDecl->isTemplateParameter()) {
4851 // Maybe we will complain about the shadowed template parameter.
4852 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4853 // Just pretend that we didn't see the previous declaration.
4854 PrevDecl = 0;
4855 }
4856
Douglas Gregor3cf538d2009-03-11 18:59:21 +00004857 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
4858 PrevDecl = 0;
4859
Steve Naroffea218b82009-07-14 14:58:18 +00004860 bool Mutable
4861 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
4862 SourceLocation TSSL = D.getSourceRange().getBegin();
4863 FieldDecl *NewFD
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004864 = CheckFieldDecl(II, T, DInfo, Record, Loc, Mutable, BitWidth, TSSL,
Steve Naroffea218b82009-07-14 14:58:18 +00004865 AS, PrevDecl, &D);
Douglas Gregor3cf538d2009-03-11 18:59:21 +00004866 if (NewFD->isInvalidDecl() && PrevDecl) {
4867 // Don't introduce NewFD into scope; there's already something
4868 // with the same name in the same scope.
4869 } else if (II) {
4870 PushOnScopeChains(NewFD, S);
4871 } else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004872 Record->addDecl(NewFD);
Douglas Gregor3cf538d2009-03-11 18:59:21 +00004873
4874 return NewFD;
4875}
4876
4877/// \brief Build a new FieldDecl and check its well-formedness.
4878///
4879/// This routine builds a new FieldDecl given the fields name, type,
4880/// record, etc. \p PrevDecl should refer to any previous declaration
4881/// with the same name and in the same scope as the field to be
4882/// created.
4883///
4884/// \returns a new FieldDecl.
4885///
Mike Stump1eb44332009-09-09 15:08:12 +00004886/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004887FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004888 DeclaratorInfo *DInfo,
Douglas Gregor3cf538d2009-03-11 18:59:21 +00004889 RecordDecl *Record, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00004890 bool Mutable, Expr *BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +00004891 SourceLocation TSSL,
Douglas Gregor4dd55f52009-03-11 20:50:30 +00004892 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor3cf538d2009-03-11 18:59:21 +00004893 Declarator *D) {
4894 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Naroff5912a352007-08-28 20:14:24 +00004895 bool InvalidDecl = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +00004896 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redl64b45f72009-01-05 20:52:13 +00004897
Douglas Gregor3cf538d2009-03-11 18:59:21 +00004898 // If we receive a broken type, recover by assuming 'int' and
4899 // marking this declaration as invalid.
4900 if (T.isNull()) {
4901 InvalidDecl = true;
4902 T = Context.IntTy;
4903 }
4904
Reid Spencer5f016e22007-07-11 17:01:13 +00004905 // C99 6.7.2.1p8: A member of a structure or union may have any type other
4906 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00004907 if (T->isVariablyModifiedType()) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004908 bool SizeIsNegative;
4909 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
4910 SizeIsNegative);
4911 if (!FixedTy.isNull()) {
4912 Diag(Loc, diag::warn_illegal_constant_array_size);
4913 T = FixedTy;
4914 } else {
4915 if (SizeIsNegative)
4916 Diag(Loc, diag::err_typecheck_negative_array_size);
4917 else
4918 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedman1ca48132009-02-21 00:44:51 +00004919 InvalidDecl = true;
4920 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004921 }
Mike Stump1eb44332009-09-09 15:08:12 +00004922
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004923 // Fields can not have abstract class types
Mike Stump1eb44332009-09-09 15:08:12 +00004924 if (RequireNonAbstractType(Loc, T, diag::err_abstract_type_in_decl,
Anders Carlsson8211eff2009-03-24 01:19:16 +00004925 AbstractFieldType))
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004926 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00004927
Eli Friedman1d954f62009-08-15 21:55:26 +00004928 bool ZeroWidth = false;
Douglas Gregor3cf538d2009-03-11 18:59:21 +00004929 // If this is declared as a bit-field, check the bit-field.
Eli Friedman1d954f62009-08-15 21:55:26 +00004930 if (BitWidth && VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
Douglas Gregor3cf538d2009-03-11 18:59:21 +00004931 InvalidDecl = true;
4932 DeleteExpr(BitWidth);
4933 BitWidth = 0;
Eli Friedman1d954f62009-08-15 21:55:26 +00004934 ZeroWidth = false;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00004935 }
Mike Stump1eb44332009-09-09 15:08:12 +00004936
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004937 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, DInfo,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00004938 BitWidth, Mutable);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004939 if (InvalidDecl)
4940 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00004941
Douglas Gregor3cf538d2009-03-11 18:59:21 +00004942 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
4943 Diag(Loc, diag::err_duplicate_member) << II;
4944 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4945 NewFD->setInvalidDecl();
Douglas Gregor72de6672009-01-08 20:45:30 +00004946 }
4947
Douglas Gregor1f2023a2009-07-22 18:25:24 +00004948 if (getLangOptions().CPlusPlus) {
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004949 QualType EltTy = Context.getBaseElementType(T);
Douglas Gregor1f2023a2009-07-22 18:25:24 +00004950
Eli Friedman1d954f62009-08-15 21:55:26 +00004951 CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
4952
4953 if (!T->isPODType())
4954 CXXRecord->setPOD(false);
4955 if (!ZeroWidth)
4956 CXXRecord->setEmpty(false);
4957
Ted Kremenek6217b802009-07-29 21:53:49 +00004958 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Douglas Gregor1f2023a2009-07-22 18:25:24 +00004959 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
4960
4961 if (!RDecl->hasTrivialConstructor())
Eli Friedman1d954f62009-08-15 21:55:26 +00004962 CXXRecord->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +00004963 if (!RDecl->hasTrivialCopyConstructor())
Eli Friedman1d954f62009-08-15 21:55:26 +00004964 CXXRecord->setHasTrivialCopyConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +00004965 if (!RDecl->hasTrivialCopyAssignment())
Eli Friedman1d954f62009-08-15 21:55:26 +00004966 CXXRecord->setHasTrivialCopyAssignment(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +00004967 if (!RDecl->hasTrivialDestructor())
Eli Friedman1d954f62009-08-15 21:55:26 +00004968 CXXRecord->setHasTrivialDestructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +00004969
4970 // C++ 9.5p1: An object of a class with a non-trivial
4971 // constructor, a non-trivial copy constructor, a non-trivial
4972 // destructor, or a non-trivial copy assignment operator
4973 // cannot be a member of a union, nor can an array of such
4974 // objects.
4975 // TODO: C++0x alters this restriction significantly.
4976 if (Record->isUnion()) {
4977 // We check for copy constructors before constructors
4978 // because otherwise we'll never get complaints about
4979 // copy constructors.
4980
4981 const CXXSpecialMember invalid = (CXXSpecialMember) -1;
4982
4983 CXXSpecialMember member;
4984 if (!RDecl->hasTrivialCopyConstructor())
4985 member = CXXCopyConstructor;
4986 else if (!RDecl->hasTrivialConstructor())
4987 member = CXXDefaultConstructor;
4988 else if (!RDecl->hasTrivialCopyAssignment())
4989 member = CXXCopyAssignment;
4990 else if (!RDecl->hasTrivialDestructor())
4991 member = CXXDestructor;
4992 else
4993 member = invalid;
4994
4995 if (member != invalid) {
4996 Diag(Loc, diag::err_illegal_union_member) << Name << member;
4997 DiagnoseNontrivial(RT, member);
4998 NewFD->setInvalidDecl();
4999 }
5000 }
5001 }
5002 }
5003
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005004 // FIXME: We need to pass in the attributes given an AST
5005 // representation, not a parser representation.
5006 if (D)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005007 // FIXME: What to pass instead of TUScope?
5008 ProcessDeclAttributes(TUScope, NewFD, *D);
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005009
Fariborz Jahanianf6123ca2009-02-19 00:22:47 +00005010 if (T.isObjCGCWeak())
Fariborz Jahanianed7e9ef2009-02-18 18:14:41 +00005011 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlssonad148062008-02-16 00:29:18 +00005012
Douglas Gregor4dd55f52009-03-11 20:50:30 +00005013 NewFD->setAccess(AS);
5014
5015 // C++ [dcl.init.aggr]p1:
5016 // An aggregate is an array or a class (clause 9) with [...] no
5017 // private or protected non-static data members (clause 11).
5018 // A POD must be an aggregate.
5019 if (getLangOptions().CPlusPlus &&
5020 (AS == AS_private || AS == AS_protected)) {
5021 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
5022 CXXRecord->setAggregate(false);
5023 CXXRecord->setPOD(false);
5024 }
5025
Steve Naroff5912a352007-08-28 20:14:24 +00005026 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00005027}
5028
Douglas Gregor1f2023a2009-07-22 18:25:24 +00005029/// DiagnoseNontrivial - Given that a class has a non-trivial
5030/// special member, figure out why.
5031void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
5032 QualType QT(T, 0U);
5033 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
5034
5035 // Check whether the member was user-declared.
5036 switch (member) {
5037 case CXXDefaultConstructor:
5038 if (RD->hasUserDeclaredConstructor()) {
5039 typedef CXXRecordDecl::ctor_iterator ctor_iter;
Sebastian Redl38fd4d02009-10-25 22:31:45 +00005040 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
5041 const FunctionDecl *body = 0;
5042 ci->getBody(body);
5043 if (!body ||
5044 !cast<CXXConstructorDecl>(body)->isImplicitlyDefined(Context)) {
Douglas Gregor1f2023a2009-07-22 18:25:24 +00005045 SourceLocation CtorLoc = ci->getLocation();
5046 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5047 return;
5048 }
Sebastian Redl38fd4d02009-10-25 22:31:45 +00005049 }
Douglas Gregor1f2023a2009-07-22 18:25:24 +00005050
5051 assert(0 && "found no user-declared constructors");
5052 return;
5053 }
5054 break;
5055
5056 case CXXCopyConstructor:
5057 if (RD->hasUserDeclaredCopyConstructor()) {
5058 SourceLocation CtorLoc =
5059 RD->getCopyConstructor(Context, 0)->getLocation();
5060 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5061 return;
5062 }
5063 break;
5064
5065 case CXXCopyAssignment:
5066 if (RD->hasUserDeclaredCopyAssignment()) {
5067 // FIXME: this should use the location of the copy
5068 // assignment, not the type.
5069 SourceLocation TyLoc = RD->getSourceRange().getBegin();
5070 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
5071 return;
5072 }
5073 break;
5074
5075 case CXXDestructor:
5076 if (RD->hasUserDeclaredDestructor()) {
5077 SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation();
5078 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5079 return;
5080 }
5081 break;
5082 }
5083
5084 typedef CXXRecordDecl::base_class_iterator base_iter;
5085
5086 // Virtual bases and members inhibit trivial copying/construction,
5087 // but not trivial destruction.
5088 if (member != CXXDestructor) {
5089 // Check for virtual bases. vbases includes indirect virtual bases,
5090 // so we just iterate through the direct bases.
5091 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
5092 if (bi->isVirtual()) {
5093 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5094 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
5095 return;
5096 }
5097
5098 // Check for virtual methods.
5099 typedef CXXRecordDecl::method_iterator meth_iter;
5100 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
5101 ++mi) {
5102 if (mi->isVirtual()) {
5103 SourceLocation MLoc = mi->getSourceRange().getBegin();
5104 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
5105 return;
5106 }
5107 }
5108 }
Mike Stump1eb44332009-09-09 15:08:12 +00005109
Douglas Gregor1f2023a2009-07-22 18:25:24 +00005110 bool (CXXRecordDecl::*hasTrivial)() const;
5111 switch (member) {
5112 case CXXDefaultConstructor:
5113 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
5114 case CXXCopyConstructor:
5115 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
5116 case CXXCopyAssignment:
5117 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
5118 case CXXDestructor:
5119 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
5120 default:
5121 assert(0 && "unexpected special member"); return;
5122 }
5123
5124 // Check for nontrivial bases (and recurse).
5125 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005126 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
Sebastian Redl9994a342009-10-25 17:03:50 +00005127 assert(BaseRT && "Don't know how to handle dependent bases");
Douglas Gregor1f2023a2009-07-22 18:25:24 +00005128 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
5129 if (!(BaseRecTy->*hasTrivial)()) {
5130 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5131 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
5132 DiagnoseNontrivial(BaseRT, member);
5133 return;
5134 }
5135 }
Mike Stump1eb44332009-09-09 15:08:12 +00005136
Douglas Gregor1f2023a2009-07-22 18:25:24 +00005137 // Check for nontrivial members (and recurse).
5138 typedef RecordDecl::field_iterator field_iter;
5139 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
5140 ++fi) {
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00005141 QualType EltTy = Context.getBaseElementType((*fi)->getType());
Ted Kremenek6217b802009-07-29 21:53:49 +00005142 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
Douglas Gregor1f2023a2009-07-22 18:25:24 +00005143 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
5144
5145 if (!(EltRD->*hasTrivial)()) {
5146 SourceLocation FLoc = (*fi)->getLocation();
5147 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
5148 DiagnoseNontrivial(EltRT, member);
5149 return;
5150 }
5151 }
5152 }
5153
5154 assert(0 && "found no explanation for non-trivial member");
5155}
5156
Mike Stump1eb44332009-09-09 15:08:12 +00005157/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanian89204a12007-10-01 16:53:59 +00005158/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005159static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00005160TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00005161 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00005162 default: assert(0 && "Unknown visitibility kind");
5163 case tok::objc_private: return ObjCIvarDecl::Private;
5164 case tok::objc_public: return ObjCIvarDecl::Public;
5165 case tok::objc_protected: return ObjCIvarDecl::Protected;
5166 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00005167 }
5168}
5169
Mike Stump1eb44332009-09-09 15:08:12 +00005170/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00005171/// in order to create an IvarDecl object for it.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005172Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00005173 SourceLocation DeclStart,
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00005174 DeclPtrTy IntfDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005175 Declarator &D, ExprTy *BitfieldWidth,
5176 tok::ObjCKeywordKind Visibility) {
Mike Stump1eb44332009-09-09 15:08:12 +00005177
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00005178 IdentifierInfo *II = D.getIdentifier();
5179 Expr *BitWidth = (Expr*)BitfieldWidth;
5180 SourceLocation Loc = DeclStart;
5181 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00005182
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00005183 // FIXME: Unnamed fields can be handled in various different ways, for
5184 // example, unnamed unions inject all members into the struct namespace!
Mike Stump1eb44332009-09-09 15:08:12 +00005185
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00005186 DeclaratorInfo *DInfo = 0;
5187 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00005188
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00005189 if (BitWidth) {
Steve Naroff63359c82009-02-20 17:57:11 +00005190 // 6.7.2.1p3, 6.7.2.1p4
Chris Lattner24793662009-03-05 22:45:59 +00005191 if (VerifyBitField(Loc, II, T, BitWidth)) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00005192 D.setInvalidType();
Chris Lattner24793662009-03-05 22:45:59 +00005193 DeleteExpr(BitWidth);
5194 BitWidth = 0;
5195 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00005196 } else {
5197 // Not a bitfield.
Mike Stump1eb44332009-09-09 15:08:12 +00005198
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00005199 // validate II.
Mike Stump1eb44332009-09-09 15:08:12 +00005200
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00005201 }
Mike Stump1eb44332009-09-09 15:08:12 +00005202
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00005203 // C99 6.7.2.1p8: A member of a structure or union may have any type other
5204 // than a variably modified type.
5205 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00005206 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnereaaebc72009-04-25 08:06:05 +00005207 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00005208 }
Mike Stump1eb44332009-09-09 15:08:12 +00005209
Ted Kremenekb8db21d2008-07-23 18:04:17 +00005210 // Get the visibility (access control) for this ivar.
Mike Stump1eb44332009-09-09 15:08:12 +00005211 ObjCIvarDecl::AccessControl ac =
Ted Kremenekb8db21d2008-07-23 18:04:17 +00005212 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
5213 : ObjCIvarDecl::None;
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00005214 // Must set ivar's DeclContext to its enclosing interface.
5215 Decl *EnclosingDecl = IntfDecl.getAs<Decl>();
5216 DeclContext *EnclosingContext;
Mike Stump1eb44332009-09-09 15:08:12 +00005217 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00005218 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5219 // Case of ivar declared in an implementation. Context is that of its class.
5220 ObjCInterfaceDecl* IDecl = IMPDecl->getClassInterface();
5221 assert(IDecl && "No class- ActOnIvar");
5222 EnclosingContext = cast_or_null<DeclContext>(IDecl);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005223 } else
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00005224 EnclosingContext = dyn_cast<DeclContext>(EnclosingDecl);
5225 assert(EnclosingContext && "null DeclContext for ivar - ActOnIvar");
Mike Stump1eb44332009-09-09 15:08:12 +00005226
Ted Kremenekb8db21d2008-07-23 18:04:17 +00005227 // Construct the decl.
Mike Stump1eb44332009-09-09 15:08:12 +00005228 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00005229 EnclosingContext, Loc, II, T,
5230 DInfo, ac, (Expr *)BitfieldWidth);
Mike Stump1eb44332009-09-09 15:08:12 +00005231
Douglas Gregor72de6672009-01-08 20:45:30 +00005232 if (II) {
John McCalla24dc2e2009-11-17 02:14:36 +00005233 NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
5234 LookupResult::ForRedeclaration);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00005235 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor72de6672009-01-08 20:45:30 +00005236 && !isa<TagDecl>(PrevDecl)) {
5237 Diag(Loc, diag::err_duplicate_member) << II;
5238 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5239 NewID->setInvalidDecl();
5240 }
5241 }
5242
Ted Kremenekb8db21d2008-07-23 18:04:17 +00005243 // Process attributes attached to the ivar.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005244 ProcessDeclAttributes(S, NewID, D);
Mike Stump1eb44332009-09-09 15:08:12 +00005245
Chris Lattnereaaebc72009-04-25 08:06:05 +00005246 if (D.isInvalidType())
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00005247 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00005248
Douglas Gregor72de6672009-01-08 20:45:30 +00005249 if (II) {
5250 // FIXME: When interfaces are DeclContexts, we'll need to add
5251 // these to the interface.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005252 S->AddDecl(DeclPtrTy::make(NewID));
Douglas Gregor72de6672009-01-08 20:45:30 +00005253 IdResolver.AddDecl(NewID);
5254 }
5255
Chris Lattnerb28317a2009-03-28 19:18:32 +00005256 return DeclPtrTy::make(NewID);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00005257}
5258
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00005259void Sema::ActOnFields(Scope* S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005260 SourceLocation RecLoc, DeclPtrTy RecDecl,
5261 DeclPtrTy *Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00005262 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00005263 AttributeList *Attr) {
Chris Lattnerb28317a2009-03-28 19:18:32 +00005264 Decl *EnclosingDecl = RecDecl.getAs<Decl>();
Steve Naroff74216642007-09-14 22:20:54 +00005265 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump1eb44332009-09-09 15:08:12 +00005266
Chris Lattner1829a6d2009-02-23 22:00:08 +00005267 // If the decl this is being inserted into is invalid, then it may be a
5268 // redeclaration or some other bogus case. Don't try to add fields to it.
5269 if (EnclosingDecl->isInvalidDecl()) {
5270 // FIXME: Deallocate fields?
5271 return;
5272 }
5273
Mike Stump1eb44332009-09-09 15:08:12 +00005274
Reid Spencer5f016e22007-07-11 17:01:13 +00005275 // Verify that all the fields are okay.
5276 unsigned NumNamedMembers = 0;
5277 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00005278
Chris Lattner1829a6d2009-02-23 22:00:08 +00005279 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00005280 for (unsigned i = 0; i != NumFields; ++i) {
Chris Lattnerb28317a2009-03-28 19:18:32 +00005281 FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00005282
Reid Spencer5f016e22007-07-11 17:01:13 +00005283 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00005284 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00005285
Douglas Gregor72de6672009-01-08 20:45:30 +00005286 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00005287 // Remember all fields written by the user.
5288 RecFields.push_back(FD);
5289 }
Mike Stump1eb44332009-09-09 15:08:12 +00005290
Chris Lattner24793662009-03-05 22:45:59 +00005291 // If the field is already invalid for some reason, don't emit more
5292 // diagnostics about it.
5293 if (FD->isInvalidDecl())
5294 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00005295
Douglas Gregore7450f52009-03-24 19:52:54 +00005296 // C99 6.7.2.1p2:
5297 // A structure or union shall not contain a member with
5298 // incomplete or function type (hence, a structure shall not
5299 // contain an instance of itself, but may contain a pointer to
5300 // an instance of itself), except that the last member of a
5301 // structure with more than one named member may have incomplete
5302 // array type; such a structure (and any union containing,
5303 // possibly recursively, a member that is such a structure)
5304 // shall not be a member of a structure or an element of an
5305 // array.
Chris Lattner02c642e2007-07-31 21:33:24 +00005306 if (FDTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00005307 // Field declared as a function.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005308 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005309 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00005310 FD->setInvalidDecl();
5311 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005312 continue;
Douglas Gregore7450f52009-03-24 19:52:54 +00005313 } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
5314 Record && Record->isStruct()) {
5315 // Flexible array member.
5316 if (NumNamedMembers < 1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005317 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005318 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00005319 FD->setInvalidDecl();
5320 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005321 continue;
5322 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005323 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00005324 if (Record)
5325 Record->setHasFlexibleArrayMember(true);
Douglas Gregore7450f52009-03-24 19:52:54 +00005326 } else if (!FDTy->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005327 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregore7450f52009-03-24 19:52:54 +00005328 diag::err_field_incomplete)) {
5329 // Incomplete type
5330 FD->setInvalidDecl();
5331 EnclosingDecl->setInvalidDecl();
5332 continue;
Ted Kremenek6217b802009-07-29 21:53:49 +00005333 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005334 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
5335 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00005336 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005337 Record->setHasFlexibleArrayMember(true);
5338 } else {
5339 // If this is a struct/class and this is not the last element, reject
5340 // it. Note that GCC supports variable sized arrays in the middle of
5341 // structures.
Douglas Gregore4f3e062009-03-06 23:41:27 +00005342 if (i != NumFields-1)
5343 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattner740782a2009-04-25 18:52:45 +00005344 << FD->getDeclName() << FD->getType();
Douglas Gregore4f3e062009-03-06 23:41:27 +00005345 else {
5346 // We support flexible arrays at the end of structs in
5347 // other structs as an extension.
5348 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
5349 << FD->getDeclName();
5350 if (Record)
5351 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00005352 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005353 }
5354 }
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00005355 if (Record && FDTTy->getDecl()->hasObjectMember())
5356 Record->setHasObjectMember(true);
Douglas Gregore7450f52009-03-24 19:52:54 +00005357 } else if (FDTy->isObjCInterfaceType()) {
5358 /// A field cannot be an Objective-c object
Steve Naroffccef3712009-02-20 22:59:16 +00005359 Diag(FD->getLocation(), diag::err_statically_allocated_object);
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00005360 FD->setInvalidDecl();
5361 EnclosingDecl->setInvalidDecl();
5362 continue;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005363 } else if (getLangOptions().ObjC1 &&
5364 getLangOptions().getGCMode() != LangOptions::NonGC &&
5365 Record &&
5366 (FD->getType()->isObjCObjectPointerType() ||
5367 FD->getType().isObjCGCStrong()))
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00005368 Record->setHasObjectMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00005369 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00005370 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00005371 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00005372 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005373
Reid Spencer5f016e22007-07-11 17:01:13 +00005374 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00005375 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005376 Record->completeDefinition(Context);
Chris Lattnere1e79852008-02-06 00:51:33 +00005377 } else {
Jay Foadbeaaccd2009-05-21 09:52:38 +00005378 ObjCIvarDecl **ClsFields =
5379 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00005380 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner38af2de2009-02-20 21:35:13 +00005381 ID->setIVarList(ClsFields, RecFields.size(), Context);
5382 ID->setLocEnd(RBrac);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00005383 // Add ivar's to class's DeclContext.
5384 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
5385 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005386 ID->addDecl(ClsFields[i]);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00005387 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00005388 // Must enforce the rule that ivars in the base classes may not be
5389 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00005390 if (ID->getSuperClass()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005391 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00005392 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
5393 ObjCIvarDecl* Ivar = (*IVI);
Daniel Dunbarad04e672009-05-03 01:08:28 +00005394
5395 if (IdentifierInfo *II = Ivar->getIdentifier()) {
5396 ObjCIvarDecl* prevIvar =
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005397 ID->getSuperClass()->lookupInstanceVariable(II);
Daniel Dunbarad04e672009-05-03 01:08:28 +00005398 if (prevIvar) {
5399 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
5400 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
5401 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00005402 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00005403 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00005404 }
Mike Stump1eb44332009-09-09 15:08:12 +00005405 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattner1829a6d2009-02-23 22:00:08 +00005406 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005407 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00005408 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
5409 // Ivar declared in @implementation never belongs to the implementation.
5410 // Only it is in implementation's lexical context.
Douglas Gregor8f36aba2009-04-23 03:23:08 +00005411 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00005412 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00005413 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00005414 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00005415
5416 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005417 ProcessDeclAttributeList(S, Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00005418}
5419
Douglas Gregor879fd492009-03-17 19:05:46 +00005420EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
5421 EnumConstantDecl *LastEnumConst,
5422 SourceLocation IdLoc,
5423 IdentifierInfo *Id,
5424 ExprArg val) {
5425 Expr *Val = (Expr *)val.get();
5426
5427 llvm::APSInt EnumVal(32);
5428 QualType EltTy;
Douglas Gregor4912c342009-11-06 00:03:12 +00005429 if (Val) {
5430 if (Val->isTypeDependent())
5431 EltTy = Context.DependentTy;
5432 else {
5433 // Make sure to promote the operand type to int.
5434 UsualUnaryConversions(Val);
5435 if (Val != val.get()) {
5436 val.release();
5437 val = Val;
5438 }
Douglas Gregor879fd492009-03-17 19:05:46 +00005439
Douglas Gregor4912c342009-11-06 00:03:12 +00005440 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
5441 SourceLocation ExpLoc;
5442 if (!Val->isValueDependent() &&
5443 VerifyIntegerConstantExpression(Val, &EnumVal)) {
5444 Val = 0;
5445 } else {
5446 EltTy = Val->getType();
5447 }
Douglas Gregor879fd492009-03-17 19:05:46 +00005448 }
5449 }
Mike Stump1eb44332009-09-09 15:08:12 +00005450
Douglas Gregor879fd492009-03-17 19:05:46 +00005451 if (!Val) {
5452 if (LastEnumConst) {
5453 // Assign the last value + 1.
5454 EnumVal = LastEnumConst->getInitVal();
5455 ++EnumVal;
5456
5457 // Check for overflow on increment.
5458 if (EnumVal < LastEnumConst->getInitVal())
5459 Diag(IdLoc, diag::warn_enum_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +00005460
Douglas Gregor879fd492009-03-17 19:05:46 +00005461 EltTy = LastEnumConst->getType();
5462 } else {
5463 // First value, set to zero.
5464 EltTy = Context.IntTy;
5465 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
5466 }
5467 }
Mike Stump1eb44332009-09-09 15:08:12 +00005468
Douglas Gregor4912c342009-11-06 00:03:12 +00005469 assert(!EltTy.isNull() && "Enum constant with NULL type");
5470
Douglas Gregor879fd492009-03-17 19:05:46 +00005471 val.release();
5472 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump1eb44332009-09-09 15:08:12 +00005473 Val, EnumVal);
Douglas Gregor879fd492009-03-17 19:05:46 +00005474}
5475
5476
Chris Lattnerb28317a2009-03-28 19:18:32 +00005477Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
5478 DeclPtrTy lastEnumConst,
5479 SourceLocation IdLoc,
5480 IdentifierInfo *Id,
5481 SourceLocation EqualLoc, ExprTy *val) {
5482 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00005483 EnumConstantDecl *LastEnumConst =
Chris Lattnerb28317a2009-03-28 19:18:32 +00005484 cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00005485 Expr *Val = static_cast<Expr*>(val);
5486
Chris Lattner31e05722007-08-26 06:24:45 +00005487 // The scope passed in may not be a decl scope. Zip up the scope tree until
5488 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00005489 S = getNonFieldDeclScope(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005490
Reid Spencer5f016e22007-07-11 17:01:13 +00005491 // Verify that there isn't already something declared with this name in this
5492 // scope.
John McCallf36e02d2009-10-09 21:13:30 +00005493 NamedDecl *PrevDecl = LookupSingleName(S, Id, LookupOrdinaryName);
Douglas Gregorf57172b2008-12-08 18:40:42 +00005494 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00005495 // Maybe we will complain about the shadowed template parameter.
5496 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
5497 // Just pretend that we didn't see the previous declaration.
5498 PrevDecl = 0;
5499 }
5500
5501 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00005502 // When in C++, we may get a TagDecl with the same name; in this case the
5503 // enum constant will 'hide' the tag.
5504 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
5505 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00005506 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005507 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00005508 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00005509 else
Chris Lattner3c73c412008-11-19 08:23:25 +00005510 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00005511 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerf306f862009-02-28 19:37:57 +00005512 if (Val) Val->Destroy(Context);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005513 return DeclPtrTy();
Reid Spencer5f016e22007-07-11 17:01:13 +00005514 }
5515 }
5516
Douglas Gregor879fd492009-03-17 19:05:46 +00005517 EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
5518 IdLoc, Id, Owned(Val));
Chris Lattner421a23d2007-08-27 21:16:18 +00005519
Reid Spencer5f016e22007-07-11 17:01:13 +00005520 // Register this decl in the current scope stack.
Douglas Gregor879fd492009-03-17 19:05:46 +00005521 if (New)
5522 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00005523
Chris Lattnerb28317a2009-03-28 19:18:32 +00005524 return DeclPtrTy::make(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00005525}
5526
Mike Stumpc6e35aa2009-05-16 07:06:02 +00005527void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
5528 SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
Edward O'Callaghanfee13812009-08-08 14:36:57 +00005529 DeclPtrTy *Elements, unsigned NumElements,
5530 Scope *S, AttributeList *Attr) {
Chris Lattnerb28317a2009-03-28 19:18:32 +00005531 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
Douglas Gregor074149e2009-01-05 19:45:36 +00005532 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanfee13812009-08-08 14:36:57 +00005533
5534 if (Attr)
5535 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump1eb44332009-09-09 15:08:12 +00005536
Chris Lattnere37f0be2007-08-28 05:10:31 +00005537 // TODO: If the result value doesn't fit in an int, it must be a long or long
5538 // long value. ISO C does not support this, but GCC does as an extension,
5539 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00005540 unsigned IntWidth = Context.Target.getIntWidth();
Edward O'Callaghanfee13812009-08-08 14:36:57 +00005541 unsigned CharWidth = Context.Target.getCharWidth();
5542 unsigned ShortWidth = Context.Target.getShortWidth();
Mike Stump1eb44332009-09-09 15:08:12 +00005543
Chris Lattnerac609682007-08-28 06:15:15 +00005544 // Verify that all the values are okay, compute the size of the values, and
5545 // reverse the list.
5546 unsigned NumNegativeBits = 0;
5547 unsigned NumPositiveBits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005548
Chris Lattnerac609682007-08-28 06:15:15 +00005549 // Keep track of whether all elements have type int.
5550 bool AllElementsInt = true;
Mike Stump1eb44332009-09-09 15:08:12 +00005551
Reid Spencer5f016e22007-07-11 17:01:13 +00005552 for (unsigned i = 0; i != NumElements; ++i) {
5553 EnumConstantDecl *ECD =
Chris Lattnerb28317a2009-03-28 19:18:32 +00005554 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00005555 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump1eb44332009-09-09 15:08:12 +00005556
Chris Lattner211a30e2007-08-28 05:27:00 +00005557 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00005558 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00005559 assert(InitVal.getBitWidth() >= IntWidth &&
5560 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00005561 if (InitVal.getBitWidth() > IntWidth) {
5562 llvm::APSInt V(InitVal);
5563 V.trunc(IntWidth);
5564 V.extend(InitVal.getBitWidth());
5565 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005566 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
5567 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00005568 }
Mike Stump1eb44332009-09-09 15:08:12 +00005569
Chris Lattnerac609682007-08-28 06:15:15 +00005570 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00005571 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00005572 NumPositiveBits = std::max(NumPositiveBits,
5573 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00005574 else
Chris Lattner21dd8212008-01-14 21:47:29 +00005575 NumNegativeBits = std::max(NumNegativeBits,
5576 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00005577
Chris Lattnerac609682007-08-28 06:15:15 +00005578 // Keep track of whether every enum element has type int (very commmon).
5579 if (AllElementsInt)
Mike Stump1eb44332009-09-09 15:08:12 +00005580 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005581 }
Mike Stump1eb44332009-09-09 15:08:12 +00005582
Chris Lattnerac609682007-08-28 06:15:15 +00005583 // Figure out the type that should be used for this enum.
Edward O'Callaghanfee13812009-08-08 14:36:57 +00005584 // FIXME: Support -fshort-enums.
Chris Lattnerac609682007-08-28 06:15:15 +00005585 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00005586 unsigned BestWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +00005587
5588 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
5589
Chris Lattnerac609682007-08-28 06:15:15 +00005590 if (NumNegativeBits) {
Mike Stump1eb44332009-09-09 15:08:12 +00005591 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerac609682007-08-28 06:15:15 +00005592 // int/long/longlong) that fits.
Edward O'Callaghanfee13812009-08-08 14:36:57 +00005593 // If it's packed, check also if it fits a char or a short.
5594 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
5595 BestType = Context.SignedCharTy;
5596 BestWidth = CharWidth;
Mike Stump1eb44332009-09-09 15:08:12 +00005597 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanfee13812009-08-08 14:36:57 +00005598 NumPositiveBits < ShortWidth) {
5599 BestType = Context.ShortTy;
5600 BestWidth = ShortWidth;
5601 }
5602 else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00005603 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00005604 BestWidth = IntWidth;
5605 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00005606 BestWidth = Context.Target.getLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +00005607
Chris Lattnerb7f6e082007-08-29 17:31:48 +00005608 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00005609 BestType = Context.LongTy;
5610 else {
Chris Lattner98be4942008-03-05 18:54:05 +00005611 BestWidth = Context.Target.getLongLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +00005612
Chris Lattnerb7f6e082007-08-29 17:31:48 +00005613 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00005614 Diag(Enum->getLocation(), diag::warn_enum_too_large);
5615 BestType = Context.LongLongTy;
5616 }
5617 }
5618 } else {
5619 // If there is no negative value, figure out which of uint, ulong, ulonglong
5620 // fits.
Edward O'Callaghanfee13812009-08-08 14:36:57 +00005621 // If it's packed, check also if it fits a char or a short.
5622 if (Packed && NumPositiveBits <= CharWidth) {
5623 BestType = Context.UnsignedCharTy;
5624 BestWidth = CharWidth;
5625 } else if (Packed && NumPositiveBits <= ShortWidth) {
5626 BestType = Context.UnsignedShortTy;
5627 BestWidth = ShortWidth;
5628 }
5629 else if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00005630 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00005631 BestWidth = IntWidth;
5632 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00005633 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00005634 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00005635 } else {
5636 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00005637 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00005638 "How could an initializer get larger than ULL?");
5639 BestType = Context.UnsignedLongLongTy;
5640 }
5641 }
Mike Stump1eb44332009-09-09 15:08:12 +00005642
Chris Lattnerb7f6e082007-08-29 17:31:48 +00005643 // Loop over all of the enumerator constants, changing their types to match
5644 // the type of the enum if needed.
5645 for (unsigned i = 0; i != NumElements; ++i) {
5646 EnumConstantDecl *ECD =
Chris Lattnerb28317a2009-03-28 19:18:32 +00005647 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
Chris Lattnerb7f6e082007-08-29 17:31:48 +00005648 if (!ECD) continue; // Already issued a diagnostic.
5649
5650 // Standard C says the enumerators have int type, but we allow, as an
5651 // extension, the enumerators to be larger than int size. If each
5652 // enumerator value fits in an int, type it as an int, otherwise type it the
5653 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
5654 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00005655 if (ECD->getType() == Context.IntTy) {
5656 // Make sure the init value is signed.
5657 llvm::APSInt IV = ECD->getInitVal();
5658 IV.setIsSigned(true);
5659 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005660
5661 if (getLangOptions().CPlusPlus)
5662 // C++ [dcl.enum]p4: Following the closing brace of an
5663 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +00005664 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005665 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00005666 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00005667 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00005668
5669 // Determine whether the value fits into an int.
5670 llvm::APSInt InitVal = ECD->getInitVal();
5671 bool FitsInInt;
5672 if (InitVal.isUnsigned() || !InitVal.isNegative())
5673 FitsInInt = InitVal.getActiveBits() < IntWidth;
5674 else
5675 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
5676
5677 // If it fits into an integer type, force it. Otherwise force it to match
5678 // the enum decl type.
5679 QualType NewTy;
5680 unsigned NewWidth;
5681 bool NewSign;
5682 if (FitsInInt) {
5683 NewTy = Context.IntTy;
5684 NewWidth = IntWidth;
5685 NewSign = true;
5686 } else if (ECD->getType() == BestType) {
5687 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005688 if (getLangOptions().CPlusPlus)
5689 // C++ [dcl.enum]p4: Following the closing brace of an
5690 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +00005691 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005692 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00005693 continue;
5694 } else {
5695 NewTy = BestType;
5696 NewWidth = BestWidth;
5697 NewSign = BestType->isSignedIntegerType();
5698 }
5699
5700 // Adjust the APSInt value.
5701 InitVal.extOrTrunc(NewWidth);
5702 InitVal.setIsSigned(NewSign);
5703 ECD->setInitVal(InitVal);
Mike Stump1eb44332009-09-09 15:08:12 +00005704
Chris Lattnerb7f6e082007-08-29 17:31:48 +00005705 // Adjust the Expr initializer and type.
Chris Lattner13fd4162009-01-15 19:19:42 +00005706 if (ECD->getInitExpr())
Mike Stump1eb44332009-09-09 15:08:12 +00005707 ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
Eli Friedman73c39ab2009-10-20 08:27:19 +00005708 CastExpr::CK_IntegralCast,
Mike Stump1eb44332009-09-09 15:08:12 +00005709 ECD->getInitExpr(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00005710 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005711 if (getLangOptions().CPlusPlus)
5712 // C++ [dcl.enum]p4: Following the closing brace of an
5713 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +00005714 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005715 ECD->setType(EnumType);
5716 else
5717 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00005718 }
Mike Stump1eb44332009-09-09 15:08:12 +00005719
Douglas Gregor44b43212008-12-11 16:49:14 +00005720 Enum->completeDefinition(Context, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005721}
5722
Chris Lattnerb28317a2009-03-28 19:18:32 +00005723Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
5724 ExprArg expr) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00005725 StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
Sebastian Redl798d1192008-12-13 16:23:55 +00005726
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00005727 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
5728 Loc, AsmString);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005729 CurContext->addDecl(New);
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00005730 return DeclPtrTy::make(New);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00005731}
Eli Friedmanc49f19b2009-06-05 02:44:36 +00005732
5733void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
5734 SourceLocation PragmaLoc,
5735 SourceLocation NameLoc) {
John McCallf36e02d2009-10-09 21:13:30 +00005736 Decl *PrevDecl = LookupSingleName(TUScope, Name, LookupOrdinaryName);
Eli Friedmanc49f19b2009-06-05 02:44:36 +00005737
Eli Friedmanc49f19b2009-06-05 02:44:36 +00005738 if (PrevDecl) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005739 PrevDecl->addAttr(::new (Context) WeakAttr());
Ryan Flynne25ff832009-07-30 03:15:39 +00005740 } else {
5741 (void)WeakUndeclaredIdentifiers.insert(
5742 std::pair<IdentifierInfo*,WeakInfo>
5743 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedmanc49f19b2009-06-05 02:44:36 +00005744 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +00005745}
5746
5747void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
5748 IdentifierInfo* AliasName,
5749 SourceLocation PragmaLoc,
5750 SourceLocation NameLoc,
5751 SourceLocation AliasNameLoc) {
John McCallf36e02d2009-10-09 21:13:30 +00005752 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, LookupOrdinaryName);
Ryan Flynne25ff832009-07-30 03:15:39 +00005753 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedmanc49f19b2009-06-05 02:44:36 +00005754
Eli Friedmanc49f19b2009-06-05 02:44:36 +00005755 if (PrevDecl) {
Ryan Flynne25ff832009-07-30 03:15:39 +00005756 if (!PrevDecl->hasAttr<AliasAttr>())
5757 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynn7b1fdbd2009-07-31 02:52:19 +00005758 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynne25ff832009-07-30 03:15:39 +00005759 } else {
5760 (void)WeakUndeclaredIdentifiers.insert(
5761 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedmanc49f19b2009-06-05 02:44:36 +00005762 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +00005763}