blob: 11e1ffe107a59ff48557ec1be9de00ab9f23ae14 [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"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000017#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000018#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.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"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Parse/DeclSpec.h"
Douglas Gregora786fdb2009-10-13 23:27:22 +000025#include "clang/Parse/ParseDiagnostic.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000026#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000028#include "clang/Basic/SourceManager.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000029#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000030// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000031#include "clang/Lex/Preprocessor.h"
Mike Stump1eb44332009-09-09 15:08:12 +000032#include "clang/Lex/HeaderSearch.h"
John McCall66755862009-12-24 09:58:38 +000033#include "llvm/ADT/Triple.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000034#include <algorithm>
Douglas Gregor9a8c9a22009-09-28 21:14:19 +000035#include <cstring>
Douglas Gregor6ed40e32008-12-23 21:05:05 +000036#include <functional>
Reid Spencer5f016e22007-07-11 17:01:13 +000037using namespace clang;
38
Chris Lattner21ff9c92009-03-05 01:25:28 +000039/// getDeclName - Return a pretty name for the specified decl if possible, or
Mike Stump1eb44332009-09-09 15:08:12 +000040/// an empty string if not. This is used for pretty crash reporting.
Chris Lattnerb28317a2009-03-28 19:18:32 +000041std::string Sema::getDeclName(DeclPtrTy d) {
42 Decl *D = d.getAs<Decl>();
Chris Lattner21ff9c92009-03-05 01:25:28 +000043 if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
44 return DN->getQualifiedNameAsString();
45 return "";
46}
47
Chris Lattner682bf922009-03-29 16:50:03 +000048Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
49 return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
50}
51
Douglas Gregord6efafa2009-02-04 19:16:12 +000052/// \brief If the identifier refers to a type name within this scope,
53/// return the declaration of that type.
54///
55/// This routine performs ordinary name lookup of the identifier II
56/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor1a51b4a2009-02-09 15:09:02 +000057/// determine whether the name refers to a type. If so, returns an
58/// opaque pointer (actually a QualType) corresponding to that
59/// type. Otherwise, returns NULL.
Douglas Gregord6efafa2009-02-04 19:16:12 +000060///
61/// If name lookup results in an ambiguity, this routine will complain
62/// and then return NULL.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +000063Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +000064 Scope *S, CXXScopeSpec *SS,
Douglas Gregorf6e6fc82009-11-20 22:03:38 +000065 bool isClassName,
66 TypeTy *ObjectTypePtr) {
67 // Determine where we will perform name lookup.
68 DeclContext *LookupCtx = 0;
69 if (ObjectTypePtr) {
70 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
71 if (ObjectType->isRecordType())
72 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskinedc28772010-04-07 23:29:58 +000073 } else if (SS && SS->isNotEmpty()) {
Douglas Gregorf6e6fc82009-11-20 22:03:38 +000074 LookupCtx = computeDeclContext(*SS, false);
75
76 if (!LookupCtx) {
77 if (isDependentScopeSpecifier(*SS)) {
78 // C++ [temp.res]p3:
79 // A qualified-id that refers to a type and in which the
80 // nested-name-specifier depends on a template-parameter (14.6.2)
81 // shall be prefixed by the keyword typename to indicate that the
82 // qualified-id denotes a type, forming an
83 // elaborated-type-specifier (7.1.5.3).
84 //
85 // We therefore do not perform any name lookup if the result would
86 // refer to a member of an unknown specialization.
87 if (!isClassName)
88 return 0;
89
John McCall33500952010-06-11 00:33:02 +000090 // We know from the grammar that this name refers to a type,
91 // so build a dependent node to describe the type.
Douglas Gregor107de902010-04-24 15:35:55 +000092 return CheckTypenameType(ETK_None,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +000093 (NestedNameSpecifier *)SS->getScopeRep(), II,
94 SourceLocation(), SS->getRange(), NameLoc
95 ).getAsOpaquePtr();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +000096 }
97
Douglas Gregor42c39f32009-08-26 18:27:52 +000098 return 0;
Douglas Gregorf6e6fc82009-11-20 22:03:38 +000099 }
100
John McCall77bb1aa2010-05-01 00:40:08 +0000101 if (!LookupCtx->isDependentContext() &&
102 RequireCompleteDeclContext(*SS, LookupCtx))
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000103 return 0;
Douglas Gregor42c39f32009-08-26 18:27:52 +0000104 }
Eli Friedman0f0615b2009-12-21 01:42:38 +0000105
106 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
107 // lookup for class-names.
108 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
109 LookupOrdinaryName;
110 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000111 if (LookupCtx) {
112 // Perform "qualified" name lookup into the declaration context we
113 // computed, which is either the type of the base of a member access
114 // expression or the declaration context associated with a prior
115 // nested-name-specifier.
116 LookupQualifiedName(Result, LookupCtx);
Douglas Gregor42af25f2009-05-11 19:58:34 +0000117
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000118 if (ObjectTypePtr && Result.empty()) {
119 // C++ [basic.lookup.classref]p3:
120 // If the unqualified-id is ~type-name, the type-name is looked up
121 // in the context of the entire postfix-expression. If the type T of
122 // the object expression is of a class type C, the type-name is also
123 // looked up in the scope of class C. At least one of the lookups shall
124 // find a name that refers to (possibly cv-qualified) T.
125 LookupName(Result, S);
126 }
127 } else {
128 // Perform unqualified name lookup.
129 LookupName(Result, S);
130 }
131
Chris Lattner22bd9052009-02-16 22:07:16 +0000132 NamedDecl *IIDecl = 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000133 switch (Result.getResultKind()) {
Chris Lattner22bd9052009-02-16 22:07:16 +0000134 case LookupResult::NotFound:
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000135 case LookupResult::NotFoundInCurrentInstantiation:
Chris Lattner22bd9052009-02-16 22:07:16 +0000136 case LookupResult::FoundOverloaded:
John McCall7ba107a2009-11-18 02:36:19 +0000137 case LookupResult::FoundUnresolvedValue:
John McCallc373d482010-01-27 01:50:18 +0000138 Result.suppressDiagnostics();
Chris Lattner22bd9052009-02-16 22:07:16 +0000139 return 0;
Douglas Gregorb696ea32009-02-04 17:00:24 +0000140
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000141 case LookupResult::Ambiguous:
John McCall6e247262009-10-10 05:48:19 +0000142 // Recover from type-hiding ambiguities by hiding the type. We'll
143 // do the lookup again when looking for an object, and we can
144 // diagnose the error then. If we don't do this, then the error
145 // about hiding the type will be immediately followed by an error
146 // that only makes sense if the identifier was treated like a type.
John McCalla24dc2e2009-11-17 02:14:36 +0000147 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
148 Result.suppressDiagnostics();
John McCall6e247262009-10-10 05:48:19 +0000149 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000150 }
John McCall6e247262009-10-10 05:48:19 +0000151
Douglas Gregor31a19b62009-04-01 21:51:26 +0000152 // Look to see if we have a type anywhere in the list of results.
153 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
154 Res != ResEnd; ++Res) {
155 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000156 if (!IIDecl ||
157 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor841b53c2009-04-13 15:14:38 +0000158 IIDecl->getLocation().getRawEncoding())
159 IIDecl = *Res;
Douglas Gregor31a19b62009-04-01 21:51:26 +0000160 }
161 }
162
163 if (!IIDecl) {
164 // None of the entities we found is a type, so there is no way
165 // to even assume that the result is a type. In this case, don't
166 // complain about the ambiguity. The parser will either try to
167 // perform this lookup again (e.g., as an object name), which
168 // will produce the ambiguity, or will complain that it expected
169 // a type name.
John McCalla24dc2e2009-11-17 02:14:36 +0000170 Result.suppressDiagnostics();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000171 return 0;
172 }
173
174 // We found a type within the ambiguous lookup; diagnose the
175 // ambiguity and then return that type. This might be the right
176 // answer, or it might not be, but it suppresses any attempt to
177 // perform the name lookup again.
Douglas Gregor31a19b62009-04-01 21:51:26 +0000178 break;
Douglas Gregorb696ea32009-02-04 17:00:24 +0000179
Chris Lattner22bd9052009-02-16 22:07:16 +0000180 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +0000181 IIDecl = Result.getFoundDecl();
Chris Lattner22bd9052009-02-16 22:07:16 +0000182 break;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000183 }
184
Chris Lattner10ca3372009-10-25 17:16:46 +0000185 assert(IIDecl && "Didn't find decl");
John McCall54abf7d2009-11-04 02:18:39 +0000186
Chris Lattner10ca3372009-10-25 17:16:46 +0000187 QualType T;
188 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall54abf7d2009-11-04 02:18:39 +0000189 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCalla24dc2e2009-11-17 02:14:36 +0000190
Chris Lattner10ca3372009-10-25 17:16:46 +0000191 if (T.isNull())
192 T = Context.getTypeDeclType(TD);
193
Douglas Gregore6258932009-03-19 00:39:20 +0000194 if (SS)
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000195 T = getElaboratedType(ETK_None, *SS, T);
Chris Lattner10ca3372009-10-25 17:16:46 +0000196
197 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Chris Lattner10ca3372009-10-25 17:16:46 +0000198 T = Context.getObjCInterfaceType(IDecl);
John McCalla24dc2e2009-11-17 02:14:36 +0000199 } else {
200 // If it's not plausibly a type, suppress diagnostics.
201 Result.suppressDiagnostics();
Chris Lattner10ca3372009-10-25 17:16:46 +0000202 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000203 }
Douglas Gregore4e5b052009-03-19 00:18:19 +0000204
Chris Lattner10ca3372009-10-25 17:16:46 +0000205 return T.getAsOpaquePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +0000206}
207
Chris Lattner4c97d762009-04-12 21:49:30 +0000208/// isTagName() - This method is called *for error recovery purposes only*
209/// to determine if the specified name is a valid tag name ("struct foo"). If
210/// so, this returns the TST for the tag corresponding to it (TST_enum,
211/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
212/// where the user forgot to specify the tag.
213DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
214 // Do a tag name lookup in this scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000215 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
216 LookupName(R, S, false);
217 R.suppressDiagnostics();
218 if (R.getResultKind() == LookupResult::Found)
John McCall1bcee0a2009-12-02 08:25:40 +0000219 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattner4c97d762009-04-12 21:49:30 +0000220 switch (TD->getTagKind()) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000221 default: return DeclSpec::TST_unspecified;
222 case TTK_Struct: return DeclSpec::TST_struct;
223 case TTK_Union: return DeclSpec::TST_union;
224 case TTK_Class: return DeclSpec::TST_class;
225 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattner4c97d762009-04-12 21:49:30 +0000226 }
227 }
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattner4c97d762009-04-12 21:49:30 +0000229 return DeclSpec::TST_unspecified;
230}
231
Douglas Gregora786fdb2009-10-13 23:27:22 +0000232bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
233 SourceLocation IILoc,
234 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000235 CXXScopeSpec *SS,
Douglas Gregora786fdb2009-10-13 23:27:22 +0000236 TypeTy *&SuggestedType) {
237 // We don't have anything to suggest (yet).
238 SuggestedType = 0;
239
Douglas Gregor546be3c2009-12-30 17:04:44 +0000240 // There may have been a typo in the name of the type. Look up typo
241 // results, in case we have something that we can suggest.
242 LookupResult Lookup(*this, &II, IILoc, LookupOrdinaryName,
243 NotForRedeclaration);
244
Douglas Gregoraaf87162010-04-14 20:04:41 +0000245 if (DeclarationName Corrected = CorrectTypo(Lookup, S, SS, 0, 0, CTC_Type)) {
246 if (NamedDecl *Result = Lookup.getAsSingle<NamedDecl>()) {
247 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
248 !Result->isInvalidDecl()) {
249 // We found a similarly-named type or interface; suggest that.
250 if (!SS || !SS->isSet())
251 Diag(IILoc, diag::err_unknown_typename_suggest)
252 << &II << Lookup.getLookupName()
253 << FixItHint::CreateReplacement(SourceRange(IILoc),
254 Result->getNameAsString());
255 else if (DeclContext *DC = computeDeclContext(*SS, false))
256 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
257 << &II << DC << Lookup.getLookupName() << SS->getRange()
258 << FixItHint::CreateReplacement(SourceRange(IILoc),
259 Result->getNameAsString());
260 else
261 llvm_unreachable("could not have corrected a typo here");
Douglas Gregor546be3c2009-12-30 17:04:44 +0000262
Douglas Gregoraaf87162010-04-14 20:04:41 +0000263 Diag(Result->getLocation(), diag::note_previous_decl)
264 << Result->getDeclName();
265
266 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS);
267 return true;
268 }
269 } else if (Lookup.empty()) {
270 // We corrected to a keyword.
271 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
272 Diag(IILoc, diag::err_unknown_typename_suggest)
273 << &II << Corrected;
274 return true;
Douglas Gregor546be3c2009-12-30 17:04:44 +0000275 }
276 }
277
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000278 if (getLangOptions().CPlusPlus) {
279 // See if II is a class template that the user forgot to pass arguments to.
280 UnqualifiedId Name;
281 Name.setIdentifier(&II, IILoc);
282 CXXScopeSpec EmptySS;
283 TemplateTy TemplateResult;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000284 bool MemberOfUnknownSpecialization;
285 if (isTemplateName(S, SS ? *SS : EmptySS, Name, 0, true, TemplateResult,
286 MemberOfUnknownSpecialization) == TNK_Type_template) {
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000287 TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
288 Diag(IILoc, diag::err_template_missing_args) << TplName;
289 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
290 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
291 << TplDecl->getTemplateParameters()->getSourceRange();
292 }
293 return true;
294 }
295 }
296
Douglas Gregora786fdb2009-10-13 23:27:22 +0000297 // FIXME: Should we move the logic that tries to recover from a missing tag
298 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
299
Douglas Gregor546be3c2009-12-30 17:04:44 +0000300 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Douglas Gregora786fdb2009-10-13 23:27:22 +0000301 Diag(IILoc, diag::err_unknown_typename) << &II;
302 else if (DeclContext *DC = computeDeclContext(*SS, false))
303 Diag(IILoc, diag::err_typename_nested_not_found)
304 << &II << DC << SS->getRange();
305 else if (isDependentScopeSpecifier(*SS)) {
306 Diag(SS->getRange().getBegin(), diag::err_typename_missing)
Daniel Dunbar01eb9b92009-10-18 21:17:35 +0000307 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
Douglas Gregora786fdb2009-10-13 23:27:22 +0000308 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregor849b2432010-03-31 17:46:05 +0000309 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Douglas Gregor1a15dae2010-06-16 22:31:08 +0000310 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc).get();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000311 } else {
312 assert(SS && SS->isInvalid() &&
313 "Invalid scope specifier has already been diagnosed");
314 }
315
316 return true;
317}
Chris Lattner4c97d762009-04-12 21:49:30 +0000318
John McCall88232aa2009-08-18 00:00:49 +0000319// Determines the context to return to after temporarily entering a
320// context. This depends in an unnecessarily complicated way on the
321// exact ordering of callbacks from the parser.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000322DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000323
John McCall88232aa2009-08-18 00:00:49 +0000324 // Functions defined inline within classes aren't parsed until we've
325 // finished parsing the top-level class, so the top-level class is
326 // the context we'll need to return to.
327 if (isa<FunctionDecl>(DC)) {
328 DC = DC->getLexicalParent();
329
330 // A function not defined within a class will always return to its
331 // lexical context.
332 if (!isa<CXXRecordDecl>(DC))
333 return DC;
334
335 // A C++ inline method/friend is parsed *after* the topmost class
336 // it was declared in is fully parsed ("complete"); the topmost
337 // class is the context we need to return to.
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000338 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000339 DC = RD;
340
341 // Return the declaration context of the topmost class the inline method is
342 // declared in.
343 return DC;
344 }
345
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +0000346 if (isa<ObjCMethodDecl>(DC))
347 return Context.getTranslationUnitDecl();
348
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000349 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000350}
351
Douglas Gregor44b43212008-12-11 16:49:14 +0000352void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000353 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +0000354 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +0000355 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +0000356 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000357}
358
Chris Lattnerb048c982008-04-06 04:47:34 +0000359void Sema::PopDeclContext() {
360 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +0000361
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000362 CurContext = getContainingDC(CurContext);
John McCallacb70392010-07-23 22:45:07 +0000363 assert(CurContext && "Popped translation unit!");
Chris Lattner0ed844b2008-04-04 06:12:32 +0000364}
365
Argyrios Kyrtzidis179fe1a2009-06-17 23:19:02 +0000366/// EnterDeclaratorContext - Used when we must lookup names in the context
367/// of a declarator's nested name specifier.
John McCall7a1dc562009-12-19 10:49:29 +0000368///
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000369void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall7a1dc562009-12-19 10:49:29 +0000370 // C++0x [basic.lookup.unqual]p13:
371 // A name used in the definition of a static data member of class
372 // X (after the qualified-id of the static member) is looked up as
373 // if the name was used in a member function of X.
374 // C++0x [basic.lookup.unqual]p14:
375 // If a variable member of a namespace is defined outside of the
376 // scope of its namespace then any name used in the definition of
377 // the variable member (after the declarator-id) is looked up as
378 // if the definition of the variable member occurred in its
379 // namespace.
380 // Both of these imply that we should push a scope whose context
381 // is the semantic context of the declaration. We can't use
382 // PushDeclContext here because that context is not necessarily
383 // lexically contained in the current context. Fortunately,
384 // the containing scope should have the appropriate information.
385
386 assert(!S->getEntity() && "scope already has entity");
387
388#ifndef NDEBUG
389 Scope *Ancestor = S->getParent();
390 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
391 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
392#endif
393
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000394 CurContext = DC;
John McCall7a1dc562009-12-19 10:49:29 +0000395 S->setEntity(DC);
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000396}
397
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000398void Sema::ExitDeclaratorContext(Scope *S) {
John McCall7a1dc562009-12-19 10:49:29 +0000399 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000400
John McCall7a1dc562009-12-19 10:49:29 +0000401 // Switch back to the lexical context. The safety of this is
402 // enforced by an assert in EnterDeclaratorContext.
403 Scope *Ancestor = S->getParent();
404 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
405 CurContext = (DeclContext*) Ancestor->getEntity();
406
407 // We don't need to do anything with the scope, which is going to
408 // disappear.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000409}
410
Douglas Gregorf9201e02009-02-11 23:02:49 +0000411/// \brief Determine whether we allow overloading of the function
412/// PrevDecl with another declaration.
413///
414/// This routine determines whether overloading is possible, not
415/// whether some new function is actually an overload. It will return
416/// true in C++ (where we can always provide overloads) or, as an
417/// extension, in C when the previous function is already an
418/// overloaded function declaration or has the "overloadable"
419/// attribute.
John McCall68263142009-11-18 22:49:29 +0000420static bool AllowOverloadingOfFunction(LookupResult &Previous,
421 ASTContext &Context) {
Douglas Gregorf9201e02009-02-11 23:02:49 +0000422 if (Context.getLangOptions().CPlusPlus)
423 return true;
424
John McCall68263142009-11-18 22:49:29 +0000425 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000426 return true;
427
John McCall68263142009-11-18 22:49:29 +0000428 return (Previous.getResultKind() == LookupResult::Found
429 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregorf9201e02009-02-11 23:02:49 +0000430}
431
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000432/// Add this decl to the scope shadowed decl chains.
John McCallab88d972009-08-31 22:39:49 +0000433void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000434 // Move up the scope chain until we find the nearest enclosing
435 // non-transparent context. The declaration will be introduced into this
436 // scope.
Mike Stump1eb44332009-09-09 15:08:12 +0000437 while (S->getEntity() &&
Douglas Gregor074149e2009-01-05 19:45:36 +0000438 ((DeclContext *)S->getEntity())->isTransparentContext())
439 S = S->getParent();
440
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000441 // Add scoped declarations into their context, so that they can be
442 // found later. Declarations without a context won't be inserted
443 // into any context.
John McCallab88d972009-08-31 22:39:49 +0000444 if (AddToContext)
445 CurContext->addDecl(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000446
Chandler Carruth8761d682010-02-21 07:08:09 +0000447 // Out-of-line definitions shouldn't be pushed into scope in C++.
448 // Out-of-line variable and function definitions shouldn't even in C.
449 if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
450 D->isOutOfLine())
451 return;
452
453 // Template instantiations should also not be pushed into scope.
454 if (isa<FunctionDecl>(D) &&
455 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregord04b1be2009-09-28 18:41:37 +0000456 return;
457
John McCallf36e02d2009-10-09 21:13:30 +0000458 // If this replaces anything in the current scope,
459 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
460 IEnd = IdResolver.end();
461 for (; I != IEnd; ++I) {
462 if (S->isDeclScope(DeclPtrTy::make(*I)) && D->declarationReplaces(*I)) {
463 S->RemoveDecl(DeclPtrTy::make(*I));
464 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000465
John McCallf36e02d2009-10-09 21:13:30 +0000466 // Should only need to replace one decl.
467 break;
Douglas Gregor516ff432009-04-24 02:57:34 +0000468 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000469 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000470
John McCallf36e02d2009-10-09 21:13:30 +0000471 S->AddDecl(DeclPtrTy::make(D));
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000472 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000473}
474
Douglas Gregor2531c2d2009-09-28 00:47:05 +0000475bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) {
Douglas Gregor2531c2d2009-09-28 00:47:05 +0000476 return IdResolver.isDeclInScope(D, Ctx, Context, S);
477}
478
John McCall68263142009-11-18 22:49:29 +0000479static bool isOutOfScopePreviousDeclaration(NamedDecl *,
480 DeclContext*,
481 ASTContext&);
482
483/// Filters out lookup results that don't fall within the given scope
484/// as determined by isDeclInScope.
485static void FilterLookupForScope(Sema &SemaRef, LookupResult &R,
486 DeclContext *Ctx, Scope *S,
487 bool ConsiderLinkage) {
488 LookupResult::Filter F = R.makeFilter();
489 while (F.hasNext()) {
490 NamedDecl *D = F.next();
491
492 if (SemaRef.isDeclInScope(D, Ctx, S))
493 continue;
494
495 if (ConsiderLinkage &&
496 isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context))
497 continue;
498
499 F.erase();
500 }
501
502 F.done();
503}
504
505static bool isUsingDecl(NamedDecl *D) {
506 return isa<UsingShadowDecl>(D) ||
507 isa<UnresolvedUsingTypenameDecl>(D) ||
508 isa<UnresolvedUsingValueDecl>(D);
509}
510
511/// Removes using shadow declarations from the lookup results.
512static void RemoveUsingDecls(LookupResult &R) {
513 LookupResult::Filter F = R.makeFilter();
514 while (F.hasNext())
515 if (isUsingDecl(F.next()))
516 F.erase();
517
518 F.done();
519}
520
Anders Carlsson99a000e2009-11-07 07:18:14 +0000521static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall86ff3082010-02-04 22:26:26 +0000522 if (D->isInvalidDecl())
523 return false;
524
Anders Carlssonf7613d52009-11-07 07:26:56 +0000525 if (D->isUsed() || D->hasAttr<UnusedAttr>())
526 return false;
John McCall86ff3082010-02-04 22:26:26 +0000527
528 // White-list anything that isn't a local variable.
529 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
530 !D->getDeclContext()->isFunctionOrMethod())
531 return false;
532
533 // Types of valid local variables should be complete, so this should succeed.
Anders Carlssonf7613d52009-11-07 07:26:56 +0000534 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
John McCallaec58602010-03-31 02:47:45 +0000535
536 // White-list anything with an __attribute__((unused)) type.
537 QualType Ty = VD->getType();
538
539 // Only look at the outermost level of typedef.
540 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
541 if (TT->getDecl()->hasAttr<UnusedAttr>())
542 return false;
543 }
544
Douglas Gregor5764f612010-05-08 23:05:03 +0000545 // If we failed to complete the type for some reason, or if the type is
546 // dependent, don't diagnose the variable.
547 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregora6a292b2010-04-27 16:20:13 +0000548 return false;
549
John McCallaec58602010-03-31 02:47:45 +0000550 if (const TagType *TT = Ty->getAs<TagType>()) {
551 const TagDecl *Tag = TT->getDecl();
552 if (Tag->hasAttr<UnusedAttr>())
553 return false;
554
555 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Douglas Gregor5764f612010-05-08 23:05:03 +0000556 // FIXME: Checking for the presence of a user-declared constructor
557 // isn't completely accurate; we'd prefer to check that the initializer
558 // has no side effects.
559 if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor())
Anders Carlssonf7613d52009-11-07 07:26:56 +0000560 return false;
561 }
562 }
John McCallaec58602010-03-31 02:47:45 +0000563
564 // TODO: __attribute__((unused)) templates?
Anders Carlssonf7613d52009-11-07 07:26:56 +0000565 }
566
John McCall86ff3082010-02-04 22:26:26 +0000567 return true;
Anders Carlsson99a000e2009-11-07 07:18:14 +0000568}
569
Douglas Gregor5764f612010-05-08 23:05:03 +0000570void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
571 if (!ShouldDiagnoseUnusedDecl(D))
572 return;
573
574 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
575 Diag(D->getLocation(), diag::warn_unused_exception_param)
576 << D->getDeclName();
577 else
578 Diag(D->getLocation(), diag::warn_unused_variable)
579 << D->getDeclName();
580}
581
Steve Naroffb216c882007-10-09 22:01:59 +0000582void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000583 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000584 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump1eb44332009-09-09 15:08:12 +0000585 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000586
Reid Spencer5f016e22007-07-11 17:01:13 +0000587 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
588 I != E; ++I) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000589 Decl *TmpD = (*I).getAs<Decl>();
Steve Naroffc752d042007-09-13 18:10:37 +0000590 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000591
Douglas Gregor44b43212008-12-11 16:49:14 +0000592 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
593 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000594
Douglas Gregor44b43212008-12-11 16:49:14 +0000595 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000596
Douglas Gregorb5352cf2009-10-08 21:35:42 +0000597 // Diagnose unused variables in this scope.
Douglas Gregor5764f612010-05-08 23:05:03 +0000598 if (S->getNumErrorsAtStart() == getDiagnostics().getNumErrors())
599 DiagnoseUnusedDecl(D);
600
Douglas Gregor44b43212008-12-11 16:49:14 +0000601 // Remove this name from our lexical scope.
602 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000603 }
604}
605
Douglas Gregorc83c6872010-04-15 22:33:43 +0000606/// \brief Look for an Objective-C class in the translation unit.
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000607///
Douglas Gregorc83c6872010-04-15 22:33:43 +0000608/// \param Id The name of the Objective-C class we're looking for. If
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000609/// typo-correction fixes this name, the Id will be updated
610/// to the fixed name.
611///
Douglas Gregorc83c6872010-04-15 22:33:43 +0000612/// \param IdLoc The location of the name in the translation unit.
613///
614/// \param TypoCorrection If true, this routine will attempt typo correction
615/// if there is no class with the given name.
616///
617/// \returns The declaration of the named Objective-C class, or NULL if the
618/// class could not be found.
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000619ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
Douglas Gregorc83c6872010-04-15 22:33:43 +0000620 SourceLocation IdLoc,
621 bool TypoCorrection) {
Steve Naroff31102512008-04-02 18:30:49 +0000622 // The third "scope" argument is 0 since we aren't enabling lazy built-in
623 // creation from this context.
Douglas Gregorc83c6872010-04-15 22:33:43 +0000624 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Douglas Gregorc83c6872010-04-15 22:33:43 +0000626 if (!IDecl && TypoCorrection) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000627 // Perform typo correction at the given location, but only if we
628 // find an Objective-C class name.
Douglas Gregorc83c6872010-04-15 22:33:43 +0000629 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000630 if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000631 (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000632 Diag(IdLoc, diag::err_undef_interface_suggest)
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000633 << Id << IDecl->getDeclName()
Douglas Gregorc83c6872010-04-15 22:33:43 +0000634 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000635 Diag(IDecl->getLocation(), diag::note_previous_decl)
636 << IDecl->getDeclName();
637
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000638 Id = IDecl->getIdentifier();
639 }
640 }
641
Steve Naroffb327ce02008-04-02 14:35:35 +0000642 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000643}
644
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000645/// getNonFieldDeclScope - Retrieves the innermost scope, starting
646/// from S, where a non-field would be declared. This routine copes
647/// with the difference between C and C++ scoping rules in structs and
648/// unions. For example, the following code is well-formed in C but
649/// ill-formed in C++:
650/// @code
651/// struct S6 {
652/// enum { BAR } e;
653/// };
Mike Stump1eb44332009-09-09 15:08:12 +0000654///
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000655/// void test_S6() {
656/// struct S6 a;
657/// a.e = BAR;
658/// }
659/// @endcode
660/// For the declaration of BAR, this routine will return a different
661/// scope. The scope S will be the scope of the unnamed enumeration
662/// within S6. In C++, this routine will return the scope associated
663/// with S6, because the enumeration's scope is a transparent
664/// context but structures can contain non-field names. In C, this
665/// routine will return the translation unit scope, since the
666/// enumeration's scope is a transparent context and structures cannot
667/// contain non-field names.
668Scope *Sema::getNonFieldDeclScope(Scope *S) {
669 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000670 (S->getEntity() &&
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000671 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
672 (S->isClassScope() && !getLangOptions().CPlusPlus))
673 S = S->getParent();
674 return S;
675}
676
Chris Lattner95e2c712008-05-05 22:18:14 +0000677void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000678 if (!Context.getBuiltinVaListType().isNull())
679 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000681 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Douglas Gregorc83c6872010-04-15 22:33:43 +0000682 NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, SourceLocation(),
683 LookupOrdinaryName, ForRedeclaration);
Steve Naroff733002f2007-10-18 22:17:45 +0000684 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000685 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
686}
687
Douglas Gregor3e41d602009-02-13 23:20:09 +0000688/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
689/// file scope. lazily create a decl for it. ForRedeclaration is true
690/// if we're creating this built-in in anticipation of redeclaring the
691/// built-in.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000692NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000693 Scope *S, bool ForRedeclaration,
694 SourceLocation Loc) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000695 Builtin::ID BID = (Builtin::ID)bid;
696
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000697 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000698 InitBuiltinVaListType();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000699
Chris Lattner86df27b2009-06-14 00:45:47 +0000700 ASTContext::GetBuiltinTypeError Error;
Mike Stump1eb44332009-09-09 15:08:12 +0000701 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000702 switch (Error) {
Chris Lattner86df27b2009-06-14 00:45:47 +0000703 case ASTContext::GE_None:
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000704 // Okay
705 break;
706
Mike Stumpf711c412009-07-28 23:57:15 +0000707 case ASTContext::GE_Missing_stdio:
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000708 if (ForRedeclaration)
709 Diag(Loc, diag::err_implicit_decl_requires_stdio)
710 << Context.BuiltinInfo.GetName(BID);
711 return 0;
Mike Stump782fa302009-07-28 02:25:19 +0000712
Mike Stumpf711c412009-07-28 23:57:15 +0000713 case ASTContext::GE_Missing_setjmp:
Mike Stump782fa302009-07-28 02:25:19 +0000714 if (ForRedeclaration)
715 Diag(Loc, diag::err_implicit_decl_requires_setjmp)
716 << Context.BuiltinInfo.GetName(BID);
717 return 0;
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000718 }
Douglas Gregor3e41d602009-02-13 23:20:09 +0000719
720 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
721 Diag(Loc, diag::ext_implicit_lib_function_decl)
722 << Context.BuiltinInfo.GetName(BID)
723 << R;
Douglas Gregorb1152d82009-02-16 21:58:21 +0000724 if (Context.BuiltinInfo.getHeaderName(BID) &&
Chris Lattner6a7334d2009-04-16 03:59:32 +0000725 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
726 != Diagnostic::Ignored)
Douglas Gregor3e41d602009-02-13 23:20:09 +0000727 Diag(Loc, diag::note_please_include_header)
728 << Context.BuiltinInfo.getHeaderName(BID)
729 << Context.BuiltinInfo.GetName(BID);
730 }
731
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000732 FunctionDecl *New = FunctionDecl::Create(Context,
733 Context.getTranslationUnitDecl(),
John McCalla93c9342009-12-07 02:54:59 +0000734 Loc, II, R, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000735 FunctionDecl::Extern,
736 FunctionDecl::None, false,
Douglas Gregor2224f842009-02-25 16:33:18 +0000737 /*hasPrototype=*/true);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000738 New->setImplicit();
739
Chris Lattner95e2c712008-05-05 22:18:14 +0000740 // Create Decl objects for each parameter, adding them to the
741 // FunctionDecl.
Douglas Gregor72564e72009-02-26 23:50:07 +0000742 if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner95e2c712008-05-05 22:18:14 +0000743 llvm::SmallVector<ParmVarDecl*, 16> Params;
744 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
745 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +0000746 FT->getArgType(i), /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000747 VarDecl::None, VarDecl::None, 0));
Douglas Gregor838db382010-02-11 01:19:42 +0000748 New->setParams(Params.data(), Params.size());
Chris Lattner95e2c712008-05-05 22:18:14 +0000749 }
Mike Stump1eb44332009-09-09 15:08:12 +0000750
751 AddKnownFunctionAttributes(New);
752
Chris Lattner7f925cc2008-04-11 07:00:53 +0000753 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000754 // FIXME: This is hideous. We need to teach PushOnScopeChains to
755 // relate Scopes to DeclContexts, and probably eliminate CurContext
756 // entirely, but we're not there yet.
757 DeclContext *SavedContext = CurContext;
758 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000759 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000760 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 return New;
762}
763
Douglas Gregorcda9c672009-02-16 17:45:42 +0000764/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
765/// same name and scope as a previous declaration 'Old'. Figure out
766/// how to resolve this situation, merging decls or emitting
Chris Lattnereaaebc72009-04-25 08:06:05 +0000767/// diagnostics as appropriate. If there was an error, set New to be invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +0000768///
John McCall68263142009-11-18 22:49:29 +0000769void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) {
770 // If the new decl is known invalid already, don't bother doing any
771 // merging checks.
772 if (New->isInvalidDecl()) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Steve Naroff2b255c42008-09-09 14:32:20 +0000774 // Allow multiple definitions for ObjC built-in typedefs.
775 // FIXME: Verify the underlying types are equivalent!
776 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000777 const IdentifierInfo *TypeID = New->getIdentifier();
778 switch (TypeID->getLength()) {
779 default: break;
Mike Stump1eb44332009-09-09 15:08:12 +0000780 case 2:
Chris Lattner2bac0f62008-11-20 05:41:43 +0000781 if (!TypeID->isStr("id"))
782 break;
David Chisnall0f436562009-08-17 16:35:33 +0000783 Context.ObjCIdRedefinitionType = New->getUnderlyingType();
Steve Naroff14108da2009-07-10 23:34:53 +0000784 // Install the built-in type for 'id', ignoring the current definition.
785 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
786 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000787 case 5:
788 if (!TypeID->isStr("Class"))
789 break;
David Chisnall0f436562009-08-17 16:35:33 +0000790 Context.ObjCClassRedefinitionType = New->getUnderlyingType();
Steve Naroff14108da2009-07-10 23:34:53 +0000791 // Install the built-in type for 'Class', ignoring the current definition.
792 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +0000793 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000794 case 3:
795 if (!TypeID->isStr("SEL"))
796 break;
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +0000797 Context.ObjCSelRedefinitionType = New->getUnderlyingType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000798 // Install the built-in type for 'SEL', ignoring the current definition.
799 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +0000800 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000801 case 8:
802 if (!TypeID->isStr("Protocol"))
803 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000804 Context.setObjCProtoType(New->getUnderlyingType());
Chris Lattnereaaebc72009-04-25 08:06:05 +0000805 return;
Steve Naroff2b255c42008-09-09 14:32:20 +0000806 }
807 // Fall through - the typedef name was not a builtin type.
808 }
John McCall68263142009-11-18 22:49:29 +0000809
Douglas Gregor66973122009-01-28 17:15:10 +0000810 // Verify the old decl was also a type.
John McCall5126fd02009-12-30 00:31:22 +0000811 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
812 if (!Old) {
Mike Stump1eb44332009-09-09 15:08:12 +0000813 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000814 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +0000815
816 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000817 if (OldD->getLocation().isValid())
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000818 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall68263142009-11-18 22:49:29 +0000819
Chris Lattnereaaebc72009-04-25 08:06:05 +0000820 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000821 }
Douglas Gregor66973122009-01-28 17:15:10 +0000822
John McCall68263142009-11-18 22:49:29 +0000823 // If the old declaration is invalid, just give up here.
824 if (Old->isInvalidDecl())
825 return New->setInvalidDecl();
826
Mike Stump1eb44332009-09-09 15:08:12 +0000827 // Determine the "old" type we'll use for checking and diagnostics.
Douglas Gregor66973122009-01-28 17:15:10 +0000828 QualType OldType;
829 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
830 OldType = OldTypedef->getUnderlyingType();
831 else
832 OldType = Context.getTypeDeclType(Old);
833
Chris Lattner99cb9972008-07-25 18:44:27 +0000834 // If the typedef types are not identical, reject them in all languages and
835 // with any extensions enabled.
Douglas Gregor66973122009-01-28 17:15:10 +0000836
Mike Stump1eb44332009-09-09 15:08:12 +0000837 if (OldType != New->getUnderlyingType() &&
838 Context.getCanonicalType(OldType) !=
Chris Lattner99cb9972008-07-25 18:44:27 +0000839 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000840 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregor66973122009-01-28 17:15:10 +0000841 << New->getUnderlyingType() << OldType;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000842 if (Old->getLocation().isValid())
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000843 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000844 return New->setInvalidDecl();
Chris Lattner99cb9972008-07-25 18:44:27 +0000845 }
Mike Stump1eb44332009-09-09 15:08:12 +0000846
John McCall5126fd02009-12-30 00:31:22 +0000847 // The types match. Link up the redeclaration chain if the old
848 // declaration was a typedef.
849 // FIXME: this is a potential source of wierdness if the type
850 // spellings don't match exactly.
851 if (isa<TypedefDecl>(Old))
852 New->setPreviousDeclaration(cast<TypedefDecl>(Old));
853
Steve Naroff14108da2009-07-10 23:34:53 +0000854 if (getLangOptions().Microsoft)
Chris Lattnereaaebc72009-04-25 08:06:05 +0000855 return;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000856
Chris Lattner32b06752009-04-17 22:04:20 +0000857 if (getLangOptions().CPlusPlus) {
Douglas Gregor93dda722010-01-11 21:54:40 +0000858 // C++ [dcl.typedef]p2:
859 // In a given non-class scope, a typedef specifier can be used to
860 // redefine the name of any type declared in that scope to refer
861 // to the type to which it already refers.
Chris Lattner32b06752009-04-17 22:04:20 +0000862 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnereaaebc72009-04-25 08:06:05 +0000863 return;
Douglas Gregor93dda722010-01-11 21:54:40 +0000864
865 // C++0x [dcl.typedef]p4:
866 // In a given class scope, a typedef specifier can be used to redefine
867 // any class-name declared in that scope that is not also a typedef-name
868 // to refer to the type to which it already refers.
869 //
870 // This wording came in via DR424, which was a correction to the
871 // wording in DR56, which accidentally banned code like:
872 //
873 // struct S {
874 // typedef struct A { } A;
875 // };
876 //
877 // in the C++03 standard. We implement the C++0x semantics, which
878 // allow the above but disallow
879 //
880 // struct S {
881 // typedef int I;
882 // typedef int I;
883 // };
884 //
885 // since that was the intent of DR56.
Douglas Gregor05f65002010-01-11 22:30:10 +0000886 if (!isa<TypedefDecl >(Old))
Douglas Gregor93dda722010-01-11 21:54:40 +0000887 return;
888
Chris Lattner32b06752009-04-17 22:04:20 +0000889 Diag(New->getLocation(), diag::err_redefinition)
890 << New->getDeclName();
891 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000892 return New->setInvalidDecl();
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000893 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000894
Chris Lattner32b06752009-04-17 22:04:20 +0000895 // If we have a redefinition of a typedef in C, emit a warning. This warning
896 // is normally mapped to an error, but can be controlled with
Eli Friedman340a4e52009-06-04 23:03:07 +0000897 // -Wtypedef-redefinition. If either the original or the redefinition is
898 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner6d97e5e2010-03-01 20:59:53 +0000899 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman340a4e52009-06-04 23:03:07 +0000900 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
901 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattnerd0359af2009-04-27 01:46:12 +0000902 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Chris Lattner32b06752009-04-17 22:04:20 +0000904 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
905 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000906 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000907 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000908}
909
Chris Lattner6b6b5372008-06-26 18:38:35 +0000910/// DeclhasAttr - returns true if decl Declaration already has the target
911/// attribute.
Mike Stump1eb44332009-09-09 15:08:12 +0000912static bool
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000913DeclHasAttr(const Decl *decl, const Attr *target) {
914 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
Chris Lattnerddee4232008-03-03 03:28:21 +0000915 if (attr->getKind() == target->getKind())
916 return true;
917
918 return false;
919}
920
921/// MergeAttributes - append attributes from the Old decl to the New one.
Chris Lattnercc581472009-03-04 06:05:19 +0000922static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000923 for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
924 if (!DeclHasAttr(New, attr) && attr->isMerged()) {
Douglas Gregor9f9bf252009-04-28 06:37:30 +0000925 Attr *NewAttr = attr->clone(C);
926 NewAttr->setInherited(true);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000927 New->addAttr(NewAttr);
Chris Lattnerddee4232008-03-03 03:28:21 +0000928 }
929 }
930}
931
Douglas Gregorc8376562009-03-06 22:43:54 +0000932/// Used in MergeFunctionDecl to keep track of function parameters in
933/// C.
934struct GNUCompatibleParamWarning {
935 ParmVarDecl *OldParm;
936 ParmVarDecl *NewParm;
937 QualType PromotedType;
938};
939
Anders Carlsson5c478cf2009-12-04 22:33:25 +0000940
941/// getSpecialMember - get the special member enum for a method.
Anders Carlsson3b8c53b2010-04-22 05:40:53 +0000942Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +0000943 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000944 if (Ctor->isCopyConstructor())
Anders Carlsson5c478cf2009-12-04 22:33:25 +0000945 return Sema::CXXCopyConstructor;
Anders Carlsson3b8c53b2010-04-22 05:40:53 +0000946
947 return Sema::CXXConstructor;
Anders Carlsson5c478cf2009-12-04 22:33:25 +0000948 }
949
950 if (isa<CXXDestructorDecl>(MD))
951 return Sema::CXXDestructor;
952
953 assert(MD->isCopyAssignment() && "Must have copy assignment operator");
954 return Sema::CXXCopyAssignment;
955}
956
Sebastian Redl515ddd82010-06-09 21:17:41 +0000957/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisf3f8d2a2010-02-18 02:00:42 +0000958/// only extern inline functions can be redefined, and even then only in
959/// GNU89 mode.
960static bool canRedefineFunction(const FunctionDecl *FD,
961 const LangOptions& LangOpts) {
962 return (LangOpts.GNUMode && !LangOpts.C99 && !LangOpts.CPlusPlus &&
963 FD->isInlineSpecified() &&
964 FD->getStorageClass() == FunctionDecl::Extern);
965}
966
Chris Lattner04421082008-04-08 04:40:51 +0000967/// MergeFunctionDecl - We just parsed a function 'New' from
968/// declarator D which has the same name and scope as a previous
969/// declaration 'Old'. Figure out how to resolve this situation,
970/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000971///
972/// In C++, New and Old must be declarations that are not
973/// overloaded. Use IsOverload to determine whether New and Old are
974/// overloaded, and to select the Old declaration that New should be
975/// merged with.
Douglas Gregorcda9c672009-02-16 17:45:42 +0000976///
977/// Returns true if there was an error, false otherwise.
978bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000979 // Verify the old decl was also a function.
Douglas Gregore53060f2009-06-25 22:08:12 +0000980 FunctionDecl *Old = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000981 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregore53060f2009-06-25 22:08:12 +0000982 = dyn_cast<FunctionTemplateDecl>(OldD))
983 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000984 else
Douglas Gregore53060f2009-06-25 22:08:12 +0000985 Old = dyn_cast<FunctionDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000986 if (!Old) {
John McCall41ce66f2009-12-10 19:51:03 +0000987 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
988 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
989 Diag(Shadow->getTargetDecl()->getLocation(),
990 diag::note_using_decl_target);
991 Diag(Shadow->getUsingDecl()->getLocation(),
992 diag::note_using_decl) << 0;
993 return true;
994 }
995
Chris Lattner5dc266a2008-11-20 06:13:02 +0000996 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000997 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000998 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000999 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001000 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001001
1002 // Determine whether the previous declaration was a definition,
1003 // implicit declaration, or a declaration.
1004 diag::kind PrevDiag;
1005 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +00001006 PrevDiag = diag::note_previous_definition;
Douglas Gregorcda9c672009-02-16 17:45:42 +00001007 else if (Old->isImplicit())
1008 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00001009 else
Chris Lattner5f4a6822008-11-23 23:12:31 +00001010 PrevDiag = diag::note_previous_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Chris Lattner8bcfc5b2008-04-06 23:10:54 +00001012 QualType OldQType = Context.getCanonicalType(Old->getType());
1013 QualType NewQType = Context.getCanonicalType(New->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Charles Davisf3f8d2a2010-02-18 02:00:42 +00001015 // Don't complain about this if we're in GNU89 mode and the old function
1016 // is an extern inline function.
Douglas Gregor04495c82009-02-24 01:23:02 +00001017 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
1018 New->getStorageClass() == FunctionDecl::Static &&
Charles Davisf3f8d2a2010-02-18 02:00:42 +00001019 Old->getStorageClass() != FunctionDecl::Static &&
1020 !canRedefineFunction(Old, getLangOptions())) {
Douglas Gregor04495c82009-02-24 01:23:02 +00001021 Diag(New->getLocation(), diag::err_static_non_static)
1022 << New;
1023 Diag(Old->getLocation(), PrevDiag);
1024 return true;
1025 }
1026
John McCallf82b4e82010-02-04 05:44:44 +00001027 // If a function is first declared with a calling convention, but is
1028 // later declared or defined without one, the second decl assumes the
1029 // calling convention of the first.
1030 //
1031 // For the new decl, we have to look at the NON-canonical type to tell the
1032 // difference between a function that really doesn't have a calling
1033 // convention and one that is declared cdecl. That's because in
1034 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1035 // because it is the default calling convention.
1036 //
1037 // Note also that we DO NOT return at this point, because we still have
1038 // other tests to run.
1039 const FunctionType *OldType = OldQType->getAs<FunctionType>();
1040 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
Rafael Espindola264ba482010-03-30 20:24:48 +00001041 const FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1042 const FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1043 if (OldTypeInfo.getCC() != CC_Default &&
1044 NewTypeInfo.getCC() == CC_Default) {
1045 NewQType = Context.getCallConvType(NewQType, OldTypeInfo.getCC());
John McCallf82b4e82010-02-04 05:44:44 +00001046 New->setType(NewQType);
1047 NewQType = Context.getCanonicalType(NewQType);
Rafael Espindola264ba482010-03-30 20:24:48 +00001048 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1049 NewTypeInfo.getCC())) {
John McCallf82b4e82010-02-04 05:44:44 +00001050 // Calling conventions really aren't compatible, so complain.
John McCall04a67a62010-02-05 21:31:56 +00001051 Diag(New->getLocation(), diag::err_cconv_change)
Rafael Espindola264ba482010-03-30 20:24:48 +00001052 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1053 << (OldTypeInfo.getCC() == CC_Default)
1054 << (OldTypeInfo.getCC() == CC_Default ? "" :
1055 FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
John McCall04a67a62010-02-05 21:31:56 +00001056 Diag(Old->getLocation(), diag::note_previous_declaration);
John McCallf82b4e82010-02-04 05:44:44 +00001057 return true;
1058 }
1059
John McCall04a67a62010-02-05 21:31:56 +00001060 // FIXME: diagnose the other way around?
Douglas Gregord2c64902010-06-18 21:30:25 +00001061 if (OldType->getNoReturnAttr() && !NewType->getNoReturnAttr()) {
John McCall04a67a62010-02-05 21:31:56 +00001062 NewQType = Context.getNoReturnType(NewQType);
1063 New->setType(NewQType);
1064 assert(NewQType.isCanonical());
1065 }
1066
Douglas Gregord2c64902010-06-18 21:30:25 +00001067 // Merge regparm attribute.
1068 if (OldType->getRegParmType() != NewType->getRegParmType()) {
1069 if (NewType->getRegParmType()) {
1070 Diag(New->getLocation(), diag::err_regparm_mismatch)
1071 << NewType->getRegParmType()
1072 << OldType->getRegParmType();
1073 Diag(Old->getLocation(), diag::note_previous_declaration);
1074 return true;
1075 }
1076
1077 NewQType = Context.getRegParmType(NewQType, OldType->getRegParmType());
1078 New->setType(NewQType);
1079 assert(NewQType.isCanonical());
1080 }
1081
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001082 if (getLangOptions().CPlusPlus) {
1083 // (C++98 13.1p2):
1084 // Certain function declarations cannot be overloaded:
Mike Stump1eb44332009-09-09 15:08:12 +00001085 // -- Function declarations that differ only in the return type
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001086 // cannot be overloaded.
Mike Stump1eb44332009-09-09 15:08:12 +00001087 QualType OldReturnType
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001088 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001089 QualType NewReturnType
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001090 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
Fariborz Jahanian2390a722010-05-19 21:37:30 +00001091 QualType ResQT;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001092 if (OldReturnType != NewReturnType) {
Fariborz Jahanian2390a722010-05-19 21:37:30 +00001093 if (NewReturnType->isObjCObjectPointerType()
1094 && OldReturnType->isObjCObjectPointerType())
1095 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1096 if (ResQT.isNull()) {
1097 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
1098 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1099 return true;
1100 }
1101 else
1102 NewQType = ResQT;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001103 }
1104
1105 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
John McCall3d043362010-04-13 07:45:41 +00001106 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001107 if (OldMethod && NewMethod) {
John McCall3d043362010-04-13 07:45:41 +00001108 // Preserve triviality.
1109 NewMethod->setTrivial(OldMethod->isTrivial());
1110
1111 bool isFriend = NewMethod->getFriendObjectKind();
1112
1113 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord()) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001114 // -- Member function declarations with the same name and the
1115 // same parameter types cannot be overloaded if any of them
1116 // is a static member function declaration.
1117 if (OldMethod->isStatic() || NewMethod->isStatic()) {
1118 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1119 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1120 return true;
1121 }
1122
1123 // C++ [class.mem]p1:
1124 // [...] A member shall not be declared twice in the
1125 // member-specification, except that a nested class or member
1126 // class template can be declared and then later defined.
1127 unsigned NewDiag;
1128 if (isa<CXXConstructorDecl>(OldMethod))
1129 NewDiag = diag::err_constructor_redeclared;
1130 else if (isa<CXXDestructorDecl>(NewMethod))
1131 NewDiag = diag::err_destructor_redeclared;
1132 else if (isa<CXXConversionDecl>(NewMethod))
1133 NewDiag = diag::err_conv_function_redeclared;
1134 else
1135 NewDiag = diag::err_member_redeclared;
1136
1137 Diag(New->getLocation(), NewDiag);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001138 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall3d043362010-04-13 07:45:41 +00001139
1140 // Complain if this is an explicit declaration of a special
1141 // member that was initially declared implicitly.
1142 //
1143 // As an exception, it's okay to befriend such methods in order
1144 // to permit the implicit constructor/destructor/operator calls.
1145 } else if (OldMethod->isImplicit()) {
1146 if (isFriend) {
1147 NewMethod->setImplicit();
1148 } else {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001149 Diag(NewMethod->getLocation(),
1150 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00001151 << New << getSpecialMember(OldMethod);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001152 return true;
1153 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001154 }
1155 }
1156
1157 // (C++98 8.3.5p3):
1158 // All declarations for a function shall agree exactly in both the
1159 // return type and the parameter-type-list.
Nuno Lopesf75b8302009-12-23 23:40:33 +00001160 // attributes should be ignored when comparing.
1161 if (Context.getNoReturnType(OldQType, false) ==
1162 Context.getNoReturnType(NewQType, false))
Douglas Gregor04495c82009-02-24 01:23:02 +00001163 return MergeCompatibleFunctionDecls(New, Old);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001164
1165 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +00001166 }
Chris Lattner04421082008-04-08 04:40:51 +00001167
1168 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001169 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +00001170 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +00001171 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall183700f2009-09-21 23:43:11 +00001172 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1173 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001174 const FunctionProtoType *OldProto = 0;
1175 if (isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregorc8376562009-03-06 22:43:54 +00001176 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregor68719812009-02-16 18:20:44 +00001177 // The old declaration provided a function prototype, but the
1178 // new declaration does not. Merge in the prototype.
Sebastian Redl465226e2009-05-27 22:11:52 +00001179 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Douglas Gregor68719812009-02-16 18:20:44 +00001180 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1181 OldProto->arg_type_end());
1182 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001183 ParamTypes.data(), ParamTypes.size(),
Douglas Gregor68719812009-02-16 18:20:44 +00001184 OldProto->isVariadic(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00001185 OldProto->getTypeQuals(),
1186 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001187 OldProto->getExtInfo());
Douglas Gregor68719812009-02-16 18:20:44 +00001188 New->setType(NewQType);
Anders Carlssona75e8532009-05-14 21:46:00 +00001189 New->setHasInheritedPrototype();
Douglas Gregor450da982009-02-16 20:58:07 +00001190
1191 // Synthesize a parameter for each argument type.
1192 llvm::SmallVector<ParmVarDecl*, 16> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00001193 for (FunctionProtoType::arg_type_iterator
1194 ParamType = OldProto->arg_type_begin(),
Douglas Gregor450da982009-02-16 20:58:07 +00001195 ParamEnd = OldProto->arg_type_end();
1196 ParamType != ParamEnd; ++ParamType) {
1197 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
1198 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00001199 *ParamType, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001200 VarDecl::None, VarDecl::None,
1201 0);
Douglas Gregor450da982009-02-16 20:58:07 +00001202 Param->setImplicit();
1203 Params.push_back(Param);
1204 }
1205
Douglas Gregor838db382010-02-11 01:19:42 +00001206 New->setParams(Params.data(), Params.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001207 }
Douglas Gregor68719812009-02-16 18:20:44 +00001208
Douglas Gregor04495c82009-02-24 01:23:02 +00001209 return MergeCompatibleFunctionDecls(New, Old);
Chris Lattner04421082008-04-08 04:40:51 +00001210 }
Chris Lattnere3995fe2007-11-06 06:07:26 +00001211
Douglas Gregorc8376562009-03-06 22:43:54 +00001212 // GNU C permits a K&R definition to follow a prototype declaration
1213 // if the declared types of the parameters in the K&R definition
1214 // match the types in the prototype declaration, even when the
1215 // promoted types of the parameters from the K&R definition differ
1216 // from the types in the prototype. GCC then keeps the types from
1217 // the prototype.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001218 //
1219 // If a variadic prototype is followed by a non-variadic K&R definition,
1220 // the K&R definition becomes variadic. This is sort of an edge case, but
1221 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1222 // C99 6.9.1p8.
Douglas Gregorc8376562009-03-06 22:43:54 +00001223 if (!getLangOptions().CPlusPlus &&
Douglas Gregorc8376562009-03-06 22:43:54 +00001224 Old->hasPrototype() && !New->hasPrototype() &&
John McCall183700f2009-09-21 23:43:11 +00001225 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregorc8376562009-03-06 22:43:54 +00001226 Old->getNumParams() == New->getNumParams()) {
1227 llvm::SmallVector<QualType, 16> ArgTypes;
1228 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump1eb44332009-09-09 15:08:12 +00001229 const FunctionProtoType *OldProto
John McCall183700f2009-09-21 23:43:11 +00001230 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001231 const FunctionProtoType *NewProto
John McCall183700f2009-09-21 23:43:11 +00001232 = New->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001233
Douglas Gregorc8376562009-03-06 22:43:54 +00001234 // Determine whether this is the GNU C extension.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001235 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1236 NewProto->getResultType());
1237 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump1eb44332009-09-09 15:08:12 +00001238 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001239 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregorc8376562009-03-06 22:43:54 +00001240 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1241 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump1eb44332009-09-09 15:08:12 +00001242 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregorc8376562009-03-06 22:43:54 +00001243 NewProto->getArgType(Idx))) {
1244 ArgTypes.push_back(NewParm->getType());
1245 } else if (Context.typesAreCompatible(OldParm->getType(),
1246 NewParm->getType())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001247 GNUCompatibleParamWarning Warn
Douglas Gregorc8376562009-03-06 22:43:54 +00001248 = { OldParm, NewParm, NewProto->getArgType(Idx) };
1249 Warnings.push_back(Warn);
1250 ArgTypes.push_back(NewParm->getType());
1251 } else
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001252 LooseCompatible = false;
Douglas Gregorc8376562009-03-06 22:43:54 +00001253 }
1254
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001255 if (LooseCompatible) {
Douglas Gregorc8376562009-03-06 22:43:54 +00001256 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1257 Diag(Warnings[Warn].NewParm->getLocation(),
1258 diag::ext_param_promoted_not_compatible_with_prototype)
1259 << Warnings[Warn].PromotedType
1260 << Warnings[Warn].OldParm->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001261 Diag(Warnings[Warn].OldParm->getLocation(),
Douglas Gregorc8376562009-03-06 22:43:54 +00001262 diag::note_previous_declaration);
1263 }
1264
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001265 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1266 ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00001267 OldProto->isVariadic(), 0,
1268 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001269 OldProto->getExtInfo()));
Douglas Gregorc8376562009-03-06 22:43:54 +00001270 return MergeCompatibleFunctionDecls(New, Old);
1271 }
1272
1273 // Fall through to diagnose conflicting types.
1274 }
1275
Steve Naroff837618c2008-01-16 15:01:34 +00001276 // A function that has already been declared has been redeclared or defined
1277 // with a different type- show appropriate diagnostic
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001278 if (unsigned BuiltinID = Old->getBuiltinID()) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00001279 // The user has declared a builtin function with an incompatible
1280 // signature.
1281 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1282 // The function the user is redeclaring is a library-defined
1283 // function like 'malloc' or 'printf'. Warn about the
Douglas Gregor374e1562009-03-23 17:47:24 +00001284 // redeclaration, then pretend that we don't know about this
1285 // library built-in.
Douglas Gregorcda9c672009-02-16 17:45:42 +00001286 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1287 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1288 << Old << Old->getType();
Douglas Gregor374e1562009-03-23 17:47:24 +00001289 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1290 Old->setInvalidDecl();
1291 return false;
Douglas Gregorcda9c672009-02-16 17:45:42 +00001292 }
Steve Naroff837618c2008-01-16 15:01:34 +00001293
Douglas Gregorcda9c672009-02-16 17:45:42 +00001294 PrevDiag = diag::note_previous_builtin_declaration;
1295 }
1296
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001297 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregor3e41d602009-02-13 23:20:09 +00001298 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +00001299 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001300}
1301
Douglas Gregor04495c82009-02-24 01:23:02 +00001302/// \brief Completes the merge of two function declarations that are
Mike Stump1eb44332009-09-09 15:08:12 +00001303/// known to be compatible.
Douglas Gregor04495c82009-02-24 01:23:02 +00001304///
1305/// This routine handles the merging of attributes and other
1306/// properties of function declarations form the old declaration to
1307/// the new declaration, once we know that New is in fact a
1308/// redeclaration of Old.
1309///
1310/// \returns false
1311bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1312 // Merge the attributes
Chris Lattnercc581472009-03-04 06:05:19 +00001313 MergeAttributes(New, Old, Context);
Douglas Gregor04495c82009-02-24 01:23:02 +00001314
1315 // Merge the storage class.
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001316 if (Old->getStorageClass() != FunctionDecl::Extern &&
1317 Old->getStorageClass() != FunctionDecl::None)
Douglas Gregor9f9bf252009-04-28 06:37:30 +00001318 New->setStorageClass(Old->getStorageClass());
Douglas Gregor04495c82009-02-24 01:23:02 +00001319
Douglas Gregor04495c82009-02-24 01:23:02 +00001320 // Merge "pure" flag.
1321 if (Old->isPure())
1322 New->setPure();
1323
1324 // Merge the "deleted" flag.
1325 if (Old->isDeleted())
1326 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001327
Douglas Gregor04495c82009-02-24 01:23:02 +00001328 if (getLangOptions().CPlusPlus)
1329 return MergeCXXFunctionDecl(New, Old);
1330
1331 return false;
1332}
1333
Reid Spencer5f016e22007-07-11 17:01:13 +00001334/// MergeVarDecl - We just parsed a variable 'New' which has the same name
1335/// and scope as a previous declaration 'Old'. Figure out how to resolve this
1336/// situation, merging decls or emitting diagnostics as appropriate.
1337///
Mike Stump1eb44332009-09-09 15:08:12 +00001338/// Tentative definition rules (C99 6.9.2p2) are checked by
1339/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001340/// definitions here, since the initializer hasn't been attached.
Mike Stump1eb44332009-09-09 15:08:12 +00001341///
John McCall68263142009-11-18 22:49:29 +00001342void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
1343 // If the new decl is already invalid, don't do any other checking.
1344 if (New->isInvalidDecl())
1345 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001346
Reid Spencer5f016e22007-07-11 17:01:13 +00001347 // Verify the old decl was also a variable.
John McCall68263142009-11-18 22:49:29 +00001348 VarDecl *Old = 0;
1349 if (!Previous.isSingleResult() ||
1350 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001351 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00001352 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00001353 Diag(Previous.getRepresentativeDecl()->getLocation(),
1354 diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001355 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 }
Chris Lattnerddee4232008-03-03 03:28:21 +00001357
Chris Lattnercc581472009-03-04 06:05:19 +00001358 MergeAttributes(New, Old, Context);
Chris Lattnerddee4232008-03-03 03:28:21 +00001359
Eli Friedman13ca96a2009-01-24 23:49:55 +00001360 // Merge the types
Eli Friedman88d936b2009-05-16 13:54:38 +00001361 QualType MergedT;
1362 if (getLangOptions().CPlusPlus) {
1363 if (Context.hasSameType(New->getType(), Old->getType()))
1364 MergedT = New->getType();
Eli Friedman153c33e2009-12-10 08:54:47 +00001365 // C++ [basic.link]p10:
1366 // [...] the types specified by all declarations referring to a given
1367 // object or function shall be identical, except that declarations for an
1368 // array object can specify array types that differ by the presence or
1369 // absence of a major array bound (8.3.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001370 else if (Old->getType()->isIncompleteArrayType() &&
Douglas Gregor8dfb7ec2009-09-09 06:04:29 +00001371 New->getType()->isArrayType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001372 CanQual<ArrayType> OldArray
Douglas Gregor8dfb7ec2009-09-09 06:04:29 +00001373 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001374 CanQual<ArrayType> NewArray
Douglas Gregor8dfb7ec2009-09-09 06:04:29 +00001375 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1376 if (OldArray->getElementType() == NewArray->getElementType())
1377 MergedT = New->getType();
Eli Friedman153c33e2009-12-10 08:54:47 +00001378 } else if (Old->getType()->isArrayType() &&
1379 New->getType()->isIncompleteArrayType()) {
1380 CanQual<ArrayType> OldArray
1381 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1382 CanQual<ArrayType> NewArray
1383 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1384 if (OldArray->getElementType() == NewArray->getElementType())
1385 MergedT = Old->getType();
Fariborz Jahanian2390a722010-05-19 21:37:30 +00001386 } else if (New->getType()->isObjCObjectPointerType()
1387 && Old->getType()->isObjCObjectPointerType()) {
1388 MergedT = Context.mergeObjCGCQualifiers(New->getType(), Old->getType());
Douglas Gregor8dfb7ec2009-09-09 06:04:29 +00001389 }
Eli Friedman88d936b2009-05-16 13:54:38 +00001390 } else {
1391 MergedT = Context.mergeTypes(New->getType(), Old->getType());
1392 }
Eli Friedman13ca96a2009-01-24 23:49:55 +00001393 if (MergedT.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001394 Diag(New->getLocation(), diag::err_redefinition_different_type)
Douglas Gregor6037fcb2009-01-09 19:42:16 +00001395 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001396 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001397 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001398 }
Eli Friedman13ca96a2009-01-24 23:49:55 +00001399 New->setType(MergedT);
Douglas Gregor656de632009-03-11 23:52:16 +00001400
Steve Naroffb7b032e2008-01-30 00:44:01 +00001401 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
1402 if (New->getStorageClass() == VarDecl::Static &&
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00001403 (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001404 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001405 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001406 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00001407 }
Mike Stump1eb44332009-09-09 15:08:12 +00001408 // C99 6.2.2p4:
Douglas Gregor5ef122e2009-03-19 22:01:50 +00001409 // For an identifier declared with the storage-class specifier
1410 // extern in a scope in which a prior declaration of that
1411 // identifier is visible,23) if the prior declaration specifies
1412 // internal or external linkage, the linkage of the identifier at
1413 // the later declaration is the same as the linkage specified at
1414 // the prior declaration. If no prior declaration is visible, or
1415 // if the prior declaration specifies no linkage, then the
1416 // identifier has external linkage.
Douglas Gregor38179b22009-03-23 16:17:01 +00001417 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor5ef122e2009-03-19 22:01:50 +00001418 /* Okay */;
1419 else if (New->getStorageClass() != VarDecl::Static &&
1420 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001421 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001422 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001423 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00001424 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00001425
Steve Naroff094cefb2008-09-17 14:05:40 +00001426 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00001428 // FIXME: The test for external storage here seems wrong? We still
1429 // need to check for mismatches.
1430 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor656de632009-03-11 23:52:16 +00001431 // Don't complain about out-of-line definitions of static members.
1432 !(Old->getLexicalDeclContext()->isRecord() &&
1433 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattner08631c52008-11-23 21:45:46 +00001434 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001435 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001436 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001437 }
Douglas Gregor275a3692009-03-10 23:43:53 +00001438
Eli Friedman63054b32009-04-19 20:27:55 +00001439 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1440 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1441 Diag(Old->getLocation(), diag::note_previous_definition);
1442 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1443 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1444 Diag(Old->getLocation(), diag::note_previous_definition);
1445 }
1446
Sebastian Redl4cae1b32010-02-02 18:35:11 +00001447 // C++ doesn't have tentative definitions, so go right ahead and check here.
1448 const VarDecl *Def;
Sebastian Redl6c048a92010-02-03 02:08:48 +00001449 if (getLangOptions().CPlusPlus &&
1450 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redl4cae1b32010-02-02 18:35:11 +00001451 (Def = Old->getDefinition())) {
1452 Diag(New->getLocation(), diag::err_redefinition)
1453 << New->getDeclName();
1454 Diag(Def->getLocation(), diag::note_previous_definition);
1455 New->setInvalidDecl();
1456 return;
1457 }
Fariborz Jahanianfba9e8f2010-06-25 00:05:45 +00001458 // c99 6.2.2 P4.
1459 // For an identifier declared with the storage-class specifier extern in a
1460 // scope in which a prior declaration of that identifier is visible, if
1461 // the prior declaration specifies internal or external linkage, the linkage
1462 // of the identifier at the later declaration is the same as the linkage
1463 // specified at the prior declaration.
1464 // FIXME. revisit this code.
Fariborz Jahanian2bf6d7b2010-06-21 16:08:37 +00001465 if (New->hasExternalStorage() &&
Fariborz Jahanian7d99e982010-06-24 18:50:41 +00001466 Old->getLinkage() == InternalLinkage &&
1467 New->getDeclContext() == Old->getDeclContext())
Fariborz Jahanian2bf6d7b2010-06-21 16:08:37 +00001468 New->setStorageClass(Old->getStorageClass());
1469
Douglas Gregor275a3692009-03-10 23:43:53 +00001470 // Keep a chain of previous declarations.
1471 New->setPreviousDeclaration(Old);
John McCall46460a62010-01-20 21:53:11 +00001472
1473 // Inherit access appropriately.
1474 New->setAccess(Old->getAccess());
Reid Spencer5f016e22007-07-11 17:01:13 +00001475}
1476
1477/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1478/// no declarator (e.g. "struct foo;") is parsed.
John McCallaec03712010-05-21 20:45:30 +00001479Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1480 DeclSpec &DS) {
Eli Friedmand2968362009-04-09 21:26:42 +00001481 // FIXME: Error on auto/register at file scope
1482 // FIXME: Error on inline/virtual/explicit
Eli Friedman63054b32009-04-19 20:27:55 +00001483 // FIXME: Warn on useless __thread
Eli Friedmand2968362009-04-09 21:26:42 +00001484 // FIXME: Warn on useless const/volatile
1485 // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1486 // FIXME: Warn on useless attributes
John McCalle3af0232009-10-07 23:34:25 +00001487 Decl *TagD = 0;
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001488 TagDecl *Tag = 0;
1489 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1490 DS.getTypeSpecType() == DeclSpec::TST_struct ||
1491 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00001492 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCalle3af0232009-10-07 23:34:25 +00001493 TagD = static_cast<Decl *>(DS.getTypeRep());
1494
1495 if (!TagD) // We probably had an error
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00001496 return DeclPtrTy();
1497
John McCall67d1a672009-08-06 02:15:43 +00001498 // Note that the above type specs guarantee that the
1499 // type rep is a Decl, whereas in many of the others
1500 // it's a Type.
John McCalle3af0232009-10-07 23:34:25 +00001501 Tag = dyn_cast<TagDecl>(TagD);
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00001502 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001503
Nuno Lopes0a8bab02009-12-17 11:35:26 +00001504 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1505 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
1506 // or incomplete types shall not be restrict-qualified."
1507 if (TypeQuals & DeclSpec::TQ_restrict)
1508 Diag(DS.getRestrictSpecLoc(),
1509 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
1510 << DS.getSourceRange();
1511 }
1512
Douglas Gregord85bea22009-09-26 06:47:28 +00001513 if (DS.isFriendSpecified()) {
John McCalle3af0232009-10-07 23:34:25 +00001514 // If we're dealing with a class template decl, assume that the
1515 // template routines are handling it.
1516 if (TagD && isa<ClassTemplateDecl>(TagD))
Douglas Gregord85bea22009-09-26 06:47:28 +00001517 return DeclPtrTy();
John McCalle3af0232009-10-07 23:34:25 +00001518 return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
Douglas Gregord85bea22009-09-26 06:47:28 +00001519 }
1520
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001521 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
Chris Lattnerd451f832009-10-25 22:21:57 +00001522 // If there are attributes in the DeclSpec, apply them to the record.
1523 if (const AttributeList *AL = DS.getAttributes())
1524 ProcessDeclAttributeList(S, Record, AL);
1525
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001526 if (!Record->getDeclName() && Record->isDefinition() &&
Douglas Gregora71c1292009-03-06 23:06:59 +00001527 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1528 if (getLangOptions().CPlusPlus ||
1529 Record->getDeclContext()->isRecord())
John McCallaec03712010-05-21 20:45:30 +00001530 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregora71c1292009-03-06 23:06:59 +00001531
Douglas Gregorcb821d02010-04-08 21:33:23 +00001532 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Douglas Gregora71c1292009-03-06 23:06:59 +00001533 << DS.getSourceRange();
1534 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001535
1536 // Microsoft allows unnamed struct/union fields. Don't complain
1537 // about them.
1538 // FIXME: Should we support Microsoft's extensions in this area?
1539 if (Record->getDeclName() && getLangOptions().Microsoft)
Chris Lattnerb28317a2009-03-28 19:18:32 +00001540 return DeclPtrTy::make(Tag);
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001541 }
Douglas Gregord85bea22009-09-26 06:47:28 +00001542
Douglas Gregora131d0f2010-07-13 06:24:26 +00001543 if (getLangOptions().CPlusPlus &&
1544 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
1545 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
1546 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
1547 !Enum->getIdentifier() && !Enum->isInvalidDecl())
1548 Diag(Enum->getLocation(), diag::ext_no_declarators)
1549 << DS.getSourceRange();
1550
Mike Stump1eb44332009-09-09 15:08:12 +00001551 if (!DS.isMissingDeclaratorOk() &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00001552 DS.getTypeSpecType() != DeclSpec::TST_error) {
Douglas Gregor21282df2009-01-22 16:23:54 +00001553 // Warn about typedefs of enums without names, since this is an
Douglas Gregora0ebd602010-07-16 15:40:40 +00001554 // extension in both Microsoft and GNU.
Douglas Gregor8158f692009-01-17 02:55:50 +00001555 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1556 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregora0ebd602010-07-16 15:40:40 +00001557 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1558 << DS.getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00001559 return DeclPtrTy::make(Tag);
Douglas Gregoree159c12009-01-13 23:10:51 +00001560 }
1561
Douglas Gregorcb821d02010-04-08 21:33:23 +00001562 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Sebastian Redla4ed0d82008-12-28 15:28:59 +00001563 << DS.getSourceRange();
Sebastian Redla4ed0d82008-12-28 15:28:59 +00001564 }
Mike Stump1eb44332009-09-09 15:08:12 +00001565
John McCallc9068d72010-07-16 08:13:16 +00001566 return DeclPtrTy::make(TagD);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001567}
1568
John McCall1d7c5282009-12-18 10:40:03 +00001569/// We are trying to inject an anonymous member into the given scope;
John McCall68263142009-11-18 22:49:29 +00001570/// check if there's an existing declaration that can't be overloaded.
1571///
1572/// \return true if this is a forbidden redeclaration
John McCall1d7c5282009-12-18 10:40:03 +00001573static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
1574 Scope *S,
Fariborz Jahanian588a4ad2010-01-22 18:30:17 +00001575 DeclContext *Owner,
John McCall1d7c5282009-12-18 10:40:03 +00001576 DeclarationName Name,
1577 SourceLocation NameLoc,
1578 unsigned diagnostic) {
1579 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
1580 Sema::ForRedeclaration);
1581 if (!SemaRef.LookupName(R, S)) return false;
John McCall68263142009-11-18 22:49:29 +00001582
John McCall1d7c5282009-12-18 10:40:03 +00001583 if (R.getAsSingle<TagDecl>())
John McCall68263142009-11-18 22:49:29 +00001584 return false;
1585
1586 // Pick a representative declaration.
John McCall1d7c5282009-12-18 10:40:03 +00001587 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Fariborz Jahanian588a4ad2010-01-22 18:30:17 +00001588 if (PrevDecl && Owner->isRecord()) {
1589 RecordDecl *Record = cast<RecordDecl>(Owner);
1590 if (!SemaRef.isDeclInScope(PrevDecl, Record, S))
1591 return false;
1592 }
John McCall68263142009-11-18 22:49:29 +00001593
John McCall1d7c5282009-12-18 10:40:03 +00001594 SemaRef.Diag(NameLoc, diagnostic) << Name;
1595 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall68263142009-11-18 22:49:29 +00001596
1597 return true;
1598}
1599
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001600/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1601/// anonymous struct or union AnonRecord into the owning context Owner
1602/// and scope S. This routine will be invoked just after we realize
1603/// that an unnamed union or struct is actually an anonymous union or
1604/// struct, e.g.,
1605///
1606/// @code
1607/// union {
1608/// int i;
1609/// float f;
1610/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1611/// // f into the surrounding scope.x
1612/// @endcode
1613///
1614/// This routine is recursive, injecting the names of nested anonymous
1615/// structs/unions into the owning context and scope as well.
John McCallaec03712010-05-21 20:45:30 +00001616static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
1617 DeclContext *Owner,
1618 RecordDecl *AnonRecord,
1619 AccessSpecifier AS) {
John McCall68263142009-11-18 22:49:29 +00001620 unsigned diagKind
1621 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
1622 : diag::err_anonymous_struct_member_redecl;
1623
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001624 bool Invalid = false;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001625 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
1626 FEnd = AnonRecord->field_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001627 F != FEnd; ++F) {
1628 if ((*F)->getDeclName()) {
John McCallaec03712010-05-21 20:45:30 +00001629 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, (*F)->getDeclName(),
John McCall1d7c5282009-12-18 10:40:03 +00001630 (*F)->getLocation(), diagKind)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001631 // C++ [class.union]p2:
1632 // The names of the members of an anonymous union shall be
1633 // distinct from the names of any other entity in the
1634 // scope in which the anonymous union is declared.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001635 Invalid = true;
1636 } else {
1637 // C++ [class.union]p2:
1638 // For the purpose of name lookup, after the anonymous union
1639 // definition, the members of the anonymous union are
1640 // considered to have been defined in the scope in which the
1641 // anonymous union is declared.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001642 Owner->makeDeclVisibleInContext(*F);
John McCallaec03712010-05-21 20:45:30 +00001643 S->AddDecl(Sema::DeclPtrTy::make(*F));
1644 SemaRef.IdResolver.AddDecl(*F);
1645
1646 // That includes picking up the appropriate access specifier.
1647 if (AS != AS_none) (*F)->setAccess(AS);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001648 }
1649 } else if (const RecordType *InnerRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001650 = (*F)->getType()->getAs<RecordType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001651 RecordDecl *InnerRecord = InnerRecordType->getDecl();
1652 if (InnerRecord->isAnonymousStructOrUnion())
Mike Stump1eb44332009-09-09 15:08:12 +00001653 Invalid = Invalid ||
John McCallaec03712010-05-21 20:45:30 +00001654 InjectAnonymousStructOrUnionMembers(SemaRef, S, Owner,
1655 InnerRecord, AS);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001656 }
1657 }
1658
1659 return Invalid;
1660}
1661
Douglas Gregor16573fa2010-04-19 22:54:31 +00001662/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
1663/// a VarDecl::StorageClass. Any error reporting is up to the caller:
1664/// illegal input values are mapped to VarDecl::None.
Abramo Bagnarab21b4052010-04-28 13:11:54 +00001665/// If the input declaration context is a linkage specification
1666/// with no braces, then Extern is mapped to None.
Douglas Gregor16573fa2010-04-19 22:54:31 +00001667static VarDecl::StorageClass
Abramo Bagnarab21b4052010-04-28 13:11:54 +00001668StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec,
1669 DeclContext *DC) {
Douglas Gregor16573fa2010-04-19 22:54:31 +00001670 switch (StorageClassSpec) {
1671 case DeclSpec::SCS_unspecified: return VarDecl::None;
Abramo Bagnarab21b4052010-04-28 13:11:54 +00001672 case DeclSpec::SCS_extern:
1673 // If the current context is a C++ linkage specification
1674 // having no braces, then the keyword "extern" is properly part
1675 // of the linkage specification itself, rather than being
1676 // the written storage class specifier.
1677 return (DC && isa<LinkageSpecDecl>(DC) &&
1678 !cast<LinkageSpecDecl>(DC)->hasBraces())
1679 ? VarDecl::None : VarDecl::Extern;
Douglas Gregor16573fa2010-04-19 22:54:31 +00001680 case DeclSpec::SCS_static: return VarDecl::Static;
1681 case DeclSpec::SCS_auto: return VarDecl::Auto;
1682 case DeclSpec::SCS_register: return VarDecl::Register;
1683 case DeclSpec::SCS_private_extern: return VarDecl::PrivateExtern;
1684 // Illegal SCSs map to None: error reporting is up to the caller.
1685 case DeclSpec::SCS_mutable: // Fall through.
1686 case DeclSpec::SCS_typedef: return VarDecl::None;
1687 }
1688 llvm_unreachable("unknown storage class specifier");
1689}
1690
1691/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
1692/// a FunctionDecl::StorageClass. Any error reporting is up to the caller:
1693/// illegal input values are mapped to FunctionDecl::None.
Abramo Bagnarab21b4052010-04-28 13:11:54 +00001694/// If the input declaration context is a linkage specification
1695/// with no braces, then Extern is mapped to None.
Douglas Gregor16573fa2010-04-19 22:54:31 +00001696static FunctionDecl::StorageClass
Abramo Bagnarab21b4052010-04-28 13:11:54 +00001697StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec,
1698 DeclContext *DC) {
Douglas Gregor16573fa2010-04-19 22:54:31 +00001699 switch (StorageClassSpec) {
1700 case DeclSpec::SCS_unspecified: return FunctionDecl::None;
Abramo Bagnarab21b4052010-04-28 13:11:54 +00001701 case DeclSpec::SCS_extern:
1702 // If the current context is a C++ linkage specification
1703 // having no braces, then the keyword "extern" is properly part
1704 // of the linkage specification itself, rather than being
1705 // the written storage class specifier.
1706 return (DC && isa<LinkageSpecDecl>(DC) &&
1707 !cast<LinkageSpecDecl>(DC)->hasBraces())
1708 ? FunctionDecl::None : FunctionDecl::Extern;
Douglas Gregor16573fa2010-04-19 22:54:31 +00001709 case DeclSpec::SCS_static: return FunctionDecl::Static;
1710 case DeclSpec::SCS_private_extern: return FunctionDecl::PrivateExtern;
1711 // Illegal SCSs map to None: error reporting is up to the caller.
1712 case DeclSpec::SCS_auto: // Fall through.
1713 case DeclSpec::SCS_mutable: // Fall through.
1714 case DeclSpec::SCS_register: // Fall through.
1715 case DeclSpec::SCS_typedef: return FunctionDecl::None;
1716 }
1717 llvm_unreachable("unknown storage class specifier");
1718}
1719
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001720/// ActOnAnonymousStructOrUnion - Handle the declaration of an
1721/// anonymous structure or union. Anonymous unions are a C++ feature
1722/// (C++ [class.union]) and a GNU C extension; anonymous structures
Mike Stump1eb44332009-09-09 15:08:12 +00001723/// are a GNU C and GNU C++ extension.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001724Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
John McCallaec03712010-05-21 20:45:30 +00001725 AccessSpecifier AS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001726 RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001727 DeclContext *Owner = Record->getDeclContext();
1728
1729 // Diagnose whether this anonymous struct/union is an extension.
1730 if (Record->isUnion() && !getLangOptions().CPlusPlus)
1731 Diag(Record->getLocation(), diag::ext_anonymous_union);
1732 else if (!Record->isUnion())
1733 Diag(Record->getLocation(), diag::ext_anonymous_struct);
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001735 // C and C++ require different kinds of checks for anonymous
1736 // structs/unions.
1737 bool Invalid = false;
1738 if (getLangOptions().CPlusPlus) {
1739 const char* PrevSpec = 0;
John McCallfec54012009-08-03 20:12:06 +00001740 unsigned DiagID;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001741 // C++ [class.union]p3:
1742 // Anonymous unions declared in a named namespace or in the
1743 // global namespace shall be declared static.
1744 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1745 (isa<TranslationUnitDecl>(Owner) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001746 (isa<NamespaceDecl>(Owner) &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001747 cast<NamespaceDecl>(Owner)->getDeclName()))) {
1748 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1749 Invalid = true;
1750
1751 // Recover by adding 'static'.
John McCallfec54012009-08-03 20:12:06 +00001752 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1753 PrevSpec, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +00001754 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001755 // C++ [class.union]p3:
1756 // A storage class is not allowed in a declaration of an
1757 // anonymous union in a class scope.
1758 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1759 isa<RecordDecl>(Owner)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001760 Diag(DS.getStorageClassSpecLoc(),
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001761 diag::err_anonymous_union_with_storage_spec);
1762 Invalid = true;
1763
1764 // Recover by removing the storage specifier.
1765 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
John McCallfec54012009-08-03 20:12:06 +00001766 PrevSpec, DiagID);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001767 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001768
Mike Stump1eb44332009-09-09 15:08:12 +00001769 // C++ [class.union]p2:
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001770 // The member-specification of an anonymous union shall only
1771 // define non-static data members. [Note: nested types and
1772 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001773 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1774 MemEnd = Record->decls_end();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001775 Mem != MemEnd; ++Mem) {
1776 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1777 // C++ [class.union]p3:
1778 // An anonymous union shall not have private or protected
1779 // members (clause 11).
John McCallaec03712010-05-21 20:45:30 +00001780 assert(FD->getAccess() != AS_none);
1781 if (FD->getAccess() != AS_public) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001782 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1783 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1784 Invalid = true;
1785 }
1786 } else if ((*Mem)->isImplicit()) {
1787 // Any implicit members are fine.
Douglas Gregor1931b442009-02-03 00:34:39 +00001788 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1789 // This is a type that showed up in an
1790 // elaborated-type-specifier inside the anonymous struct or
1791 // union, but which actually declares a type outside of the
1792 // anonymous struct or union. It's okay.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001793 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1794 if (!MemRecord->isAnonymousStructOrUnion() &&
1795 MemRecord->getDeclName()) {
1796 // This is a nested type declaration.
1797 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1798 << (int)Record->isUnion();
1799 Invalid = true;
1800 }
Abramo Bagnara6206d532010-06-05 05:09:32 +00001801 } else if (isa<AccessSpecDecl>(*Mem)) {
1802 // Any access specifier is fine.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001803 } else {
1804 // We have something that isn't a non-static data
1805 // member. Complain about it.
1806 unsigned DK = diag::err_anonymous_record_bad_member;
1807 if (isa<TypeDecl>(*Mem))
1808 DK = diag::err_anonymous_record_with_type;
1809 else if (isa<FunctionDecl>(*Mem))
1810 DK = diag::err_anonymous_record_with_function;
1811 else if (isa<VarDecl>(*Mem))
1812 DK = diag::err_anonymous_record_with_static;
1813 Diag((*Mem)->getLocation(), DK)
1814 << (int)Record->isUnion();
1815 Invalid = true;
1816 }
1817 }
Mike Stump1eb44332009-09-09 15:08:12 +00001818 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001819
1820 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001821 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1822 << (int)getLangOptions().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001823 Invalid = true;
1824 }
1825
John McCalleb692e02009-10-22 23:31:08 +00001826 // Mock up a declarator.
1827 Declarator Dc(DS, Declarator::TypeNameContext);
John McCallbf1a0282010-06-04 23:28:52 +00001828 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCalla93c9342009-12-07 02:54:59 +00001829 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCalleb692e02009-10-22 23:31:08 +00001830
Mike Stump1eb44332009-09-09 15:08:12 +00001831 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001832 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001833 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1834 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001835 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001836 Context.getTypeDeclType(Record),
John McCalla93c9342009-12-07 02:54:59 +00001837 TInfo,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001838 /*BitWidth=*/0, /*Mutable=*/false);
John McCallaec03712010-05-21 20:45:30 +00001839 Anon->setAccess(AS);
Douglas Gregorfe60f842010-05-03 15:18:25 +00001840 if (getLangOptions().CPlusPlus) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001841 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorfe60f842010-05-03 15:18:25 +00001842 if (!cast<CXXRecordDecl>(Record)->isEmpty())
1843 cast<CXXRecordDecl>(OwningClass)->setEmpty(false);
1844 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001845 } else {
Douglas Gregor16573fa2010-04-19 22:54:31 +00001846 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
1847 assert(SCSpec != DeclSpec::SCS_typedef &&
1848 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnarab21b4052010-04-28 13:11:54 +00001849 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec, 0);
Douglas Gregor16573fa2010-04-19 22:54:31 +00001850 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001851 // mutable can only appear on non-static class members, so it's always
1852 // an error here
1853 Diag(Record->getLocation(), diag::err_mutable_nonmember);
1854 Invalid = true;
1855 SC = VarDecl::None;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001856 }
Douglas Gregor16573fa2010-04-19 22:54:31 +00001857 SCSpec = DS.getStorageClassSpecAsWritten();
1858 VarDecl::StorageClass SCAsWritten
Abramo Bagnarab21b4052010-04-28 13:11:54 +00001859 = StorageClassSpecToVarDeclStorageClass(SCSpec, 0);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001860
1861 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001862 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001863 Context.getTypeDeclType(Record),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001864 TInfo, SC, SCAsWritten);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001865 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001866 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001867
1868 // Add the anonymous struct/union object to the current
1869 // context. We'll be referencing this object when we refer to one of
1870 // its members.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001871 Owner->addDecl(Anon);
Douglas Gregorfe60f842010-05-03 15:18:25 +00001872
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001873 // Inject the members of the anonymous struct/union into the owning
1874 // context and into the identifier resolver chain for name lookup
1875 // purposes.
John McCallaec03712010-05-21 20:45:30 +00001876 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS))
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001877 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001878
1879 // Mark this as an anonymous struct/union type. Note that we do not
1880 // do this until after we have already checked and injected the
1881 // members of this anonymous struct/union type, because otherwise
1882 // the members could be injected twice: once by DeclContext when it
1883 // builds its lookup table, and once by
Mike Stump1eb44332009-09-09 15:08:12 +00001884 // InjectAnonymousStructOrUnionMembers.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001885 Record->setAnonymousStructOrUnion(true);
1886
1887 if (Invalid)
1888 Anon->setInvalidDecl();
1889
Chris Lattnerb28317a2009-03-28 19:18:32 +00001890 return DeclPtrTy::make(Anon);
Reid Spencer5f016e22007-07-11 17:01:13 +00001891}
1892
Steve Narofff0090632007-09-02 02:04:30 +00001893
Douglas Gregor10bd3682008-11-17 22:58:34 +00001894/// GetNameForDeclarator - Determine the full declaration name for the
1895/// given Declarator.
1896DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001897 return GetNameFromUnqualifiedId(D.getName());
1898}
1899
1900/// \brief Retrieves the canonicalized name from a parsed unqualified-id.
John McCall129e2df2009-11-30 22:42:35 +00001901DeclarationName Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001902 switch (Name.getKind()) {
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001903 case UnqualifiedId::IK_Identifier:
1904 return DeclarationName(Name.Identifier);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001905
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001906 case UnqualifiedId::IK_OperatorFunctionId:
1907 return Context.DeclarationNames.getCXXOperatorName(
Sean Huntf4fdd9b2009-11-29 03:04:53 +00001908 Name.OperatorFunctionId.Operator);
Sean Hunt0486d742009-11-28 04:44:28 +00001909
1910 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +00001911 return Context.DeclarationNames.getCXXLiteralOperatorName(
1912 Name.Identifier);
Sean Hunt0486d742009-11-28 04:44:28 +00001913
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001914 case UnqualifiedId::IK_ConversionFunctionId: {
1915 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId);
1916 if (Ty.isNull())
1917 return DeclarationName();
Douglas Gregordb422df2009-09-25 21:45:23 +00001918
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001919 return Context.DeclarationNames.getCXXConversionFunctionName(
Sean Huntf4fdd9b2009-11-29 03:04:53 +00001920 Context.getCanonicalType(Ty));
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001921 }
1922
1923 case UnqualifiedId::IK_ConstructorName: {
1924 QualType Ty = GetTypeFromParser(Name.ConstructorName);
1925 if (Ty.isNull())
1926 return DeclarationName();
1927
1928 return Context.DeclarationNames.getCXXConstructorName(
Sean Huntf4fdd9b2009-11-29 03:04:53 +00001929 Context.getCanonicalType(Ty));
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001930 }
1931
Douglas Gregor0efc2c12010-01-13 17:31:36 +00001932 case UnqualifiedId::IK_ConstructorTemplateId: {
1933 // In well-formed code, we can only have a constructor
1934 // template-id that refers to the current context, so go there
1935 // to find the actual type being constructed.
1936 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
1937 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
1938 return DeclarationName();
1939
1940 // Determine the type of the class being constructed.
John McCall3cb0ebd2010-03-10 03:28:59 +00001941 QualType CurClassType = Context.getTypeDeclType(CurClass);
Douglas Gregor0efc2c12010-01-13 17:31:36 +00001942
1943 // FIXME: Check two things: that the template-id names the same type as
1944 // CurClassType, and that the template-id does not occur when the name
1945 // was qualified.
1946
1947 return Context.DeclarationNames.getCXXConstructorName(
1948 Context.getCanonicalType(CurClassType));
1949 }
1950
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001951 case UnqualifiedId::IK_DestructorName: {
1952 QualType Ty = GetTypeFromParser(Name.DestructorName);
1953 if (Ty.isNull())
1954 return DeclarationName();
1955
1956 return Context.DeclarationNames.getCXXDestructorName(
1957 Context.getCanonicalType(Ty));
1958 }
1959
1960 case UnqualifiedId::IK_TemplateId: {
1961 TemplateName TName
John McCall0bd6feb2009-12-02 08:04:21 +00001962 = TemplateName::getFromVoidPointer(Name.TemplateId->Template);
1963 return Context.getNameForTemplate(TName);
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001964 }
Douglas Gregordb422df2009-09-25 21:45:23 +00001965 }
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001966
Douglas Gregor10bd3682008-11-17 22:58:34 +00001967 assert(false && "Unknown name kind");
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001968 return DeclarationName();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001969}
1970
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001971/// isNearlyMatchingFunction - Determine whether the C++ functions
1972/// Declaration and Definition are "nearly" matching. This heuristic
1973/// is used to improve diagnostics in the case where an out-of-line
1974/// function definition doesn't match any declaration within
1975/// the class or namespace.
1976static bool isNearlyMatchingFunction(ASTContext &Context,
1977 FunctionDecl *Declaration,
1978 FunctionDecl *Definition) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001979 if (Declaration->param_size() != Definition->param_size())
1980 return false;
1981 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1982 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1983 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1984
Douglas Gregora4923eb2009-11-16 21:35:15 +00001985 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
1986 DefParamTy.getNonReferenceType()))
Douglas Gregor584049d2008-12-15 23:53:10 +00001987 return false;
1988 }
1989
1990 return true;
1991}
1992
John McCall63b43852010-04-29 23:50:39 +00001993/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
1994/// declarator needs to be rebuilt in the current instantiation.
1995/// Any bits of declarator which appear before the name are valid for
1996/// consideration here. That's specifically the type in the decl spec
1997/// and the base type in any member-pointer chunks.
1998static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
1999 DeclarationName Name) {
2000 // The types we specifically need to rebuild are:
2001 // - typenames, typeofs, and decltypes
2002 // - types which will become injected class names
2003 // Of course, we also need to rebuild any type referencing such a
2004 // type. It's safest to just say "dependent", but we call out a
2005 // few cases here.
2006
2007 DeclSpec &DS = D.getMutableDeclSpec();
2008 switch (DS.getTypeSpecType()) {
2009 case DeclSpec::TST_typename:
2010 case DeclSpec::TST_typeofType:
2011 case DeclSpec::TST_typeofExpr:
2012 case DeclSpec::TST_decltype: {
2013 // Grab the type from the parser.
2014 TypeSourceInfo *TSI = 0;
2015 QualType T = S.GetTypeFromParser(DS.getTypeRep(), &TSI);
2016 if (T.isNull() || !T->isDependentType()) break;
2017
2018 // Make sure there's a type source info. This isn't really much
2019 // of a waste; most dependent types should have type source info
2020 // attached already.
2021 if (!TSI)
2022 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
2023
2024 // Rebuild the type in the current instantiation.
2025 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
2026 if (!TSI) return true;
2027
2028 // Store the new type back in the decl spec.
2029 QualType LocType = S.CreateLocInfoType(TSI->getType(), TSI);
2030 DS.UpdateTypeRep(LocType.getAsOpaquePtr());
2031 break;
2032 }
2033
2034 default:
2035 // Nothing to do for these decl specs.
2036 break;
2037 }
2038
2039 // It doesn't matter what order we do this in.
2040 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2041 DeclaratorChunk &Chunk = D.getTypeObject(I);
2042
2043 // The only type information in the declarator which can come
2044 // before the declaration name is the base type of a member
2045 // pointer.
2046 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
2047 continue;
2048
2049 // Rebuild the scope specifier in-place.
2050 CXXScopeSpec &SS = Chunk.Mem.Scope();
2051 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
2052 return true;
2053 }
2054
2055 return false;
2056}
2057
Mike Stump1eb44332009-09-09 15:08:12 +00002058Sema::DeclPtrTy
2059Sema::HandleDeclarator(Scope *S, Declarator &D,
Douglas Gregore542c862009-06-23 23:11:28 +00002060 MultiTemplateParamsArg TemplateParamLists,
2061 bool IsFunctionDefinition) {
Douglas Gregor10bd3682008-11-17 22:58:34 +00002062 DeclarationName Name = GetNameForDeclarator(D);
2063
Chris Lattnere80a59c2007-07-25 00:24:17 +00002064 // All of these full declarators require an identifier. If it doesn't have
2065 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00002066 if (!Name) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00002067 if (!D.isInvalidType()) // Reject this if we think it is valid.
Chris Lattner1f6f54b2008-11-11 06:13:16 +00002068 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002069 diag::err_declarator_need_ident)
2070 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00002071 return DeclPtrTy();
Chris Lattnere80a59c2007-07-25 00:24:17 +00002072 }
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Chris Lattner31e05722007-08-26 06:24:45 +00002074 // The scope passed in may not be a decl scope. Zip up the scope tree until
2075 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00002076 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregoraaba5e32009-02-04 19:02:06 +00002077 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00002078 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002079
John McCall63b43852010-04-29 23:50:39 +00002080 DeclContext *DC = CurContext;
2081 if (D.getCXXScopeSpec().isInvalid())
2082 D.setInvalidType();
2083 else if (D.getCXXScopeSpec().isSet()) {
2084 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
2085 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
2086 if (!DC) {
2087 // If we could not compute the declaration context, it's because the
2088 // declaration context is dependent but does not refer to a class,
2089 // class template, or class template partial specialization. Complain
2090 // and return early, to avoid the coming semantic disaster.
2091 Diag(D.getIdentifierLoc(),
2092 diag::err_template_qualified_declarator_no_match)
2093 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
2094 << D.getCXXScopeSpec().getRange();
2095 return DeclPtrTy();
2096 }
John McCall0dd7ceb2009-12-19 09:35:56 +00002097
John McCall63b43852010-04-29 23:50:39 +00002098 bool IsDependentContext = DC->isDependentContext();
John McCall0dd7ceb2009-12-19 09:35:56 +00002099
John McCall63b43852010-04-29 23:50:39 +00002100 if (!IsDependentContext &&
John McCall77bb1aa2010-05-01 00:40:08 +00002101 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall63b43852010-04-29 23:50:39 +00002102 return DeclPtrTy();
2103
2104 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
2105 Diag(D.getIdentifierLoc(),
2106 diag::err_member_def_undefined_record)
2107 << Name << DC << D.getCXXScopeSpec().getRange();
2108 D.setInvalidType();
2109 }
2110
2111 // Check whether we need to rebuild the type of the given
2112 // declaration in the current instantiation.
2113 if (EnteringContext && IsDependentContext &&
2114 TemplateParamLists.size() != 0) {
2115 ContextRAII SavedContext(*this, DC);
2116 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
2117 D.setInvalidType();
Douglas Gregor4a959d82009-08-06 16:20:37 +00002118 }
2119 }
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002121 NamedDecl *New;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002122
John McCallbf1a0282010-06-04 23:28:52 +00002123 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
2124 QualType R = TInfo->getType();
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002125
John McCall68263142009-11-18 22:49:29 +00002126 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
2127 ForRedeclaration);
2128
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002129 // See if this is a redefinition of a variable in the same scope.
John McCall63b43852010-04-29 23:50:39 +00002130 if (!D.getCXXScopeSpec().isSet()) {
John McCall68263142009-11-18 22:49:29 +00002131 bool IsLinkageLookup = false;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002132
2133 // If the declaration we're planning to build will be a function
2134 // or object with linkage, then look for another declaration with
2135 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
2136 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2137 /* Do nothing*/;
2138 else if (R->isFunctionType()) {
Douglas Gregor6bec78d2009-07-07 17:00:05 +00002139 if (CurContext->isFunctionOrMethod() ||
2140 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall68263142009-11-18 22:49:29 +00002141 IsLinkageLookup = true;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002142 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
John McCall68263142009-11-18 22:49:29 +00002143 IsLinkageLookup = true;
Douglas Gregor6bec78d2009-07-07 17:00:05 +00002144 else if (CurContext->getLookupContext()->isTranslationUnit() &&
2145 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall68263142009-11-18 22:49:29 +00002146 IsLinkageLookup = true;
2147
2148 if (IsLinkageLookup)
2149 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002150
John McCall68263142009-11-18 22:49:29 +00002151 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002152 } else { // Something like "int foo::x;"
John McCall68263142009-11-18 22:49:29 +00002153 LookupQualifiedName(Previous, DC);
2154
2155 // Don't consider using declarations as previous declarations for
2156 // out-of-line members.
2157 RemoveUsingDecls(Previous);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002158
2159 // C++ 7.3.1.2p2:
2160 // Members (including explicit specializations of templates) of a named
2161 // namespace can also be defined outside that namespace by explicit
2162 // qualification of the name being defined, provided that the entity being
2163 // defined was already declared in the namespace and the definition appears
2164 // after the point of declaration in a namespace that encloses the
2165 // declarations namespace.
2166 //
Douglas Gregor584049d2008-12-15 23:53:10 +00002167 // Note that we only check the context at this point. We don't yet
2168 // have enough information to make sure that PrevDecl is actually
2169 // the declaration we want to match. For example, given:
2170 //
Douglas Gregor9d350972008-12-12 08:25:50 +00002171 // class X {
2172 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00002173 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00002174 // };
2175 //
Douglas Gregor584049d2008-12-15 23:53:10 +00002176 // void X::f(int) { } // ill-formed
2177 //
2178 // In this case, PrevDecl will point to the overload set
2179 // containing the two f's declared in X, but neither of them
Mike Stump1eb44332009-09-09 15:08:12 +00002180 // matches.
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002181
2182 // First check whether we named the global scope.
2183 if (isa<TranslationUnitDecl>(DC)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002184 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002185 << Name << D.getCXXScopeSpec().getRange();
Sebastian Redl9770ef02009-11-08 11:36:54 +00002186 } else {
2187 DeclContext *Cur = CurContext;
2188 while (isa<LinkageSpecDecl>(Cur))
2189 Cur = Cur->getParent();
2190 if (!Cur->Encloses(DC)) {
2191 // The qualifying scope doesn't enclose the original declaration.
2192 // Emit diagnostic based on current scope.
2193 SourceLocation L = D.getIdentifierLoc();
2194 SourceRange R = D.getCXXScopeSpec().getRange();
2195 if (isa<FunctionDecl>(Cur))
2196 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
2197 else
2198 Diag(L, diag::err_invalid_declarator_scope)
2199 << Name << cast<NamedDecl>(DC) << R;
2200 D.setInvalidType();
2201 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002202 }
2203 }
2204
John McCall68263142009-11-18 22:49:29 +00002205 if (Previous.isSingleResult() &&
2206 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002207 // Maybe we will complain about the shadowed template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002208 if (!D.isInvalidType())
John McCall68263142009-11-18 22:49:29 +00002209 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
2210 Previous.getFoundDecl()))
Chris Lattnereaaebc72009-04-25 08:06:05 +00002211 D.setInvalidType();
Mike Stump1eb44332009-09-09 15:08:12 +00002212
Douglas Gregor72c3f312008-12-05 18:15:24 +00002213 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +00002214 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +00002215 }
2216
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002217 // In C++, the previous declaration we find might be a tag type
2218 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00002219 // tag type. Note that this does does not apply if we're declaring a
2220 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00002221 if (Previous.isSingleTagDecl() &&
Douglas Gregor66973122009-01-28 17:15:10 +00002222 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall68263142009-11-18 22:49:29 +00002223 Previous.clear();
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002224
Douglas Gregorcda9c672009-02-16 17:45:42 +00002225 bool Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002226 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregore542c862009-06-23 23:11:28 +00002227 if (TemplateParamLists.size()) {
2228 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
2229 return DeclPtrTy();
2230 }
Mike Stump1eb44332009-09-09 15:08:12 +00002231
John McCalla93c9342009-12-07 02:54:59 +00002232 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002233 } else if (R->isFunctionType()) {
John McCalla93c9342009-12-07 02:54:59 +00002234 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregore542c862009-06-23 23:11:28 +00002235 move(TemplateParamLists),
Chris Lattnereaaebc72009-04-25 08:06:05 +00002236 IsFunctionDefinition, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +00002237 } else {
John McCalla93c9342009-12-07 02:54:59 +00002238 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002239 move(TemplateParamLists),
2240 Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +00002241 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002242
2243 if (New == 0)
Chris Lattnerb28317a2009-03-28 19:18:32 +00002244 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002246 // If this has an identifier and is not an invalid redeclaration or
2247 // function template specialization, add it to the scope stack.
Douglas Gregorf178dca2010-07-24 00:10:38 +00002248 if (New->getDeclName() && !(Redeclaration && New->isInvalidDecl()))
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002249 PushOnScopeChains(New, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002250
Chris Lattnerb28317a2009-03-28 19:18:32 +00002251 return DeclPtrTy::make(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00002252}
2253
Eli Friedman1ca48132009-02-21 00:44:51 +00002254/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2255/// types into constant array types in certain situations which would otherwise
2256/// be errors (for GCC compatibility).
2257static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2258 ASTContext &Context,
2259 bool &SizeIsNegative) {
2260 // This method tries to turn a variable array into a constant
2261 // array even when the size isn't an ICE. This is necessary
2262 // for compatibility with code that depends on gcc's buggy
2263 // constant expression folding, like struct {char x[(int)(char*)2];}
2264 SizeIsNegative = false;
2265
John McCall0953e762009-09-24 19:53:00 +00002266 QualifierCollector Qs;
2267 const Type *Ty = Qs.strip(T);
2268
2269 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedman1ca48132009-02-21 00:44:51 +00002270 QualType Pointee = PTy->getPointeeType();
2271 QualType FixedType =
2272 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
2273 if (FixedType.isNull()) return FixedType;
Eli Friedman61125c82009-02-21 00:58:02 +00002274 FixedType = Context.getPointerType(FixedType);
John McCall0953e762009-09-24 19:53:00 +00002275 return Qs.apply(FixedType);
Eli Friedman1ca48132009-02-21 00:44:51 +00002276 }
2277
2278 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanbc592e62009-02-26 03:58:54 +00002279 if (!VLATy)
2280 return QualType();
2281 // FIXME: We should probably handle this case
2282 if (VLATy->getElementType()->isVariablyModifiedType())
2283 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00002284
Eli Friedman1ca48132009-02-21 00:44:51 +00002285 Expr::EvalResult EvalResult;
2286 if (!VLATy->getSizeExpr() ||
Eli Friedmanbc592e62009-02-26 03:58:54 +00002287 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
2288 !EvalResult.Val.isInt())
Eli Friedman1ca48132009-02-21 00:44:51 +00002289 return QualType();
Eli Friedmanbc592e62009-02-26 03:58:54 +00002290
Eli Friedman1ca48132009-02-21 00:44:51 +00002291 llvm::APSInt &Res = EvalResult.Val.getInt();
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002292 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
John McCall46a617a2009-10-16 00:14:28 +00002293 // TODO: preserve the size expression in declarator info
2294 return Context.getConstantArrayType(VLATy->getElementType(),
2295 Res, ArrayType::Normal, 0);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002296 }
Eli Friedman1ca48132009-02-21 00:44:51 +00002297
2298 SizeIsNegative = true;
2299 return QualType();
2300}
2301
Douglas Gregor63935192009-03-02 00:19:53 +00002302/// \brief Register the given locally-scoped external C declaration so
2303/// that it can be found later for redeclarations
Mike Stump1eb44332009-09-09 15:08:12 +00002304void
John McCall68263142009-11-18 22:49:29 +00002305Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
2306 const LookupResult &Previous,
Douglas Gregor63935192009-03-02 00:19:53 +00002307 Scope *S) {
2308 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
2309 "Decl is not a locally-scoped decl!");
2310 // Note that we have a locally-scoped external with this name.
2311 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
2312
John McCall68263142009-11-18 22:49:29 +00002313 if (!Previous.isSingleResult())
Douglas Gregor63935192009-03-02 00:19:53 +00002314 return;
2315
John McCall68263142009-11-18 22:49:29 +00002316 NamedDecl *PrevDecl = Previous.getFoundDecl();
2317
Douglas Gregor63935192009-03-02 00:19:53 +00002318 // If there was a previous declaration of this variable, it may be
2319 // in our identifier chain. Update the identifier chain with the new
2320 // declaration.
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002321 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
Douglas Gregor63935192009-03-02 00:19:53 +00002322 // The previous declaration was found on the identifer resolver
2323 // chain, so remove it from its scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002324 while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
Douglas Gregor63935192009-03-02 00:19:53 +00002325 S = S->getParent();
2326
2327 if (S)
Chris Lattnerb28317a2009-03-28 19:18:32 +00002328 S->RemoveDecl(DeclPtrTy::make(PrevDecl));
Douglas Gregor63935192009-03-02 00:19:53 +00002329 }
2330}
2331
Eli Friedman85a53192009-04-07 19:37:57 +00002332/// \brief Diagnose function specifiers on a declaration of an identifier that
2333/// does not identify a function.
2334void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
2335 // FIXME: We should probably indicate the identifier in question to avoid
2336 // confusion for constructs like "inline int a(), b;"
2337 if (D.getDeclSpec().isInlineSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00002338 Diag(D.getDeclSpec().getInlineSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00002339 diag::err_inline_non_function);
2340
2341 if (D.getDeclSpec().isVirtualSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00002342 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00002343 diag::err_virtual_non_function);
2344
2345 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00002346 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00002347 diag::err_explicit_non_function);
2348}
2349
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002350NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002351Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCalla93c9342009-12-07 02:54:59 +00002352 QualType R, TypeSourceInfo *TInfo,
John McCall68263142009-11-18 22:49:29 +00002353 LookupResult &Previous, bool &Redeclaration) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002354 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2355 if (D.getCXXScopeSpec().isSet()) {
2356 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2357 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00002358 D.setInvalidType();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002359 // Pretend we didn't see the scope specifier.
Douglas Gregor9de672f2010-03-23 15:26:55 +00002360 DC = CurContext;
2361 Previous.clear();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002362 }
2363
Douglas Gregor021c3b32009-03-11 23:00:04 +00002364 if (getLangOptions().CPlusPlus) {
2365 // Check that there are no default arguments (C++ only).
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002366 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +00002367 }
2368
Eli Friedman85a53192009-04-07 19:37:57 +00002369 DiagnoseFunctionSpecifiers(D);
2370
Eli Friedman63054b32009-04-19 20:27:55 +00002371 if (D.getDeclSpec().isThreadSpecified())
2372 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2373
Douglas Gregoraef01992010-07-13 06:37:01 +00002374 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
2375 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
2376 << D.getName().getSourceRange();
2377 return 0;
2378 }
2379
John McCalla93c9342009-12-07 02:54:59 +00002380 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002381 if (!NewTD) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002382
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002383 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002384 ProcessDeclAttributes(S, NewTD, D);
John McCall68263142009-11-18 22:49:29 +00002385
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002386 // Merge the decl with the existing one if appropriate. If the decl is
2387 // in an outer scope, it isn't the same thing.
John McCall68263142009-11-18 22:49:29 +00002388 FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false);
2389 if (!Previous.empty()) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00002390 Redeclaration = true;
John McCall68263142009-11-18 22:49:29 +00002391 MergeTypeDefDecl(NewTD, Previous);
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002392 }
2393
Chris Lattner38c5ebd2009-04-19 05:21:20 +00002394 // C99 6.7.7p2: If a typedef name specifies a variably modified type
2395 // then it shall have block scope.
2396 QualType T = NewTD->getUnderlyingType();
2397 if (T->isVariablyModifiedType()) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00002398 FunctionNeedsScopeChecking() = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002399
Chris Lattner38c5ebd2009-04-19 05:21:20 +00002400 if (S->getFnParent() == 0) {
Eli Friedman1ca48132009-02-21 00:44:51 +00002401 bool SizeIsNegative;
2402 QualType FixedTy =
2403 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2404 if (!FixedTy.isNull()) {
2405 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
John McCalla93c9342009-12-07 02:54:59 +00002406 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
Eli Friedman1ca48132009-02-21 00:44:51 +00002407 } else {
2408 if (SizeIsNegative)
2409 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2410 else if (T->isVariableArrayType())
2411 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
2412 else
2413 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002414 NewTD->setInvalidDecl();
Eli Friedman1ca48132009-02-21 00:44:51 +00002415 }
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002416 }
2417 }
Douglas Gregorc29f77b2009-07-07 16:35:42 +00002418
2419 // If this is the C FILE type, notify the AST context.
2420 if (IdentifierInfo *II = NewTD->getIdentifier())
2421 if (!NewTD->isInvalidDecl() &&
Mike Stump782fa302009-07-28 02:25:19 +00002422 NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
2423 if (II->isStr("FILE"))
2424 Context.setFILEDecl(NewTD);
2425 else if (II->isStr("jmp_buf"))
2426 Context.setjmp_bufDecl(NewTD);
2427 else if (II->isStr("sigjmp_buf"))
2428 Context.setsigjmp_bufDecl(NewTD);
2429 }
2430
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002431 return NewTD;
2432}
2433
Douglas Gregor8f301052009-02-24 19:23:27 +00002434/// \brief Determines whether the given declaration is an out-of-scope
2435/// previous declaration.
2436///
2437/// This routine should be invoked when name lookup has found a
2438/// previous declaration (PrevDecl) that is not in the scope where a
2439/// new declaration by the same name is being introduced. If the new
2440/// declaration occurs in a local scope, previous declarations with
2441/// linkage may still be considered previous declarations (C99
2442/// 6.2.2p4-5, C++ [basic.link]p6).
2443///
2444/// \param PrevDecl the previous declaration found by name
2445/// lookup
Mike Stump1eb44332009-09-09 15:08:12 +00002446///
Douglas Gregor8f301052009-02-24 19:23:27 +00002447/// \param DC the context in which the new declaration is being
2448/// declared.
2449///
2450/// \returns true if PrevDecl is an out-of-scope previous declaration
2451/// for a new delcaration with the same name.
Mike Stump1eb44332009-09-09 15:08:12 +00002452static bool
Douglas Gregor8f301052009-02-24 19:23:27 +00002453isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2454 ASTContext &Context) {
2455 if (!PrevDecl)
2456 return 0;
2457
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002458 if (!PrevDecl->hasLinkage())
2459 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00002460
2461 if (Context.getLangOptions().CPlusPlus) {
2462 // C++ [basic.link]p6:
2463 // If there is a visible declaration of an entity with linkage
2464 // having the same name and type, ignoring entities declared
2465 // outside the innermost enclosing namespace scope, the block
2466 // scope declaration declares that same entity and receives the
2467 // linkage of the previous declaration.
2468 DeclContext *OuterContext = DC->getLookupContext();
2469 if (!OuterContext->isFunctionOrMethod())
2470 // This rule only applies to block-scope declarations.
2471 return false;
2472 else {
2473 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2474 if (PrevOuterContext->isRecord())
2475 // We found a member function: ignore it.
2476 return false;
2477 else {
2478 // Find the innermost enclosing namespace for the new and
2479 // previous declarations.
2480 while (!OuterContext->isFileContext())
2481 OuterContext = OuterContext->getParent();
2482 while (!PrevOuterContext->isFileContext())
2483 PrevOuterContext = PrevOuterContext->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002484
Douglas Gregor8f301052009-02-24 19:23:27 +00002485 // The previous declaration is in a different namespace, so it
2486 // isn't the same function.
Mike Stump1eb44332009-09-09 15:08:12 +00002487 if (OuterContext->getPrimaryContext() !=
Douglas Gregor8f301052009-02-24 19:23:27 +00002488 PrevOuterContext->getPrimaryContext())
2489 return false;
2490 }
2491 }
2492 }
2493
Douglas Gregor8f301052009-02-24 19:23:27 +00002494 return true;
2495}
2496
John McCallb6217662010-03-15 10:12:16 +00002497static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
2498 CXXScopeSpec &SS = D.getCXXScopeSpec();
2499 if (!SS.isSet()) return;
2500 DD->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2501 SS.getRange());
2502}
2503
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002504NamedDecl*
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002505Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCalla93c9342009-12-07 02:54:59 +00002506 QualType R, TypeSourceInfo *TInfo,
John McCall68263142009-11-18 22:49:29 +00002507 LookupResult &Previous,
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002508 MultiTemplateParamsArg TemplateParamLists,
Douglas Gregorcda9c672009-02-16 17:45:42 +00002509 bool &Redeclaration) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002510 DeclarationName Name = GetNameForDeclarator(D);
2511
2512 // Check that there are no default arguments (C++ only).
2513 if (getLangOptions().CPlusPlus)
2514 CheckExtraCXXDefaultArguments(D);
2515
Douglas Gregor16573fa2010-04-19 22:54:31 +00002516 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
2517 assert(SCSpec != DeclSpec::SCS_typedef &&
2518 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnarab21b4052010-04-28 13:11:54 +00002519 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec, 0);
Douglas Gregor16573fa2010-04-19 22:54:31 +00002520 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002521 // mutable can only appear on non-static class members, so it's always
2522 // an error here
2523 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002524 D.setInvalidType();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002525 SC = VarDecl::None;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002526 }
Douglas Gregor16573fa2010-04-19 22:54:31 +00002527 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
2528 VarDecl::StorageClass SCAsWritten
Abramo Bagnarab21b4052010-04-28 13:11:54 +00002529 = StorageClassSpecToVarDeclStorageClass(SCSpec, DC);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002530
2531 IdentifierInfo *II = Name.getAsIdentifierInfo();
2532 if (!II) {
2533 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2534 << Name.getAsString();
2535 return 0;
2536 }
2537
Eli Friedman85a53192009-04-07 19:37:57 +00002538 DiagnoseFunctionSpecifiers(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +00002539
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00002540 if (!DC->isRecord() && S->getFnParent() == 0) {
2541 // C99 6.9p2: The storage-class specifiers auto and register shall not
2542 // appear in the declaration specifiers in an external declaration.
2543 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Mike Stump1eb44332009-09-09 15:08:12 +00002544
Chris Lattnerd4b19d52009-05-12 21:44:00 +00002545 // If this is a register variable with an asm label specified, then this
2546 // is a GNU extension.
2547 if (SC == VarDecl::Register && D.getAsmLabel())
2548 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2549 else
2550 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002551 D.setInvalidType();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002552 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002553 }
Douglas Gregor656de632009-03-11 23:52:16 +00002554 if (DC->isRecord() && !CurContext->isRecord()) {
2555 // This is an out-of-line definition of a static data member.
2556 if (SC == VarDecl::Static) {
Mike Stump1eb44332009-09-09 15:08:12 +00002557 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor656de632009-03-11 23:52:16 +00002558 diag::err_static_out_of_line)
Douglas Gregor849b2432010-03-31 17:46:05 +00002559 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor656de632009-03-11 23:52:16 +00002560 } else if (SC == VarDecl::None)
2561 SC = VarDecl::Static;
2562 }
Anders Carlssone98da2e2009-06-24 00:28:53 +00002563 if (SC == VarDecl::Static) {
2564 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2565 if (RD->isLocalClass())
Mike Stump1eb44332009-09-09 15:08:12 +00002566 Diag(D.getIdentifierLoc(),
Anders Carlssone98da2e2009-06-24 00:28:53 +00002567 diag::err_static_data_member_not_allowed_in_local_class)
2568 << Name << RD->getDeclName();
2569 }
2570 }
Mike Stump1eb44332009-09-09 15:08:12 +00002571
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002572 // Match up the template parameter lists with the scope specifier, then
2573 // determine whether we have a template or a template specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002574 bool isExplicitSpecialization = false;
Abramo Bagnara9b934882010-06-12 08:15:14 +00002575 unsigned NumMatchedTemplateParamLists = TemplateParamLists.size();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00002576 bool Invalid = false;
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002577 if (TemplateParameterList *TemplateParams
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002578 = MatchTemplateParametersToScopeSpecifier(
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002579 D.getDeclSpec().getSourceRange().getBegin(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002580 D.getCXXScopeSpec(),
Douglas Gregor27eeb5e2009-07-22 22:05:02 +00002581 (TemplateParameterList**)TemplateParamLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002582 TemplateParamLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00002583 /*never a friend*/ false,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00002584 isExplicitSpecialization,
2585 Invalid)) {
Abramo Bagnara9b934882010-06-12 08:15:14 +00002586 // All but one template parameter lists have been matching.
2587 --NumMatchedTemplateParamLists;
2588
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002589 if (TemplateParams->size() > 0) {
2590 // There is no such thing as a variable template.
2591 Diag(D.getIdentifierLoc(), diag::err_template_variable)
2592 << II
2593 << SourceRange(TemplateParams->getTemplateLoc(),
2594 TemplateParams->getRAngleLoc());
2595 return 0;
2596 } else {
2597 // There is an extraneous 'template<>' for this variable. Complain
2598 // about it, but allow the declaration of the variable.
Mike Stump1eb44332009-09-09 15:08:12 +00002599 Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor7cdbc582009-07-22 23:48:44 +00002600 diag::err_template_variable_noparams)
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002601 << II
2602 << SourceRange(TemplateParams->getTemplateLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +00002603 TemplateParams->getRAngleLoc());
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002604
2605 isExplicitSpecialization = true;
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002606 }
Mike Stump1eb44332009-09-09 15:08:12 +00002607 }
2608
Douglas Gregor16573fa2010-04-19 22:54:31 +00002609 VarDecl *NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2610 II, R, TInfo, SC, SCAsWritten);
Eli Friedman63054b32009-04-19 20:27:55 +00002611
Douglas Gregor0167f3c2010-07-14 23:14:12 +00002612 if (D.isInvalidType() || Invalid)
Chris Lattnereaaebc72009-04-25 08:06:05 +00002613 NewVD->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002614
John McCallb6217662010-03-15 10:12:16 +00002615 SetNestedNameSpecifier(NewVD, D);
2616
Abramo Bagnara9b934882010-06-12 08:15:14 +00002617 if (NumMatchedTemplateParamLists > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00002618 NewVD->setTemplateParameterListsInfo(Context,
2619 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00002620 (TemplateParameterList**)TemplateParamLists.release());
2621 }
2622
Eli Friedman63054b32009-04-19 20:27:55 +00002623 if (D.getDeclSpec().isThreadSpecified()) {
2624 if (NewVD->hasLocalStorage())
2625 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
Eli Friedman4fb71b02009-04-19 21:48:33 +00002626 else if (!Context.Target.isTLSSupported())
2627 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
Eli Friedman63054b32009-04-19 20:27:55 +00002628 else
2629 NewVD->setThreadSpecified(true);
2630 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002631
Douglas Gregor656de632009-03-11 23:52:16 +00002632 // Set the lexical context. If the declarator has a C++ scope specifier, the
2633 // lexical context will be different from the semantic context.
2634 NewVD->setLexicalDeclContext(CurContext);
2635
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002636 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002637 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002638
2639 // Handle GNU asm-label extension (encoded as an attribute).
2640 if (Expr *E = (Expr*) D.getAsmLabel()) {
2641 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00002642 StringLiteral *SE = cast<StringLiteral>(E);
Ted Kremenek3d2c43e2010-02-11 05:28:37 +00002643 NewVD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString()));
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002644 }
2645
John McCall8472af42010-03-16 21:48:18 +00002646 // Diagnose shadowed variables before filtering for scope.
John McCalla369a952010-03-20 04:12:52 +00002647 if (!D.getCXXScopeSpec().isSet())
John McCall053f4bd2010-03-22 09:20:08 +00002648 CheckShadow(S, NewVD, Previous);
John McCall8472af42010-03-16 21:48:18 +00002649
John McCall68263142009-11-18 22:49:29 +00002650 // Don't consider existing declarations that are in a different
2651 // scope and are out-of-semantic-context declarations (if the new
2652 // declaration has linkage).
2653 FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage());
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002654
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002655 // Merge the decl with the existing one if appropriate.
John McCall68263142009-11-18 22:49:29 +00002656 if (!Previous.empty()) {
2657 if (Previous.isSingleResult() &&
2658 isa<FieldDecl>(Previous.getFoundDecl()) &&
2659 D.getCXXScopeSpec().isSet()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002660 // The user tried to define a non-static data member
2661 // out-of-line (C++ [dcl.meaning]p1).
2662 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
2663 << D.getCXXScopeSpec().getRange();
John McCall68263142009-11-18 22:49:29 +00002664 Previous.clear();
Chris Lattnereaaebc72009-04-25 08:06:05 +00002665 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002666 }
2667 } else if (D.getCXXScopeSpec().isSet()) {
2668 // No previous declaration in the qualifying scope.
Douglas Gregor3f093272009-10-13 21:16:44 +00002669 Diag(D.getIdentifierLoc(), diag::err_no_member)
2670 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
2671 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00002672 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002673 }
2674
John McCall68263142009-11-18 22:49:29 +00002675 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002676
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002677 // This is an explicit specialization of a static data member. Check it.
2678 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
John McCall68263142009-11-18 22:49:29 +00002679 CheckMemberSpecialization(NewVD, Previous))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002680 NewVD->setInvalidDecl();
John McCall68263142009-11-18 22:49:29 +00002681
Ryan Flynn478fbc62009-07-25 22:29:44 +00002682 // attributes declared post-definition are currently ignored
John McCall68263142009-11-18 22:49:29 +00002683 if (Previous.isSingleResult()) {
Sebastian Redl31310a22010-02-01 20:16:42 +00002684 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
2685 if (Def && (Def = Def->getDefinition()) &&
2686 Def != NewVD && D.hasAttributes()) {
Ryan Flynn478fbc62009-07-25 22:29:44 +00002687 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
2688 Diag(Def->getLocation(), diag::note_previous_definition);
2689 }
2690 }
2691
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002692 // If this is a locally-scoped extern C variable, update the map of
2693 // such variables.
Douglas Gregor48a83b52009-09-12 00:17:51 +00002694 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
Chris Lattnereaaebc72009-04-25 08:06:05 +00002695 !NewVD->isInvalidDecl())
John McCall68263142009-11-18 22:49:29 +00002696 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002697
2698 return NewVD;
2699}
2700
John McCall053f4bd2010-03-22 09:20:08 +00002701/// \brief Diagnose variable or built-in function shadowing. Implements
2702/// -Wshadow.
John McCall8472af42010-03-16 21:48:18 +00002703///
John McCall053f4bd2010-03-22 09:20:08 +00002704/// This method is called whenever a VarDecl is added to a "useful"
2705/// scope.
John McCall8472af42010-03-16 21:48:18 +00002706///
John McCalla369a952010-03-20 04:12:52 +00002707/// \param S the scope in which the shadowing name is being declared
2708/// \param R the lookup of the name
John McCall8472af42010-03-16 21:48:18 +00002709///
John McCall053f4bd2010-03-22 09:20:08 +00002710void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCall8472af42010-03-16 21:48:18 +00002711 // Return if warning is ignored.
2712 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow) == Diagnostic::Ignored)
2713 return;
2714
John McCalla369a952010-03-20 04:12:52 +00002715 // Don't diagnose declarations at file scope. The scope might not
2716 // have a DeclContext if (e.g.) we're parsing a function prototype.
2717 DeclContext *NewDC = static_cast<DeclContext*>(S->getEntity());
2718 if (NewDC && NewDC->isFileContext())
John McCall8472af42010-03-16 21:48:18 +00002719 return;
John McCalla369a952010-03-20 04:12:52 +00002720
2721 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregorc48c9162010-03-17 16:03:44 +00002722 if (R.getResultKind() != LookupResult::Found)
John McCall8472af42010-03-16 21:48:18 +00002723 return;
John McCall8472af42010-03-16 21:48:18 +00002724
John McCall8472af42010-03-16 21:48:18 +00002725 NamedDecl* ShadowedDecl = R.getFoundDecl();
2726 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
2727 return;
2728
John McCalla369a952010-03-20 04:12:52 +00002729 DeclContext *OldDC = ShadowedDecl->getDeclContext();
2730
2731 // Only warn about certain kinds of shadowing for class members.
2732 if (NewDC && NewDC->isRecord()) {
2733 // In particular, don't warn about shadowing non-class members.
2734 if (!OldDC->isRecord())
2735 return;
2736
2737 // TODO: should we warn about static data members shadowing
2738 // static data members from base classes?
2739
2740 // TODO: don't diagnose for inaccessible shadowed members.
2741 // This is hard to do perfectly because we might friend the
2742 // shadowing context, but that's just a false negative.
2743 }
2744
2745 // Determine what kind of declaration we're shadowing.
John McCall8472af42010-03-16 21:48:18 +00002746 unsigned Kind;
John McCalla369a952010-03-20 04:12:52 +00002747 if (isa<RecordDecl>(OldDC)) {
John McCall8472af42010-03-16 21:48:18 +00002748 if (isa<FieldDecl>(ShadowedDecl))
2749 Kind = 3; // field
2750 else
2751 Kind = 2; // static data member
John McCalla369a952010-03-20 04:12:52 +00002752 } else if (OldDC->isFileContext())
John McCall8472af42010-03-16 21:48:18 +00002753 Kind = 1; // global
2754 else
2755 Kind = 0; // local
2756
John McCalla369a952010-03-20 04:12:52 +00002757 DeclarationName Name = R.getLookupName();
2758
John McCall8472af42010-03-16 21:48:18 +00002759 // Emit warning and note.
John McCalla369a952010-03-20 04:12:52 +00002760 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCall8472af42010-03-16 21:48:18 +00002761 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
2762}
2763
John McCall053f4bd2010-03-22 09:20:08 +00002764/// \brief Check -Wshadow without the advantage of a previous lookup.
2765void Sema::CheckShadow(Scope *S, VarDecl *D) {
2766 LookupResult R(*this, D->getDeclName(), D->getLocation(),
2767 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
2768 LookupName(R, S);
2769 CheckShadow(S, D, R);
2770}
2771
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002772/// \brief Perform semantic checking on a newly-created variable
2773/// declaration.
2774///
2775/// This routine performs all of the type-checking required for a
Douglas Gregor180bb632009-05-01 15:47:09 +00002776/// variable declaration once it has been built. It is used both to
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002777/// check variables after they have been parsed and their declarators
Douglas Gregor180bb632009-05-01 15:47:09 +00002778/// have been translated into a declaration, and to check variables
2779/// that have been instantiated from a template.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002780///
Chris Lattnereaaebc72009-04-25 08:06:05 +00002781/// Sets NewVD->isInvalidDecl() if an error was encountered.
John McCall68263142009-11-18 22:49:29 +00002782void Sema::CheckVariableDeclaration(VarDecl *NewVD,
2783 LookupResult &Previous,
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002784 bool &Redeclaration) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00002785 // If the decl is already known invalid, don't check it.
2786 if (NewVD->isInvalidDecl())
2787 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002788
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002789 QualType T = NewVD->getType();
2790
John McCallc12c5bb2010-05-15 11:32:37 +00002791 if (T->isObjCObjectType()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002792 Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002793 return NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002794 }
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002796 // Emit an error if an address space was applied to decl with local storage.
2797 // This includes arrays of objects with address space qualifiers, but not
2798 // automatic variables that point to other address spaces.
2799 // ISO/IEC TR 18037 S5.1.2
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002800 if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
2801 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002802 return NewVD->setInvalidDecl();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002803 }
Fariborz Jahanian7b5b3172009-02-21 19:44:02 +00002804
Mike Stumpf33651c2009-04-14 00:57:29 +00002805 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002806 && !NewVD->hasAttr<BlocksAttr>())
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002807 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Fariborz Jahanian7b5b3172009-02-21 19:44:02 +00002808
Chris Lattner38c5ebd2009-04-19 05:21:20 +00002809 bool isVM = T->isVariablyModifiedType();
Chris Lattnerbe6d2592009-07-19 20:17:11 +00002810 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
Chris Lattner6d97e5e2010-03-01 20:59:53 +00002811 NewVD->hasAttr<BlocksAttr>() ||
2812 // FIXME: We need to diagnose jumps passed initialized variables in C++.
2813 // However, this turns on the scope checker for everything with a variable
2814 // which may impact compile time. See if we can find a better solution
2815 // to this, perhaps only checking functions that contain gotos in C++?
2816 (LangOpts.CPlusPlus && NewVD->hasLocalStorage()))
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00002817 FunctionNeedsScopeChecking() = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002818
Chris Lattner38c5ebd2009-04-19 05:21:20 +00002819 if ((isVM && NewVD->hasLinkage()) ||
2820 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002821 bool SizeIsNegative;
2822 QualType FixedTy =
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002823 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
Mike Stump1eb44332009-09-09 15:08:12 +00002824
Chris Lattnereaaebc72009-04-25 08:06:05 +00002825 if (FixedTy.isNull() && T->isVariableArrayType()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002826 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002827 // FIXME: This won't give the correct result for
2828 // int a[10][n];
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002829 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002830
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002831 if (NewVD->isFileVarDecl())
2832 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnereaaebc72009-04-25 08:06:05 +00002833 << SizeRange;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002834 else if (NewVD->getStorageClass() == VarDecl::Static)
2835 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00002836 << SizeRange;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002837 else
2838 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00002839 << SizeRange;
2840 return NewVD->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002841 }
2842
Chris Lattnereaaebc72009-04-25 08:06:05 +00002843 if (FixedTy.isNull()) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002844 if (NewVD->isFileVarDecl())
2845 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
2846 else
2847 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002848 return NewVD->setInvalidDecl();
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002849 }
Mike Stump1eb44332009-09-09 15:08:12 +00002850
Chris Lattnereaaebc72009-04-25 08:06:05 +00002851 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
2852 NewVD->setType(FixedTy);
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002853 }
2854
John McCall68263142009-11-18 22:49:29 +00002855 if (Previous.empty() && NewVD->isExternC()) {
Douglas Gregor63935192009-03-02 00:19:53 +00002856 // Since we did not find anything by this name and we're declaring
2857 // an extern "C" variable, look for a non-visible extern "C"
2858 // declaration with the same name.
2859 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002860 = LocallyScopedExternalDecls.find(NewVD->getDeclName());
Douglas Gregor63935192009-03-02 00:19:53 +00002861 if (Pos != LocallyScopedExternalDecls.end())
John McCall68263142009-11-18 22:49:29 +00002862 Previous.addDecl(Pos->second);
Douglas Gregor63935192009-03-02 00:19:53 +00002863 }
2864
Chris Lattnereaaebc72009-04-25 08:06:05 +00002865 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002866 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
2867 << T;
Chris Lattnereaaebc72009-04-25 08:06:05 +00002868 return NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002869 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002870
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002871 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00002872 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
2873 return NewVD->setInvalidDecl();
2874 }
Mike Stump1eb44332009-09-09 15:08:12 +00002875
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002876 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpc975bb02009-05-01 23:41:47 +00002877 Diag(NewVD->getLocation(), diag::err_block_on_vm);
2878 return NewVD->setInvalidDecl();
2879 }
2880
Sebastian Redlf9ea1f32010-07-12 23:11:43 +00002881 // Function pointers and references cannot have qualified function type, only
2882 // function pointer-to-members can do that.
2883 QualType Pointee;
2884 unsigned PtrOrRef = 0;
2885 if (const PointerType *Ptr = T->getAs<PointerType>())
2886 Pointee = Ptr->getPointeeType();
2887 else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
2888 Pointee = Ref->getPointeeType();
2889 PtrOrRef = 1;
2890 }
2891 if (!Pointee.isNull() && Pointee->isFunctionProtoType() &&
2892 Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) {
2893 Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer)
2894 << PtrOrRef;
2895 return NewVD->setInvalidDecl();
2896 }
2897
John McCall68263142009-11-18 22:49:29 +00002898 if (!Previous.empty()) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00002899 Redeclaration = true;
John McCall68263142009-11-18 22:49:29 +00002900 MergeVarDecl(NewVD, Previous);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002901 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002902}
2903
Douglas Gregora8f32e02009-10-06 17:59:45 +00002904/// \brief Data used with FindOverriddenMethod
2905struct FindOverriddenMethodData {
2906 Sema *S;
2907 CXXMethodDecl *Method;
2908};
2909
2910/// \brief Member lookup function that determines whether a given C++
2911/// method overrides a method in a base class, to be used with
2912/// CXXRecordDecl::lookupInBases().
John McCallaf8e6ed2009-11-12 03:15:40 +00002913static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002914 CXXBasePath &Path,
2915 void *UserData) {
2916 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlsson95496802009-11-26 20:50:40 +00002917
Douglas Gregora8f32e02009-10-06 17:59:45 +00002918 FindOverriddenMethodData *Data
2919 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlsson95496802009-11-26 20:50:40 +00002920
2921 DeclarationName Name = Data->Method->getDeclName();
2922
2923 // FIXME: Do we care about other names here too?
2924 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCallad00b772010-06-16 08:42:20 +00002925 // We really want to find the base class destructor here.
Anders Carlsson95496802009-11-26 20:50:40 +00002926 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
2927 CanQualType CT = Data->S->Context.getCanonicalType(T);
2928
Anders Carlsson1a689722009-11-27 01:26:58 +00002929 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlsson95496802009-11-26 20:50:40 +00002930 }
2931
2932 for (Path.Decls = BaseRecord->lookup(Name);
Douglas Gregora8f32e02009-10-06 17:59:45 +00002933 Path.Decls.first != Path.Decls.second;
2934 ++Path.Decls.first) {
John McCall52a02752010-06-16 09:33:39 +00002935 NamedDecl *D = *Path.Decls.first;
John McCallad00b772010-06-16 08:42:20 +00002936 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
2937 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregora8f32e02009-10-06 17:59:45 +00002938 return true;
2939 }
2940 }
2941
2942 return false;
2943}
2944
Sebastian Redla165da02009-11-18 21:51:29 +00002945/// AddOverriddenMethods - See if a method overrides any in the base classes,
2946/// and if so, check that it's a valid override and remember it.
2947void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2948 // Look for virtual methods in base classes that this method might override.
2949 CXXBasePaths Paths;
2950 FindOverriddenMethodData Data;
2951 Data.Method = MD;
2952 Data.S = this;
2953 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
2954 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
2955 E = Paths.found_decls_end(); I != E; ++I) {
2956 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
2957 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Sean Huntbbd37c62009-11-21 08:43:09 +00002958 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
2959 !CheckOverridingFunctionAttributes(MD, OldMD))
Anders Carlsson3aaf4862009-12-04 05:51:56 +00002960 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redla165da02009-11-18 21:51:29 +00002961 }
2962 }
2963 }
2964}
2965
Mike Stump1eb44332009-09-09 15:08:12 +00002966NamedDecl*
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002967Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCalla93c9342009-12-07 02:54:59 +00002968 QualType R, TypeSourceInfo *TInfo,
John McCall68263142009-11-18 22:49:29 +00002969 LookupResult &Previous,
Douglas Gregore542c862009-06-23 23:11:28 +00002970 MultiTemplateParamsArg TemplateParamLists,
Chris Lattnereaaebc72009-04-25 08:06:05 +00002971 bool IsFunctionDefinition, bool &Redeclaration) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002972 assert(R.getTypePtr()->isFunctionType());
2973
2974 DeclarationName Name = GetNameForDeclarator(D);
2975 FunctionDecl::StorageClass SC = FunctionDecl::None;
2976 switch (D.getDeclSpec().getStorageClassSpec()) {
2977 default: assert(0 && "Unknown storage class!");
2978 case DeclSpec::SCS_auto:
2979 case DeclSpec::SCS_register:
2980 case DeclSpec::SCS_mutable:
Mike Stump1eb44332009-09-09 15:08:12 +00002981 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor04495c82009-02-24 01:23:02 +00002982 diag::err_typecheck_sclass_func);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002983 D.setInvalidType();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002984 break;
2985 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
2986 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
Douglas Gregor04495c82009-02-24 01:23:02 +00002987 case DeclSpec::SCS_static: {
Douglas Gregor656de632009-03-11 23:52:16 +00002988 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor04495c82009-02-24 01:23:02 +00002989 // C99 6.7.1p5:
2990 // The declaration of an identifier for a function that has
2991 // block scope shall have no explicit storage-class specifier
2992 // other than extern
2993 // See also (C++ [dcl.stc]p4).
Mike Stump1eb44332009-09-09 15:08:12 +00002994 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor04495c82009-02-24 01:23:02 +00002995 diag::err_static_block_func);
2996 SC = FunctionDecl::None;
2997 } else
Mike Stump1eb44332009-09-09 15:08:12 +00002998 SC = FunctionDecl::Static;
Douglas Gregor04495c82009-02-24 01:23:02 +00002999 break;
3000 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003001 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
3002 }
3003
Eli Friedman63054b32009-04-19 20:27:55 +00003004 if (D.getDeclSpec().isThreadSpecified())
3005 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3006
John McCall3f9a8a62009-08-11 06:59:38 +00003007 bool isFriend = D.getDeclSpec().isFriendSpecified();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003008 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor021c3b32009-03-11 23:00:04 +00003009 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003010 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
3011
Douglas Gregor16573fa2010-04-19 22:54:31 +00003012 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3013 FunctionDecl::StorageClass SCAsWritten
Abramo Bagnarab21b4052010-04-28 13:11:54 +00003014 = StorageClassSpecToFunctionDeclStorageClass(SCSpec, DC);
Douglas Gregor16573fa2010-04-19 22:54:31 +00003015
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003016 // Check that the return type is not an abstract class type.
Anders Carlsson8211eff2009-03-24 01:19:16 +00003017 // For record types, this is done by the AbstractClassUsageDiagnoser once
Mike Stump1eb44332009-09-09 15:08:12 +00003018 // the class has been completely parsed.
Anders Carlsson8211eff2009-03-24 01:19:16 +00003019 if (!DC->isRecord() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003020 RequireNonAbstractType(D.getIdentifierLoc(),
John McCall183700f2009-09-21 23:43:11 +00003021 R->getAs<FunctionType>()->getResultType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003022 diag::err_abstract_type_in_decl,
Anders Carlsson8211eff2009-03-24 01:19:16 +00003023 AbstractReturnType))
Chris Lattnereaaebc72009-04-25 08:06:05 +00003024 D.setInvalidType();
Mike Stump1eb44332009-09-09 15:08:12 +00003025
Chris Lattnerbb749822009-04-11 19:17:25 +00003026 // Do not allow returning a objc interface by-value.
John McCallc12c5bb2010-05-15 11:32:37 +00003027 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
Chris Lattnerbb749822009-04-11 19:17:25 +00003028 Diag(D.getIdentifierLoc(),
3029 diag::err_object_cannot_be_passed_returned_by_value) << 0
John McCall183700f2009-09-21 23:43:11 +00003030 << R->getAs<FunctionType>()->getResultType();
Chris Lattnereaaebc72009-04-25 08:06:05 +00003031 D.setInvalidType();
Chris Lattnerbb749822009-04-11 19:17:25 +00003032 }
Douglas Gregore542c862009-06-23 23:11:28 +00003033
Douglas Gregor021c3b32009-03-11 23:00:04 +00003034 bool isVirtualOkay = false;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003035 FunctionDecl *NewFD;
John McCall02cace72009-08-28 07:59:38 +00003036
John McCall3f9a8a62009-08-11 06:59:38 +00003037 if (isFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00003038 // C++ [class.friend]p5
3039 // A function can be defined in a friend declaration of a
3040 // class . . . . Such a function is implicitly inline.
3041 isInline |= IsFunctionDefinition;
John McCall02cace72009-08-28 07:59:38 +00003042 }
John McCall3f9a8a62009-08-11 06:59:38 +00003043
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003044 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003045 // This is a C++ constructor declaration.
3046 assert(DC->isRecord() &&
3047 "Constructors can only be declared in a member context");
3048
Chris Lattner65401802009-04-25 08:28:21 +00003049 R = CheckConstructorDeclarator(D, R, SC);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003050
3051 // Create the new declaration
Mike Stump1eb44332009-09-09 15:08:12 +00003052 NewFD = CXXConstructorDecl::Create(Context,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003053 cast<CXXRecordDecl>(DC),
John McCalla93c9342009-12-07 02:54:59 +00003054 D.getIdentifierLoc(), Name, R, TInfo,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003055 isExplicit, isInline,
3056 /*isImplicitlyDeclared=*/false);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003057 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003058 // This is a C++ destructor declaration.
3059 if (DC->isRecord()) {
Douglas Gregord92ec472010-07-01 05:10:53 +00003060 R = CheckDestructorDeclarator(D, R, SC);
Mike Stump1eb44332009-09-09 15:08:12 +00003061
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003062 NewFD = CXXDestructorDecl::Create(Context,
3063 cast<CXXRecordDecl>(DC),
Mike Stump1eb44332009-09-09 15:08:12 +00003064 D.getIdentifierLoc(), Name, R,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003065 isInline,
3066 /*isImplicitlyDeclared=*/false);
John McCall21ef0fa2010-03-11 09:03:00 +00003067 NewFD->setTypeSourceInfo(TInfo);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003068
Douglas Gregor021c3b32009-03-11 23:00:04 +00003069 isVirtualOkay = true;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003070 } else {
3071 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
3072
3073 // Create a FunctionDecl to satisfy the function definition parsing
3074 // code path.
3075 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00003076 Name, R, TInfo, SC, SCAsWritten, isInline,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003077 /*hasPrototype=*/true);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003078 D.setInvalidType();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003079 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003080 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003081 if (!DC->isRecord()) {
3082 Diag(D.getIdentifierLoc(),
3083 diag::err_conv_function_not_member);
3084 return 0;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003085 }
Mike Stump1eb44332009-09-09 15:08:12 +00003086
Chris Lattner6e475012009-04-25 08:35:12 +00003087 CheckConversionDeclarator(D, R, SC);
3088 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
John McCalla93c9342009-12-07 02:54:59 +00003089 D.getIdentifierLoc(), Name, R, TInfo,
Chris Lattner6e475012009-04-25 08:35:12 +00003090 isInline, isExplicit);
Mike Stump1eb44332009-09-09 15:08:12 +00003091
Chris Lattner6e475012009-04-25 08:35:12 +00003092 isVirtualOkay = true;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003093 } else if (DC->isRecord()) {
Anders Carlsson4649cac2009-04-30 22:41:11 +00003094 // If the of the function is the same as the name of the record, then this
Mike Stump1eb44332009-09-09 15:08:12 +00003095 // must be an invalid constructor that has a return type.
3096 // (The parser checks for a return type and makes the declarator a
Anders Carlsson4649cac2009-04-30 22:41:11 +00003097 // constructor if it has no return type).
Mike Stump1eb44332009-09-09 15:08:12 +00003098 // must have an invalid constructor that has a return type
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00003099 if (Name.getAsIdentifierInfo() &&
3100 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
Anders Carlsson4649cac2009-04-30 22:41:11 +00003101 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
3102 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3103 << SourceRange(D.getIdentifierLoc());
3104 return 0;
3105 }
Mike Stump1eb44332009-09-09 15:08:12 +00003106
Anders Carlsson67bf2e72009-11-15 18:59:32 +00003107 bool isStatic = SC == FunctionDecl::Static;
3108
3109 // [class.free]p1:
3110 // Any allocation function for a class T is a static member
3111 // (even if not explicitly declared static).
3112 if (Name.getCXXOverloadedOperator() == OO_New ||
3113 Name.getCXXOverloadedOperator() == OO_Array_New)
3114 isStatic = true;
Anders Carlsson1f126bd2009-11-15 19:08:46 +00003115
3116 // [class.free]p6 Any deallocation function for a class X is a static member
3117 // (even if not explicitly declared static).
3118 if (Name.getCXXOverloadedOperator() == OO_Delete ||
3119 Name.getCXXOverloadedOperator() == OO_Array_Delete)
3120 isStatic = true;
Anders Carlsson67bf2e72009-11-15 18:59:32 +00003121
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003122 // This is a C++ method declaration.
3123 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
John McCalla93c9342009-12-07 02:54:59 +00003124 D.getIdentifierLoc(), Name, R, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00003125 isStatic, SCAsWritten, isInline);
Douglas Gregor021c3b32009-03-11 23:00:04 +00003126
Anders Carlsson1f126bd2009-11-15 19:08:46 +00003127 isVirtualOkay = !isStatic;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003128 } else {
Douglas Gregord874def2009-03-19 18:33:54 +00003129 // Determine whether the function was written with a
3130 // prototype. This true when:
3131 // - we're in C++ (where every function has a prototype),
3132 // - there is a prototype in the declarator, or
3133 // - the type R of the function is some kind of typedef or other reference
3134 // to a type name (which eventually refers to a function type).
Mike Stump1eb44332009-09-09 15:08:12 +00003135 bool HasPrototype =
Chris Lattner0d48bf92009-03-17 23:17:04 +00003136 getLangOptions().CPlusPlus ||
Douglas Gregor13d7a322009-03-19 18:14:46 +00003137 (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
Douglas Gregord1659a62009-03-23 16:26:51 +00003138 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
Mike Stump1eb44332009-09-09 15:08:12 +00003139
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003140 NewFD = FunctionDecl::Create(Context, DC,
3141 D.getIdentifierLoc(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00003142 Name, R, TInfo, SC, SCAsWritten, isInline,
3143 HasPrototype);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003144 }
3145
Chris Lattnereaaebc72009-04-25 08:06:05 +00003146 if (D.isInvalidType())
Chris Lattner584be452009-04-25 05:44:12 +00003147 NewFD->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003148
John McCallb6217662010-03-15 10:12:16 +00003149 SetNestedNameSpecifier(NewFD, D);
3150
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003151 // Set the lexical context. If the declarator has a C++
John McCall02cace72009-08-28 07:59:38 +00003152 // scope specifier, or is the object of a friend declaration, the
3153 // lexical context will be different from the semantic context.
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003154 NewFD->setLexicalDeclContext(CurContext);
3155
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003156 // Match up the template parameter lists with the scope specifier, then
3157 // determine whether we have a template or a template specialization.
Douglas Gregorc5c903a2009-06-24 00:23:40 +00003158 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003159 bool isExplicitSpecialization = false;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003160 bool isFunctionTemplateSpecialization = false;
Abramo Bagnara9b934882010-06-12 08:15:14 +00003161 unsigned NumMatchedTemplateParamLists = TemplateParamLists.size();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00003162 bool Invalid = false;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003163 if (TemplateParameterList *TemplateParams
3164 = MatchTemplateParametersToScopeSpecifier(
3165 D.getDeclSpec().getSourceRange().getBegin(),
3166 D.getCXXScopeSpec(),
Douglas Gregor27eeb5e2009-07-22 22:05:02 +00003167 (TemplateParameterList**)TemplateParamLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003168 TemplateParamLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00003169 isFriend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00003170 isExplicitSpecialization,
3171 Invalid)) {
Abramo Bagnara9b934882010-06-12 08:15:14 +00003172 // All but one template parameter lists have been matching.
3173 --NumMatchedTemplateParamLists;
3174
Douglas Gregorc5c903a2009-06-24 00:23:40 +00003175 if (TemplateParams->size() > 0) {
3176 // This is a function template
Mike Stump1eb44332009-09-09 15:08:12 +00003177
Douglas Gregor05396e22009-08-25 17:23:04 +00003178 // Check that we can declare a template here.
3179 if (CheckTemplateDeclScope(S, TemplateParams))
3180 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003181
Douglas Gregord60e1052009-08-27 16:57:43 +00003182 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
Douglas Gregorc5c903a2009-06-24 00:23:40 +00003183 NewFD->getLocation(),
3184 Name, TemplateParams,
3185 NewFD);
Douglas Gregord60e1052009-08-27 16:57:43 +00003186 FunctionTemplate->setLexicalDeclContext(CurContext);
Douglas Gregorc5c903a2009-06-24 00:23:40 +00003187 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
3188 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003189 // This is a function template specialization.
3190 isFunctionTemplateSpecialization = true;
John McCall7ad650f2010-03-24 07:46:06 +00003191
John McCallaf2094e2010-04-08 09:05:18 +00003192 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
John McCall7ad650f2010-03-24 07:46:06 +00003193 if (isFriend && isFunctionTemplateSpecialization) {
John McCall5fd378b2010-03-24 08:27:58 +00003194 // We want to remove the "template<>", found here.
3195 SourceRange RemoveRange = TemplateParams->getSourceRange();
3196
3197 // If we remove the template<> and the name is not a
3198 // template-id, we're actually silently creating a problem:
3199 // the friend declaration will refer to an untemplated decl,
3200 // and clearly the user wants a template specialization. So
3201 // we need to insert '<>' after the name.
3202 SourceLocation InsertLoc;
3203 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
3204 InsertLoc = D.getName().getSourceRange().getEnd();
3205 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
3206 }
3207
John McCall7ad650f2010-03-24 07:46:06 +00003208 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
John McCall5fd378b2010-03-24 08:27:58 +00003209 << Name << RemoveRange
Douglas Gregor849b2432010-03-31 17:46:05 +00003210 << FixItHint::CreateRemoval(RemoveRange)
3211 << FixItHint::CreateInsertion(InsertLoc, "<>");
John McCall7ad650f2010-03-24 07:46:06 +00003212 }
Douglas Gregorc5c903a2009-06-24 00:23:40 +00003213 }
Mike Stump1eb44332009-09-09 15:08:12 +00003214 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00003215
3216 if (NumMatchedTemplateParamLists > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00003217 NewFD->setTemplateParameterListsInfo(Context,
3218 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00003219 (TemplateParameterList**)TemplateParamLists.release());
3220 }
3221
Douglas Gregor0167f3c2010-07-14 23:14:12 +00003222 if (Invalid) {
3223 NewFD->setInvalidDecl();
3224 if (FunctionTemplate)
3225 FunctionTemplate->setInvalidDecl();
3226 }
3227
Douglas Gregor021c3b32009-03-11 23:00:04 +00003228 // C++ [dcl.fct.spec]p5:
3229 // The virtual specifier shall only be used in declarations of
3230 // nonstatic class member functions that appear within a
3231 // member-specification of a class declaration; see 10.3.
3232 //
Chris Lattnereaaebc72009-04-25 08:06:05 +00003233 if (isVirtual && !NewFD->isInvalidDecl()) {
Douglas Gregor021c3b32009-03-11 23:00:04 +00003234 if (!isVirtualOkay) {
Mike Stump1eb44332009-09-09 15:08:12 +00003235 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Douglas Gregor021c3b32009-03-11 23:00:04 +00003236 diag::err_virtual_non_function);
3237 } else if (!CurContext->isRecord()) {
3238 // 'virtual' was specified outside of the class.
3239 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
Douglas Gregor849b2432010-03-31 17:46:05 +00003240 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
Douglas Gregor021c3b32009-03-11 23:00:04 +00003241 } else {
3242 // Okay: Add virtual to the method.
Douglas Gregor021c3b32009-03-11 23:00:04 +00003243 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00003244 CurClass->setMethodAsVirtual(NewFD);
Douglas Gregor021c3b32009-03-11 23:00:04 +00003245 }
3246 }
3247
Anders Carlsson0757c8c2010-01-24 16:49:46 +00003248 // C++ [dcl.fct.spec]p6:
3249 // The explicit specifier shall be used only in the declaration of a
3250 // constructor or conversion function within its class definition; see 12.3.1
3251 // and 12.3.2.
3252 if (isExplicit && !NewFD->isInvalidDecl()) {
3253 if (!CurContext->isRecord()) {
3254 // 'explicit' was specified outside of the class.
3255 Diag(D.getDeclSpec().getExplicitSpecLoc(),
3256 diag::err_explicit_out_of_class)
Douglas Gregor849b2432010-03-31 17:46:05 +00003257 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
Anders Carlsson0757c8c2010-01-24 16:49:46 +00003258 } else if (!isa<CXXConstructorDecl>(NewFD) &&
3259 !isa<CXXConversionDecl>(NewFD)) {
3260 // 'explicit' was specified on a function that wasn't a constructor
3261 // or conversion function.
3262 Diag(D.getDeclSpec().getExplicitSpecLoc(),
3263 diag::err_explicit_non_ctor_or_conv_function)
Douglas Gregor849b2432010-03-31 17:46:05 +00003264 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
Anders Carlsson0757c8c2010-01-24 16:49:46 +00003265 }
3266 }
3267
John McCall68263142009-11-18 22:49:29 +00003268 // Filter out previous declarations that don't match the scope.
3269 FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
3270
Douglas Gregora735b202009-10-13 14:39:41 +00003271 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00003272 // DC is the namespace in which the function is being declared.
3273 assert((DC->isFileContext() || !Previous.empty()) &&
3274 "previously-undeclared friend function being created "
3275 "in a non-namespace context");
3276
John McCallb0cb0222010-03-27 05:57:59 +00003277 // For now, claim that the objects have no previous declaration.
Douglas Gregora735b202009-10-13 14:39:41 +00003278 if (FunctionTemplate) {
John McCallb0cb0222010-03-27 05:57:59 +00003279 FunctionTemplate->setObjectOfFriendDecl(false);
Douglas Gregora735b202009-10-13 14:39:41 +00003280 FunctionTemplate->setAccess(AS_public);
3281 }
John McCall77e8b112010-04-13 20:37:33 +00003282 NewFD->setObjectOfFriendDecl(false);
Douglas Gregora735b202009-10-13 14:39:41 +00003283 NewFD->setAccess(AS_public);
3284 }
3285
Mike Stump1eb44332009-09-09 15:08:12 +00003286 if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
Douglas Gregor656de632009-03-11 23:52:16 +00003287 !CurContext->isRecord()) {
3288 // C++ [class.static]p1:
3289 // A data or function member of a class may be declared static
3290 // in a class definition, in which case it is a static member of
3291 // the class.
3292
3293 // Complain about the 'static' specifier if it's on an out-of-line
3294 // member function definition.
Mike Stump1eb44332009-09-09 15:08:12 +00003295 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor656de632009-03-11 23:52:16 +00003296 diag::err_static_out_of_line)
Douglas Gregor849b2432010-03-31 17:46:05 +00003297 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor656de632009-03-11 23:52:16 +00003298 }
3299
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003300 // Handle GNU asm-label extension (encoded as an attribute).
3301 if (Expr *E = (Expr*) D.getAsmLabel()) {
3302 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00003303 StringLiteral *SE = cast<StringLiteral>(E);
Ted Kremenek3d2c43e2010-02-11 05:28:37 +00003304 NewFD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString()));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003305 }
3306
Chris Lattner2dbd2852009-04-25 06:12:16 +00003307 // Copy the parameter declarations from the declarator D to the function
3308 // declaration NewFD, if they are available. First scavenge them into Params.
3309 llvm::SmallVector<ParmVarDecl*, 16> Params;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003310 if (D.getNumTypeObjects() > 0) {
3311 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3312
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003313 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
3314 // function that takes no arguments, not a function that takes a
3315 // single void argument.
3316 // We let through "const void" here because Sema::GetTypeForDeclarator
3317 // already checks for that case.
3318 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3319 FTI.ArgInfo[0].Param &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00003320 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
Chris Lattner2dbd2852009-04-25 06:12:16 +00003321 // Empty arg list, don't push any params.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003322 ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003323
3324 // In C++, the empty parameter-type-list must be spelled "void"; a
3325 // typedef of void is not permitted.
3326 if (getLangOptions().CPlusPlus &&
Chris Lattner584be452009-04-25 05:44:12 +00003327 Param->getType().getUnqualifiedType() != Context.VoidTy)
Douglas Gregora3a83512009-04-01 23:51:29 +00003328 Diag(Param->getLocation(), diag::err_param_typedef_of_void);
Chris Lattner2dbd2852009-04-25 06:12:16 +00003329 // FIXME: Leaks decl?
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003330 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00003331 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
3332 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
3333 assert(Param->getDeclContext() != NewFD && "Was set before ?");
3334 Param->setDeclContext(NewFD);
3335 Params.push_back(Param);
John McCallf19de1c2010-04-14 01:27:20 +00003336
3337 if (Param->isInvalidDecl())
3338 NewFD->setInvalidDecl();
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00003339 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003340 }
Mike Stump1eb44332009-09-09 15:08:12 +00003341
John McCall183700f2009-09-21 23:43:11 +00003342 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner1ad9b282009-04-25 06:03:53 +00003343 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003344 // following example, we'll need to synthesize (unnamed)
3345 // parameters for use in the declaration.
3346 //
3347 // @code
3348 // typedef void fn(int);
3349 // fn f;
3350 // @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003351
Chris Lattner1ad9b282009-04-25 06:03:53 +00003352 // Synthesize a parameter for each argument type.
Chris Lattner1ad9b282009-04-25 06:03:53 +00003353 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
3354 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCall82dc0092010-06-04 11:21:44 +00003355 ParmVarDecl *Param =
3356 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
Chris Lattner1ad9b282009-04-25 06:03:53 +00003357 Params.push_back(Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003358 }
Chris Lattner84bb9442009-04-25 18:38:18 +00003359 } else {
3360 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
3361 "Should not need args for typedef of non-prototype fn");
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003362 }
Chris Lattner2dbd2852009-04-25 06:12:16 +00003363 // Finally, we know we have the right number of parameters, install them.
Douglas Gregor838db382010-02-11 01:19:42 +00003364 NewFD->setParams(Params.data(), Params.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003365
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003366 // If the declarator is a template-id, translate the parser's template
3367 // argument list into our AST format.
3368 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00003369 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003370 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
3371 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00003372 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
3373 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003374 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3375 TemplateId->getTemplateArgs(),
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003376 TemplateId->NumArgs);
3377 translateTemplateArguments(TemplateArgsPtr,
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003378 TemplateArgs);
3379 TemplateArgsPtr.release();
3380
3381 HasExplicitTemplateArgs = true;
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003382
3383 if (FunctionTemplate) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003384 // FIXME: Diagnose function template with explicit template
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003385 // arguments.
3386 HasExplicitTemplateArgs = false;
3387 } else if (!isFunctionTemplateSpecialization &&
3388 !D.getDeclSpec().isFriendSpecified()) {
3389 // We have encountered something that the user meant to be a
3390 // specialization (because it has explicitly-specified template
3391 // arguments) but that was not introduced with a "template<>" (or had
3392 // too few of them).
3393 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
3394 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
Douglas Gregor849b2432010-03-31 17:46:05 +00003395 << FixItHint::CreateInsertion(
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003396 D.getDeclSpec().getSourceRange().getBegin(),
3397 "template<> ");
3398 isFunctionTemplateSpecialization = true;
John McCall7ad650f2010-03-24 07:46:06 +00003399 } else {
3400 // "friend void foo<>(int);" is an implicit specialization decl.
3401 isFunctionTemplateSpecialization = true;
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003402 }
John McCallaf2094e2010-04-08 09:05:18 +00003403 } else if (isFriend && isFunctionTemplateSpecialization) {
3404 // This combination is only possible in a recovery case; the user
3405 // wrote something like:
3406 // template <> friend void foo(int);
3407 // which we're recovering from as if the user had written:
3408 // friend void foo<>(int);
3409 // Go ahead and fake up a template id.
3410 HasExplicitTemplateArgs = true;
3411 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
3412 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003413 }
John McCall68263142009-11-18 22:49:29 +00003414
John McCallaf2094e2010-04-08 09:05:18 +00003415 // If it's a friend (and only if it's a friend), it's possible
3416 // that either the specialized function type or the specialized
3417 // template is dependent, and therefore matching will fail. In
3418 // this case, don't check the specialization yet.
3419 if (isFunctionTemplateSpecialization && isFriend &&
3420 (NewFD->getType()->isDependentType() || DC->isDependentContext())) {
3421 assert(HasExplicitTemplateArgs &&
3422 "friend function specialization without template args");
3423 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
3424 Previous))
Douglas Gregor036ada22010-03-24 17:31:23 +00003425 NewFD->setInvalidDecl();
John McCallaf2094e2010-04-08 09:05:18 +00003426 } else if (isFunctionTemplateSpecialization) {
3427 if (CheckFunctionTemplateSpecialization(NewFD,
3428 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
3429 Previous))
3430 NewFD->setInvalidDecl();
3431 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
3432 if (CheckMemberSpecialization(NewFD, Previous))
3433 NewFD->setInvalidDecl();
3434 }
John McCallba9d8532010-04-13 06:39:49 +00003435
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003436 // Perform semantic checking on the function declaration.
3437 bool OverloadableAttrRequired = false; // FIXME: HACK!
John McCall9f54ad42009-12-10 09:41:52 +00003438 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
Douglas Gregorfd056bc2009-10-13 16:30:37 +00003439 Redeclaration, /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003440
John McCall68263142009-11-18 22:49:29 +00003441 assert((NewFD->isInvalidDecl() || !Redeclaration ||
3442 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3443 "previous declaration set still overloaded");
3444
John McCall76d32642010-04-24 01:30:58 +00003445 NamedDecl *PrincipalDecl = (FunctionTemplate
3446 ? cast<NamedDecl>(FunctionTemplate)
3447 : NewFD);
3448
John McCallb0cb0222010-03-27 05:57:59 +00003449 if (isFriend && Redeclaration) {
John McCallba9d8532010-04-13 06:39:49 +00003450 AccessSpecifier Access = AS_public;
3451 if (!NewFD->isInvalidDecl())
3452 Access = NewFD->getPreviousDeclaration()->getAccess();
3453
John McCallb0cb0222010-03-27 05:57:59 +00003454 NewFD->setAccess(Access);
John McCall76d32642010-04-24 01:30:58 +00003455 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
3456
3457 PrincipalDecl->setObjectOfFriendDecl(true);
John McCallb0cb0222010-03-27 05:57:59 +00003458 }
3459
John McCall76d32642010-04-24 01:30:58 +00003460 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
3461 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3462 PrincipalDecl->setNonMemberOperator();
3463
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00003464 // If we have a function template, check the template parameter
3465 // list. This will check and merge default template arguments.
3466 if (FunctionTemplate) {
3467 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
3468 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
3469 PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
3470 D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
3471 : TPC_FunctionTemplate);
3472 }
3473
Chris Lattnereaaebc72009-04-25 08:06:05 +00003474 if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
John McCall46460a62010-01-20 21:53:11 +00003475 // Fake up an access specifier if it's supposed to be a class member.
John McCall86ff3082010-02-04 22:26:26 +00003476 if (!Redeclaration && isa<CXXRecordDecl>(NewFD->getDeclContext()))
John McCall46460a62010-01-20 21:53:11 +00003477 NewFD->setAccess(AS_public);
3478
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003479 // An out-of-line member function declaration must also be a
3480 // definition (C++ [dcl.meaning]p1).
Douglas Gregor741fab62009-10-08 15:54:21 +00003481 // Note that this is not the case for explicit specializations of
3482 // function templates or member functions of class templates, per
Chandler Carruthb21fc4a2010-07-16 04:32:28 +00003483 // C++ [temp.expl.spec]p2. We also allow these declarations as an extension
3484 // for compatibility with old SWIG code which likes to generate them.
Douglas Gregord85cef52009-09-17 19:51:30 +00003485 if (!IsFunctionDefinition && !isFriend &&
Douglas Gregor37d681852009-10-12 22:27:17 +00003486 !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
Chandler Carruthb21fc4a2010-07-16 04:32:28 +00003487 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003488 << D.getCXXScopeSpec().getRange();
Chandler Carruthb21fc4a2010-07-16 04:32:28 +00003489 }
3490 if (!Redeclaration && !(isFriend && CurContext->isDependentContext())) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003491 // The user tried to provide an out-of-line definition for a
3492 // function that is a member of a class or namespace, but there
Mike Stump1eb44332009-09-09 15:08:12 +00003493 // was no such member function declared (C++ [class.mfct]p2,
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003494 // C++ [namespace.memdef]p2). For example:
Mike Stump1eb44332009-09-09 15:08:12 +00003495 //
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003496 // class X {
3497 // void f() const;
Mike Stump1eb44332009-09-09 15:08:12 +00003498 // };
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003499 //
3500 // void X::f() { } // ill-formed
3501 //
3502 // Complain about this problem, and attempt to suggest close
3503 // matches (e.g., those that differ only in cv-qualifiers and
3504 // whether the parameter types are references).
3505 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
Douglas Gregor3f093272009-10-13 21:16:44 +00003506 << Name << DC << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00003507 NewFD->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003508
John McCalla24dc2e2009-11-17 02:14:36 +00003509 LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00003510 ForRedeclaration);
John McCalla24dc2e2009-11-17 02:14:36 +00003511 LookupQualifiedName(Prev, DC);
Mike Stump1eb44332009-09-09 15:08:12 +00003512 assert(!Prev.isAmbiguous() &&
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003513 "Cannot have an ambiguity in previous-declaration lookup");
3514 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3515 Func != FuncEnd; ++Func) {
3516 if (isa<FunctionDecl>(*Func) &&
3517 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
3518 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3519 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003520 }
3521 }
3522
3523 // Handle attributes. We need to have merged decls when handling attributes
3524 // (for example to check for conflicts, etc).
3525 // FIXME: This needs to happen before we merge declarations. Then,
3526 // let attribute merging cope with attribute conflicts.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003527 ProcessDeclAttributes(S, NewFD, D);
Ryan Flynn478fbc62009-07-25 22:29:44 +00003528
3529 // attributes declared post-definition are currently ignored
John McCall68263142009-11-18 22:49:29 +00003530 if (Redeclaration && Previous.isSingleResult()) {
3531 const FunctionDecl *Def;
3532 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003533 if (PrevFD && PrevFD->hasBody(Def) && D.hasAttributes()) {
Ryan Flynn478fbc62009-07-25 22:29:44 +00003534 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
3535 Diag(Def->getLocation(), diag::note_previous_definition);
3536 }
3537 }
3538
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003539 AddKnownFunctionAttributes(NewFD);
3540
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003541 if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003542 // If a function name is overloadable in C, then every function
3543 // with that name must be marked "overloadable".
3544 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
3545 << Redeclaration << NewFD;
John McCall68263142009-11-18 22:49:29 +00003546 if (!Previous.empty())
3547 Diag(Previous.getRepresentativeDecl()->getLocation(),
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003548 diag::note_attribute_overloadable_prev_overload);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003549 NewFD->addAttr(::new (Context) OverloadableAttr());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003550 }
3551
3552 // If this is a locally-scoped extern C function, update the
3553 // map of such names.
Douglas Gregor48a83b52009-09-12 00:17:51 +00003554 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
Chris Lattnereaaebc72009-04-25 08:06:05 +00003555 && !NewFD->isInvalidDecl())
John McCall68263142009-11-18 22:49:29 +00003556 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003557
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00003558 // Set this FunctionDecl's range up to the right paren.
3559 NewFD->setLocEnd(D.getSourceRange().getEnd());
3560
Douglas Gregore53060f2009-06-25 22:08:12 +00003561 if (FunctionTemplate && NewFD->isInvalidDecl())
3562 FunctionTemplate->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003563
Douglas Gregore53060f2009-06-25 22:08:12 +00003564 if (FunctionTemplate)
3565 return FunctionTemplate;
Mike Stump1eb44332009-09-09 15:08:12 +00003566
Tanya Lattnere6bbc012010-02-12 00:07:30 +00003567
3568 // Keep track of static, non-inlined function definitions that
3569 // have not been used. We will warn later.
3570 // FIXME: Also include static functions declared but not defined.
3571 if (!NewFD->isInvalidDecl() && IsFunctionDefinition
3572 && !NewFD->isInlined() && NewFD->getLinkage() == InternalLinkage
Chris Lattner1a4221c2010-04-09 17:25:05 +00003573 && !NewFD->isUsed() && !NewFD->hasAttr<UnusedAttr>()
3574 && !NewFD->hasAttr<ConstructorAttr>()
3575 && !NewFD->hasAttr<DestructorAttr>())
Tanya Lattnere6bbc012010-02-12 00:07:30 +00003576 UnusedStaticFuncs.push_back(NewFD);
3577
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003578 return NewFD;
3579}
3580
3581/// \brief Perform semantic checking of a new function declaration.
3582///
3583/// Performs semantic analysis of the new function declaration
3584/// NewFD. This routine performs all semantic checking that does not
3585/// require the actual declarator involved in the declaration, and is
3586/// used both for the declaration of functions as they are parsed
3587/// (called via ActOnDeclarator) and for the declaration of functions
3588/// that have been instantiated via C++ template instantiation (called
3589/// via InstantiateDecl).
3590///
Douglas Gregorfd056bc2009-10-13 16:30:37 +00003591/// \param IsExplicitSpecialiation whether this new function declaration is
3592/// an explicit specialization of the previous declaration.
3593///
Chris Lattnereaaebc72009-04-25 08:06:05 +00003594/// This sets NewFD->isInvalidDecl() to true if there was an error.
John McCall9f54ad42009-12-10 09:41:52 +00003595void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall68263142009-11-18 22:49:29 +00003596 LookupResult &Previous,
Douglas Gregorfd056bc2009-10-13 16:30:37 +00003597 bool IsExplicitSpecialization,
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003598 bool &Redeclaration,
3599 bool &OverloadableAttrRequired) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00003600 // If NewFD is already known erroneous, don't do any of this checking.
3601 if (NewFD->isInvalidDecl())
3602 return;
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003603
Eli Friedman88f7b572009-05-16 12:15:55 +00003604 if (NewFD->getResultType()->isVariablyModifiedType()) {
3605 // Functions returning a variably modified type violate C99 6.7.5.2p2
3606 // because all functions have linkage.
3607 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
3608 return NewFD->setInvalidDecl();
3609 }
3610
Douglas Gregor48a83b52009-09-12 00:17:51 +00003611 if (NewFD->isMain())
3612 CheckMain(NewFD);
John McCall8c4859a2009-07-24 03:03:21 +00003613
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003614 // Check for a previous declaration of this name.
John McCall68263142009-11-18 22:49:29 +00003615 if (Previous.empty() && NewFD->isExternC()) {
Douglas Gregor63935192009-03-02 00:19:53 +00003616 // Since we did not find anything by this name and we're declaring
3617 // an extern "C" function, look for a non-visible extern "C"
3618 // declaration with the same name.
3619 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003620 = LocallyScopedExternalDecls.find(NewFD->getDeclName());
Douglas Gregor63935192009-03-02 00:19:53 +00003621 if (Pos != LocallyScopedExternalDecls.end())
John McCall68263142009-11-18 22:49:29 +00003622 Previous.addDecl(Pos->second);
Douglas Gregor63935192009-03-02 00:19:53 +00003623 }
3624
Douglas Gregor04495c82009-02-24 01:23:02 +00003625 // Merge or overload the declaration with an existing declaration of
3626 // the same name, if appropriate.
John McCall68263142009-11-18 22:49:29 +00003627 if (!Previous.empty()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00003628 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003629 // a declaration that requires merging. If it's an overload,
3630 // there's no more work to do here; we'll just add the new
3631 // function to the scope.
Douglas Gregorae170942009-02-13 00:26:38 +00003632
John McCall68263142009-11-18 22:49:29 +00003633 NamedDecl *OldDecl = 0;
John McCall871b2e72009-12-09 03:35:25 +00003634 if (!AllowOverloadingOfFunction(Previous, Context)) {
3635 Redeclaration = true;
3636 OldDecl = Previous.getFoundDecl();
3637 } else {
3638 if (!getLangOptions().CPlusPlus) {
3639 OverloadableAttrRequired = true;
3640
3641 // Functions marked "overloadable" must have a prototype (that
3642 // we can't get through declaration merging).
3643 if (!NewFD->getType()->getAs<FunctionProtoType>()) {
3644 Diag(NewFD->getLocation(),
3645 diag::err_attribute_overloadable_no_prototype)
3646 << NewFD;
John McCall68263142009-11-18 22:49:29 +00003647 Redeclaration = true;
John McCall871b2e72009-12-09 03:35:25 +00003648
3649 // Turn this into a variadic function with no parameters.
3650 QualType R = Context.getFunctionType(
3651 NewFD->getType()->getAs<FunctionType>()->getResultType(),
Rafael Espindola264ba482010-03-30 20:24:48 +00003652 0, 0, true, 0, false, false, 0, 0,
3653 FunctionType::ExtInfo());
John McCall871b2e72009-12-09 03:35:25 +00003654 NewFD->setType(R);
3655 return NewFD->setInvalidDecl();
3656 }
3657 }
3658
John McCallad00b772010-06-16 08:42:20 +00003659 switch (CheckOverload(S, NewFD, Previous, OldDecl,
3660 /*NewIsUsingDecl*/ false)) {
John McCall871b2e72009-12-09 03:35:25 +00003661 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00003662 Redeclaration = true;
John McCall871b2e72009-12-09 03:35:25 +00003663 break;
3664
3665 case Ovl_NonFunction:
3666 Redeclaration = true;
3667 break;
3668
3669 case Ovl_Overload:
3670 Redeclaration = false;
3671 break;
John McCall68263142009-11-18 22:49:29 +00003672 }
3673 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003674
John McCall68263142009-11-18 22:49:29 +00003675 if (Redeclaration) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003676 // NewFD and OldDecl represent declarations that need to be
Mike Stump1eb44332009-09-09 15:08:12 +00003677 // merged.
Douglas Gregorcda9c672009-02-16 17:45:42 +00003678 if (MergeFunctionDecl(NewFD, OldDecl))
Chris Lattnereaaebc72009-04-25 08:06:05 +00003679 return NewFD->setInvalidDecl();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003680
John McCall68263142009-11-18 22:49:29 +00003681 Previous.clear();
3682 Previous.addDecl(OldDecl);
3683
Douglas Gregore53060f2009-06-25 22:08:12 +00003684 if (FunctionTemplateDecl *OldTemplateDecl
Douglas Gregor37d681852009-10-12 22:27:17 +00003685 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
Douglas Gregorfd056bc2009-10-13 16:30:37 +00003686 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
Douglas Gregor37d681852009-10-12 22:27:17 +00003687 FunctionTemplateDecl *NewTemplateDecl
3688 = NewFD->getDescribedFunctionTemplate();
3689 assert(NewTemplateDecl && "Template/non-template mismatch");
3690 if (CXXMethodDecl *Method
3691 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
3692 Method->setAccess(OldTemplateDecl->getAccess());
3693 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
3694 }
Douglas Gregorfd056bc2009-10-13 16:30:37 +00003695
3696 // If this is an explicit specialization of a member that is a function
3697 // template, mark it as a member specialization.
3698 if (IsExplicitSpecialization &&
3699 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
3700 NewTemplateDecl->setMemberSpecialization();
3701 assert(OldTemplateDecl->isMemberSpecialization());
3702 }
Douglas Gregor37d681852009-10-12 22:27:17 +00003703 } else {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00003704 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
3705 NewFD->setAccess(OldDecl->getAccess());
Douglas Gregore53060f2009-06-25 22:08:12 +00003706 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00003707 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003708 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00003709 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003710
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003711 // Semantic checking for this function declaration (in isolation).
3712 if (getLangOptions().CPlusPlus) {
3713 // C++-specific checks.
3714 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
3715 CheckConstructor(Constructor);
Anders Carlsson6d701392009-11-15 22:49:34 +00003716 } else if (CXXDestructorDecl *Destructor =
3717 dyn_cast<CXXDestructorDecl>(NewFD)) {
3718 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003719 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson6d701392009-11-15 22:49:34 +00003720
Douglas Gregor4923aa22010-07-02 20:37:36 +00003721 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson6d701392009-11-15 22:49:34 +00003722 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003723 if (!ClassType->isDependentType()) {
3724 DeclarationName Name
3725 = Context.DeclarationNames.getCXXDestructorName(
3726 Context.getCanonicalType(ClassType));
3727 if (NewFD->getDeclName() != Name) {
3728 Diag(NewFD->getLocation(), diag::err_destructor_name);
3729 return NewFD->setInvalidDecl();
3730 }
3731 }
Anders Carlsson6d701392009-11-15 22:49:34 +00003732
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003733 Record->setUserDeclaredDestructor(true);
3734 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
3735 // user-defined destructor.
3736 Record->setPOD(false);
3737
3738 // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
3739 // declared destructor.
3740 // FIXME: C++0x: don't do this for "= default" destructors
3741 Record->setHasTrivialDestructor(false);
3742 } else if (CXXConversionDecl *Conversion
Douglas Gregor4ba31362009-12-01 17:24:26 +00003743 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003744 ActOnConversionDeclarator(Conversion);
Douglas Gregor4ba31362009-12-01 17:24:26 +00003745 }
3746
3747 // Find any virtual functions that this function overrides.
Douglas Gregore6342c02009-12-01 17:35:23 +00003748 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
3749 if (!Method->isFunctionTemplateSpecialization() &&
3750 !Method->getDescribedFunctionTemplate())
3751 AddOverriddenMethods(Method->getParent(), Method);
3752 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003753
Eli Friedman5fcf1f02009-12-02 07:16:50 +00003754 // Additional checks for the destructor; make sure we do this after we
3755 // figure out whether the destructor is virtual.
3756 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
3757 if (!Destructor->getParent()->isDependentType())
3758 CheckDestructor(Destructor);
3759
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003760 // Extra checking for C++ overloaded operators (C++ [over.oper]).
3761 if (NewFD->isOverloadedOperator() &&
3762 CheckOverloadedOperatorDeclaration(NewFD))
3763 return NewFD->setInvalidDecl();
Sean Hunta6c058d2010-01-13 09:01:02 +00003764
3765 // Extra checking for C++0x literal operators (C++0x [over.literal]).
3766 if (NewFD->getLiteralIdentifier() &&
3767 CheckLiteralOperatorDeclaration(NewFD))
3768 return NewFD->setInvalidDecl();
3769
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003770 // In C++, check default arguments now that we have merged decls. Unless
3771 // the lexical context is the class, because in this case this is done
3772 // during delayed parsing anyway.
3773 if (!CurContext->isRecord())
3774 CheckCXXDefaultArguments(NewFD);
3775 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003776}
3777
John McCall8c4859a2009-07-24 03:03:21 +00003778void Sema::CheckMain(FunctionDecl* FD) {
John McCall13591ed2009-07-25 04:36:53 +00003779 // C++ [basic.start.main]p3: A program that declares main to be inline
3780 // or static is ill-formed.
3781 // C99 6.7.4p4: In a hosted environment, the inline function specifier
3782 // shall not appear in a declaration of main.
3783 // static main is not an error under C99, but we should warn about it.
Douglas Gregor0130f3c2009-10-27 21:01:01 +00003784 bool isInline = FD->isInlineSpecified();
John McCall13591ed2009-07-25 04:36:53 +00003785 bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
3786 if (isInline || isStatic) {
3787 unsigned diagID = diag::warn_unusual_main_decl;
3788 if (isInline || getLangOptions().CPlusPlus)
3789 diagID = diag::err_unusual_main_decl;
3790
3791 int which = isStatic + (isInline << 1) - 1;
3792 Diag(FD->getLocation(), diagID) << which;
3793 }
3794
3795 QualType T = FD->getType();
3796 assert(T->isFunctionType() && "function decl is not of function type");
John McCall183700f2009-09-21 23:43:11 +00003797 const FunctionType* FT = T->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003798
John McCall13591ed2009-07-25 04:36:53 +00003799 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
3800 // TODO: add a replacement fixit to turn the return type into 'int'.
3801 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
3802 FD->setInvalidDecl(true);
3803 }
3804
3805 // Treat protoless main() as nullary.
3806 if (isa<FunctionNoProtoType>(FT)) return;
3807
3808 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
3809 unsigned nparams = FTP->getNumArgs();
3810 assert(FD->getNumParams() == nparams);
3811
John McCall66755862009-12-24 09:58:38 +00003812 bool HasExtraParameters = (nparams > 3);
3813
3814 // Darwin passes an undocumented fourth argument of type char**. If
3815 // other platforms start sprouting these, the logic below will start
3816 // getting shifty.
3817 if (nparams == 4 &&
3818 Context.Target.getTriple().getOS() == llvm::Triple::Darwin)
3819 HasExtraParameters = false;
3820
3821 if (HasExtraParameters) {
John McCall13591ed2009-07-25 04:36:53 +00003822 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
3823 FD->setInvalidDecl(true);
3824 nparams = 3;
3825 }
3826
3827 // FIXME: a lot of the following diagnostics would be improved
3828 // if we had some location information about types.
3829
3830 QualType CharPP =
3831 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall66755862009-12-24 09:58:38 +00003832 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall13591ed2009-07-25 04:36:53 +00003833
3834 for (unsigned i = 0; i < nparams; ++i) {
3835 QualType AT = FTP->getArgType(i);
3836
3837 bool mismatch = true;
3838
3839 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
3840 mismatch = false;
3841 else if (Expected[i] == CharPP) {
3842 // As an extension, the following forms are okay:
3843 // char const **
3844 // char const * const *
3845 // char * const *
3846
John McCall0953e762009-09-24 19:53:00 +00003847 QualifierCollector qs;
John McCall13591ed2009-07-25 04:36:53 +00003848 const PointerType* PT;
Ted Kremenek6217b802009-07-29 21:53:49 +00003849 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
3850 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
John McCall13591ed2009-07-25 04:36:53 +00003851 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
3852 qs.removeConst();
3853 mismatch = !qs.empty();
3854 }
3855 }
3856
3857 if (mismatch) {
3858 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
3859 // TODO: suggest replacing given type with expected type
3860 FD->setInvalidDecl(true);
3861 }
3862 }
3863
3864 if (nparams == 1 && !FD->isInvalidDecl()) {
3865 Diag(FD->getLocation(), diag::warn_main_one_arg);
3866 }
John McCall8c4859a2009-07-24 03:03:21 +00003867}
3868
Eli Friedmanc594b322008-05-20 13:48:25 +00003869bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman3b8a36a2009-02-27 04:17:12 +00003870 // FIXME: Need strict checking. In C89, we need to check for
3871 // any assignment, increment, decrement, function-calls, or
3872 // commas outside of a sizeof. In C99, it's the same list,
3873 // except that the aforementioned are allowed in unevaluated
3874 // expressions. Everything else falls under the
3875 // "may accept other forms of constant expressions" exception.
3876 // (We never end up here for C++, so the constant expression
3877 // rules there don't matter.)
Chris Lattner111c2ee2009-02-24 21:54:33 +00003878 if (Init->isConstantInitializer(Context))
Eli Friedman578a9722009-02-22 06:45:27 +00003879 return false;
Eli Friedman21298282009-02-26 04:47:58 +00003880 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
3881 << Init->getSourceRange();
Eli Friedmanc594b322008-05-20 13:48:25 +00003882 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00003883}
3884
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003885void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
3886 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003887}
3888
3889/// AddInitializerToDecl - Adds the initializer Init to the
3890/// declaration dcl. If DirectInit is true, this is C++ direct
3891/// initialization rather than copy initialization.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003892void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
3893 Decl *RealDecl = dcl.getAs<Decl>();
Chris Lattner9a11b9a2007-10-19 20:10:30 +00003894 // If there is no declaration, there was an error parsing it. Just ignore
3895 // the initializer.
Eli Friedman3b8a36a2009-02-27 04:17:12 +00003896 if (RealDecl == 0)
Chris Lattner9a11b9a2007-10-19 20:10:30 +00003897 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003898
Douglas Gregor021c3b32009-03-11 23:00:04 +00003899 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
3900 // With declarators parsed the way they are, the parser cannot
3901 // distinguish between a normal initializer and a pure-specifier.
3902 // Thus this grotesque test.
3903 IntegerLiteral *IL;
3904 Expr *Init = static_cast<Expr *>(init.get());
3905 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor4ba31362009-12-01 17:24:26 +00003906 Context.getCanonicalType(IL->getType()) == Context.IntTy)
3907 CheckPureMethod(Method, Init->getSourceRange());
3908 else {
Douglas Gregor021c3b32009-03-11 23:00:04 +00003909 Diag(Method->getLocation(), diag::err_member_function_initialization)
3910 << Method->getDeclName() << Init->getSourceRange();
3911 Method->setInvalidDecl();
3912 }
3913 return;
3914 }
3915
Steve Naroff410e3e22007-09-12 20:13:48 +00003916 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3917 if (!VDecl) {
Douglas Gregor021c3b32009-03-11 23:00:04 +00003918 if (getLangOptions().CPlusPlus &&
3919 RealDecl->getLexicalDeclContext()->isRecord() &&
3920 isa<NamedDecl>(RealDecl))
3921 Diag(RealDecl->getLocation(), diag::err_member_initialization)
3922 << cast<NamedDecl>(RealDecl)->getDeclName();
3923 else
3924 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00003925 RealDecl->setInvalidDecl();
3926 return;
Eli Friedman3b8a36a2009-02-27 04:17:12 +00003927 }
3928
Eli Friedman49e2b8e2009-11-14 03:40:14 +00003929 // A definition must end up with a complete type, which means it must be
3930 // complete with the restriction that an array type might be completed by the
3931 // initializer; note that later code assumes this restriction.
3932 QualType BaseDeclType = VDecl->getType();
3933 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
3934 BaseDeclType = Array->getElementType();
3935 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
Eli Friedmana31feca2009-04-13 21:28:54 +00003936 diag::err_typecheck_decl_incomplete_type)) {
3937 RealDecl->setInvalidDecl();
3938 return;
3939 }
3940
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003941 // The variable can not have an abstract class type.
3942 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
3943 diag::err_abstract_type_in_decl,
3944 AbstractVariableType))
3945 VDecl->setInvalidDecl();
3946
Sebastian Redl31310a22010-02-01 20:16:42 +00003947 const VarDecl *Def;
3948 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003949 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor275a3692009-03-10 23:43:53 +00003950 << VDecl->getDeclName();
3951 Diag(Def->getLocation(), diag::note_previous_definition);
3952 VDecl->setInvalidDecl();
3953 return;
3954 }
3955
Eli Friedman3b8a36a2009-02-27 04:17:12 +00003956 // Take ownership of the expression, now that we're sure we have somewhere
3957 // to put it.
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003958 Expr *Init = init.takeAs<Expr>();
Eli Friedman3b8a36a2009-02-27 04:17:12 +00003959 assert(Init && "missing initializer");
3960
Douglas Gregor99a2e602009-12-16 01:38:02 +00003961 // Capture the variable that is being initialized and the style of
3962 // initialization.
3963 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
3964
3965 // FIXME: Poor source location information.
3966 InitializationKind Kind
3967 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
3968 Init->getLocStart(),
3969 Init->getLocEnd())
3970 : InitializationKind::CreateCopy(VDecl->getLocation(),
3971 Init->getLocStart());
3972
Steve Naroffbb204692007-09-12 14:07:44 +00003973 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00003974 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00003975 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00003976 if (VDecl->isBlockVarDecl()) {
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003977 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00003978 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00003979 VDecl->setInvalidDecl();
3980 } else if (!VDecl->isInvalidDecl()) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003981 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
Eli Friedmana91eb542009-12-22 02:10:53 +00003982 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003983 MultiExprArg(*this, (void**)&Init, 1),
Eli Friedmana91eb542009-12-22 02:10:53 +00003984 &DclT);
3985 if (Result.isInvalid()) {
Steve Naroff248a7532008-04-15 22:42:06 +00003986 VDecl->setInvalidDecl();
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003987 return;
3988 }
Mike Stump1eb44332009-09-09 15:08:12 +00003989
Eli Friedmana91eb542009-12-22 02:10:53 +00003990 Init = Result.takeAs<Expr>();
3991
Anders Carlssonc5eb7312008-08-22 05:00:02 +00003992 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmanda153232009-02-20 01:34:21 +00003993 // Don't check invalid declarations to avoid emitting useless diagnostics.
3994 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003995 if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
Anders Carlssonc5eb7312008-08-22 05:00:02 +00003996 CheckForConstantInitializer(Init, DclT);
3997 }
Steve Naroffbb204692007-09-12 14:07:44 +00003998 }
Mike Stump1eb44332009-09-09 15:08:12 +00003999 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor021c3b32009-03-11 23:00:04 +00004000 VDecl->getLexicalDeclContext()->isRecord()) {
4001 // This is an in-class initialization for a static data member, e.g.,
4002 //
4003 // struct S {
4004 // static const int value = 17;
4005 // };
4006
4007 // Attach the initializer
Douglas Gregor838db382010-02-11 01:19:42 +00004008 VDecl->setInit(Init);
Douglas Gregor021c3b32009-03-11 23:00:04 +00004009
4010 // C++ [class.mem]p4:
4011 // A member-declarator can contain a constant-initializer only
4012 // if it declares a static member (9.4) of const integral or
4013 // const enumeration type, see 9.4.2.
4014 QualType T = VDecl->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004015 if (!T->isDependentType() &&
Douglas Gregor021c3b32009-03-11 23:00:04 +00004016 (!Context.getCanonicalType(T).isConstQualified() ||
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004017 !T->isIntegralOrEnumerationType())) {
Douglas Gregor021c3b32009-03-11 23:00:04 +00004018 Diag(VDecl->getLocation(), diag::err_member_initialization)
4019 << VDecl->getDeclName() << Init->getSourceRange();
4020 VDecl->setInvalidDecl();
4021 } else {
4022 // C++ [class.static.data]p4:
4023 // If a static data member is of const integral or const
4024 // enumeration type, its declaration in the class definition
4025 // can specify a constant-initializer which shall be an
4026 // integral constant expression (5.19).
4027 if (!Init->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004028 !Init->getType()->isIntegralOrEnumerationType()) {
Douglas Gregor021c3b32009-03-11 23:00:04 +00004029 // We have a non-dependent, non-integral or enumeration type.
Mike Stump1eb44332009-09-09 15:08:12 +00004030 Diag(Init->getSourceRange().getBegin(),
Douglas Gregor021c3b32009-03-11 23:00:04 +00004031 diag::err_in_class_initializer_non_integral_type)
4032 << Init->getType() << Init->getSourceRange();
4033 VDecl->setInvalidDecl();
4034 } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
4035 // Check whether the expression is a constant expression.
4036 llvm::APSInt Value;
4037 SourceLocation Loc;
4038 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
4039 Diag(Loc, diag::err_in_class_initializer_non_constant)
4040 << Init->getSourceRange();
4041 VDecl->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00004042 } else if (!VDecl->getType()->isDependentType())
Eli Friedman73c39ab2009-10-20 08:27:19 +00004043 ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
Douglas Gregor021c3b32009-03-11 23:00:04 +00004044 }
4045 }
Steve Naroff248a7532008-04-15 22:42:06 +00004046 } else if (VDecl->isFileVarDecl()) {
Douglas Gregor41b1d6b2010-04-19 21:31:25 +00004047 if (VDecl->getStorageClass() == VarDecl::Extern &&
Douglas Gregor66dd9392010-04-22 14:36:26 +00004048 (!getLangOptions().CPlusPlus ||
4049 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
Steve Naroff410e3e22007-09-12 20:13:48 +00004050 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedmana91eb542009-12-22 02:10:53 +00004051 if (!VDecl->isInvalidDecl()) {
4052 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
4053 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4054 MultiExprArg(*this, (void**)&Init, 1),
4055 &DclT);
4056 if (Result.isInvalid()) {
Steve Naroff248a7532008-04-15 22:42:06 +00004057 VDecl->setInvalidDecl();
Eli Friedmana91eb542009-12-22 02:10:53 +00004058 return;
4059 }
4060
4061 Init = Result.takeAs<Expr>();
4062 }
Mike Stump1eb44332009-09-09 15:08:12 +00004063
Anders Carlssonc5eb7312008-08-22 05:00:02 +00004064 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmanda153232009-02-20 01:34:21 +00004065 // Don't check invalid declarations to avoid emitting useless diagnostics.
4066 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Anders Carlssonc5eb7312008-08-22 05:00:02 +00004067 // C99 6.7.8p4. All file scoped initializers need to be constant.
4068 CheckForConstantInitializer(Init, DclT);
4069 }
Steve Naroffbb204692007-09-12 14:07:44 +00004070 }
4071 // If the type changed, it means we had an incomplete type that was
Mike Stump1eb44332009-09-09 15:08:12 +00004072 // completed by the initializer. For example:
Steve Naroffbb204692007-09-12 14:07:44 +00004073 // int ary[] = { 1, 3, 5 };
4074 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00004075 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00004076 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00004077 Init->setType(DclT);
4078 }
Mike Stump1eb44332009-09-09 15:08:12 +00004079
Anders Carlsson0ece4912009-12-15 20:51:39 +00004080 Init = MaybeCreateCXXExprWithTemporaries(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00004081 // Attach the initializer to the decl.
Douglas Gregor838db382010-02-11 01:19:42 +00004082 VDecl->setInit(Init);
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00004083
Eli Friedmandd4e4852009-12-20 22:29:11 +00004084 if (getLangOptions().CPlusPlus) {
4085 // Make sure we mark the destructor as used if necessary.
4086 QualType InitType = VDecl->getType();
Douglas Gregorbd6d6192010-01-05 19:06:31 +00004087 while (const ArrayType *Array = Context.getAsArrayType(InitType))
Eli Friedmandd4e4852009-12-20 22:29:11 +00004088 InitType = Context.getBaseElementType(Array);
John McCall68c6c9a2010-02-02 09:10:11 +00004089 if (const RecordType *Record = InitType->getAs<RecordType>())
4090 FinalizeVarWithDestructor(VDecl, Record);
Eli Friedmandd4e4852009-12-20 22:29:11 +00004091 }
4092
Steve Naroffbb204692007-09-12 14:07:44 +00004093 return;
4094}
4095
John McCall7727acf2010-03-31 02:13:20 +00004096/// ActOnInitializerError - Given that there was an error parsing an
4097/// initializer for the given declaration, try to return to some form
4098/// of sanity.
4099void Sema::ActOnInitializerError(DeclPtrTy dcl) {
4100 // Our main concern here is re-establishing invariants like "a
4101 // variable's type is either dependent or complete".
4102 Decl *D = dcl.getAs<Decl>();
4103 if (!D || D->isInvalidDecl()) return;
4104
4105 VarDecl *VD = dyn_cast<VarDecl>(D);
4106 if (!VD) return;
4107
4108 QualType Ty = VD->getType();
4109 if (Ty->isDependentType()) return;
4110
4111 // Require a complete type.
4112 if (RequireCompleteType(VD->getLocation(),
4113 Context.getBaseElementType(Ty),
4114 diag::err_typecheck_decl_incomplete_type)) {
4115 VD->setInvalidDecl();
4116 return;
4117 }
4118
4119 // Require an abstract type.
4120 if (RequireNonAbstractType(VD->getLocation(), Ty,
4121 diag::err_abstract_type_in_decl,
4122 AbstractVariableType)) {
4123 VD->setInvalidDecl();
4124 return;
4125 }
4126
4127 // Don't bother complaining about constructors or destructors,
4128 // though.
4129}
4130
Mike Stump1eb44332009-09-09 15:08:12 +00004131void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
Anders Carlsson6a75cd92009-07-11 00:34:39 +00004132 bool TypeContainsUndeducedAuto) {
Chris Lattnerb28317a2009-03-28 19:18:32 +00004133 Decl *RealDecl = dcl.getAs<Decl>();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004134
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00004135 // If there is no declaration, there was an error parsing it. Just ignore it.
4136 if (RealDecl == 0)
4137 return;
4138
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004139 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
4140 QualType Type = Var->getType();
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00004141
Anders Carlsson6a75cd92009-07-11 00:34:39 +00004142 // C++0x [dcl.spec.auto]p3
4143 if (TypeContainsUndeducedAuto) {
4144 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
4145 << Var->getDeclName() << Type;
4146 Var->setInvalidDecl();
4147 return;
4148 }
Mike Stump1eb44332009-09-09 15:08:12 +00004149
Douglas Gregor60c93c92010-02-09 07:26:29 +00004150 switch (Var->isThisDeclarationADefinition()) {
4151 case VarDecl::Definition:
4152 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
4153 break;
4154
4155 // We have an out-of-line definition of a static data member
4156 // that has an in-class initializer, so we type-check this like
4157 // a declaration.
4158 //
4159 // Fall through
4160
4161 case VarDecl::DeclarationOnly:
4162 // It's only a declaration.
4163
4164 // Block scope. C99 6.7p7: If an identifier for an object is
4165 // declared with no linkage (C99 6.2.2p6), the type for the
4166 // object shall be complete.
4167 if (!Type->isDependentType() && Var->isBlockVarDecl() &&
4168 !Var->getLinkage() && !Var->isInvalidDecl() &&
4169 RequireCompleteType(Var->getLocation(), Type,
4170 diag::err_typecheck_decl_incomplete_type))
4171 Var->setInvalidDecl();
4172
4173 // Make sure that the type is not abstract.
4174 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
4175 RequireNonAbstractType(Var->getLocation(), Type,
4176 diag::err_abstract_type_in_decl,
4177 AbstractVariableType))
4178 Var->setInvalidDecl();
4179 return;
4180
4181 case VarDecl::TentativeDefinition:
4182 // File scope. C99 6.9.2p2: A declaration of an identifier for an
4183 // object that has file scope without an initializer, and without a
4184 // storage-class specifier or with the storage-class specifier "static",
4185 // constitutes a tentative definition. Note: A tentative definition with
4186 // external linkage is valid (C99 6.2.2p5).
4187 if (!Var->isInvalidDecl()) {
4188 if (const IncompleteArrayType *ArrayT
4189 = Context.getAsIncompleteArrayType(Type)) {
4190 if (RequireCompleteType(Var->getLocation(),
4191 ArrayT->getElementType(),
4192 diag::err_illegal_decl_array_incomplete_type))
4193 Var->setInvalidDecl();
4194 } else if (Var->getStorageClass() == VarDecl::Static) {
4195 // C99 6.9.2p3: If the declaration of an identifier for an object is
4196 // a tentative definition and has internal linkage (C99 6.2.2p3), the
4197 // declared type shall not be an incomplete type.
4198 // NOTE: code such as the following
4199 // static struct s;
4200 // struct s { int a; };
4201 // is accepted by gcc. Hence here we issue a warning instead of
4202 // an error and we do not invalidate the static declaration.
4203 // NOTE: to avoid multiple warnings, only check the first declaration.
4204 if (Var->getPreviousDeclaration() == 0)
4205 RequireCompleteType(Var->getLocation(), Type,
4206 diag::ext_typecheck_decl_incomplete_type);
4207 }
4208 }
4209
4210 // Record the tentative definition; we're done.
4211 if (!Var->isInvalidDecl())
4212 TentativeDefinitions.push_back(Var);
4213 return;
4214 }
4215
4216 // Provide a specific diagnostic for uninitialized variable
4217 // definitions with incomplete array type.
4218 if (Type->isIncompleteArrayType()) {
Sebastian Redl6e824752009-11-05 19:47:47 +00004219 Diag(Var->getLocation(),
4220 diag::err_typecheck_incomplete_array_needs_initializer);
4221 Var->setInvalidDecl();
4222 return;
4223 }
4224
Douglas Gregor60c93c92010-02-09 07:26:29 +00004225 // Provide a specific diagnostic for uninitialized variable
4226 // definitions with reference type.
4227 if (Type->isReferenceType()) {
4228 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
4229 << Var->getDeclName()
4230 << SourceRange(Var->getLocation(), Var->getLocation());
4231 Var->setInvalidDecl();
4232 return;
4233 }
4234
4235 // Do not attempt to type-check the default initializer for a
4236 // variable with dependent type.
4237 if (Type->isDependentType())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004238 return;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004239
Douglas Gregor60c93c92010-02-09 07:26:29 +00004240 if (Var->isInvalidDecl())
4241 return;
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004242
Douglas Gregor60c93c92010-02-09 07:26:29 +00004243 if (RequireCompleteType(Var->getLocation(),
4244 Context.getBaseElementType(Type),
4245 diag::err_typecheck_decl_incomplete_type)) {
4246 Var->setInvalidDecl();
4247 return;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004248 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004249
Douglas Gregor60c93c92010-02-09 07:26:29 +00004250 // The variable can not have an abstract class type.
4251 if (RequireNonAbstractType(Var->getLocation(), Type,
4252 diag::err_abstract_type_in_decl,
4253 AbstractVariableType)) {
4254 Var->setInvalidDecl();
4255 return;
4256 }
4257
Douglas Gregor516a6bc2010-03-08 02:45:10 +00004258 const RecordType *Record
4259 = Context.getBaseElementType(Type)->getAs<RecordType>();
4260 if (Record && getLangOptions().CPlusPlus && !getLangOptions().CPlusPlus0x &&
4261 cast<CXXRecordDecl>(Record->getDecl())->isPOD()) {
4262 // C++03 [dcl.init]p9:
4263 // If no initializer is specified for an object, and the
4264 // object is of (possibly cv-qualified) non-POD class type (or
4265 // array thereof), the object shall be default-initialized; if
4266 // the object is of const-qualified type, the underlying class
4267 // type shall have a user-declared default
4268 // constructor. Otherwise, if no initializer is specified for
4269 // a non- static object, the object and its subobjects, if
4270 // any, have an indeterminate initial value); if the object
4271 // or any of its subobjects are of const-qualified type, the
4272 // program is ill-formed.
4273 // FIXME: DPG thinks it is very fishy that C++0x disables this.
4274 } else {
4275 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
4276 InitializationKind Kind
4277 = InitializationKind::CreateDefault(Var->getLocation());
Douglas Gregor60c93c92010-02-09 07:26:29 +00004278
Douglas Gregor516a6bc2010-03-08 02:45:10 +00004279 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
4280 OwningExprResult Init = InitSeq.Perform(*this, Entity, Kind,
4281 MultiExprArg(*this, 0, 0));
4282 if (Init.isInvalid())
4283 Var->setInvalidDecl();
4284 else if (Init.get())
Douglas Gregor838db382010-02-11 01:19:42 +00004285 Var->setInit(MaybeCreateCXXExprWithTemporaries(Init.takeAs<Expr>()));
Douglas Gregor60c93c92010-02-09 07:26:29 +00004286 }
Douglas Gregor516a6bc2010-03-08 02:45:10 +00004287
4288 if (!Var->isInvalidDecl() && getLangOptions().CPlusPlus && Record)
4289 FinalizeVarWithDestructor(Var, Record);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004290 }
4291}
4292
Eli Friedmanc1dc6532009-05-29 01:49:24 +00004293Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4294 DeclPtrTy *Group,
Chris Lattner682bf922009-03-29 16:50:03 +00004295 unsigned NumDecls) {
4296 llvm::SmallVector<Decl*, 8> Decls;
Eli Friedmanc1dc6532009-05-29 01:49:24 +00004297
4298 if (DS.isTypeSpecOwned())
4299 Decls.push_back((Decl*)DS.getTypeRep());
4300
Chris Lattner682bf922009-03-29 16:50:03 +00004301 for (unsigned i = 0; i != NumDecls; ++i)
4302 if (Decl *D = Group[i].getAs<Decl>())
4303 Decls.push_back(D);
Mike Stump1eb44332009-09-09 15:08:12 +00004304
Chris Lattner682bf922009-03-29 16:50:03 +00004305 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
Jay Foadbeaaccd2009-05-21 09:52:38 +00004306 Decls.data(), Decls.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00004307}
Steve Naroffe1223f72007-08-28 03:03:08 +00004308
Chris Lattner682bf922009-03-29 16:50:03 +00004309
Chris Lattner04421082008-04-08 04:40:51 +00004310/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4311/// to introduce parameters into function prototype scope.
Mike Stump1eb44332009-09-09 15:08:12 +00004312Sema::DeclPtrTy
Chris Lattner04421082008-04-08 04:40:51 +00004313Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00004314 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00004315
Chris Lattner04421082008-04-08 04:40:51 +00004316 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00004317 VarDecl::StorageClass StorageClass = VarDecl::None;
Douglas Gregor16573fa2010-04-19 22:54:31 +00004318 VarDecl::StorageClass StorageClassAsWritten = VarDecl::None;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00004319 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4320 StorageClass = VarDecl::Register;
Douglas Gregor16573fa2010-04-19 22:54:31 +00004321 StorageClassAsWritten = VarDecl::Register;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00004322 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00004323 Diag(DS.getStorageClassSpecLoc(),
4324 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00004325 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00004326 }
Eli Friedman63054b32009-04-19 20:27:55 +00004327
4328 if (D.getDeclSpec().isThreadSpecified())
4329 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4330
Eli Friedman85a53192009-04-07 19:37:57 +00004331 DiagnoseFunctionSpecifiers(D);
4332
Douglas Gregor6d6eb572008-05-07 04:49:29 +00004333 // Check that there are no default arguments inside the type of this
4334 // parameter (C++ only).
4335 if (getLangOptions().CPlusPlus)
4336 CheckExtraCXXDefaultArguments(D);
Mike Stump1eb44332009-09-09 15:08:12 +00004337
Douglas Gregor402abb52009-05-28 23:31:59 +00004338 TagDecl *OwnedDecl = 0;
John McCallbf1a0282010-06-04 23:28:52 +00004339 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedDecl);
4340 QualType parmDeclType = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004341
Douglas Gregor402abb52009-05-28 23:31:59 +00004342 if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
4343 // C++ [dcl.fct]p6:
4344 // Types shall not be defined in return or parameter types.
4345 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
4346 << Context.getTypeDeclType(OwnedDecl);
4347 }
4348
Chris Lattnerd84aac12010-02-22 00:40:25 +00004349 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattner04421082008-04-08 04:40:51 +00004350 IdentifierInfo *II = D.getIdentifier();
Chris Lattnercf79b012009-01-21 02:38:50 +00004351 if (II) {
John McCall10f28732010-03-18 06:42:38 +00004352 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
4353 ForRedeclaration);
4354 LookupName(R, S);
4355 if (R.isSingleResult()) {
4356 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnercf79b012009-01-21 02:38:50 +00004357 if (PrevDecl->isTemplateParameter()) {
4358 // Maybe we will complain about the shadowed template parameter.
4359 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4360 // Just pretend that we didn't see the previous declaration.
4361 PrevDecl = 0;
Chris Lattnerb28317a2009-03-28 19:18:32 +00004362 } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
Chris Lattnercf79b012009-01-21 02:38:50 +00004363 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerd84aac12010-02-22 00:40:25 +00004364 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattner04421082008-04-08 04:40:51 +00004365
Chris Lattnercf79b012009-01-21 02:38:50 +00004366 // Recover by removing the name
4367 II = 0;
4368 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00004369 D.setInvalidType(true);
Chris Lattnercf79b012009-01-21 02:38:50 +00004370 }
Chris Lattner04421082008-04-08 04:40:51 +00004371 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004372 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00004373
John McCall7a9813c2010-01-22 00:28:27 +00004374 // Temporarily put parameter variables in the translation unit, not
4375 // the enclosing context. This prevents them from accidentally
4376 // looking like class members in C++.
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00004377 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
4378 TInfo, parmDeclType, II,
Douglas Gregor16573fa2010-04-19 22:54:31 +00004379 D.getIdentifierLoc(),
4380 StorageClass, StorageClassAsWritten);
Mike Stump1eb44332009-09-09 15:08:12 +00004381
Chris Lattnereaaebc72009-04-25 08:06:05 +00004382 if (D.isInvalidType())
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00004383 New->setInvalidDecl();
4384
Chris Lattnerf97e8fa2009-04-11 19:34:56 +00004385 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4386 if (D.getCXXScopeSpec().isSet()) {
4387 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
4388 << D.getCXXScopeSpec().getRange();
4389 New->setInvalidDecl();
4390 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00004391
Douglas Gregor44b43212008-12-11 16:49:14 +00004392 // Add the parameter declaration into this scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004393 S->AddDecl(DeclPtrTy::make(New));
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00004394 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00004395 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00004396
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004397 ProcessDeclAttributes(S, New, D);
Mike Stumpea000bf2009-04-30 00:19:40 +00004398
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004399 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00004400 Diag(New->getLocation(), diag::err_block_on_nonlocal);
4401 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00004402 return DeclPtrTy::make(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00004403}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00004404
John McCall82dc0092010-06-04 11:21:44 +00004405/// \brief Synthesizes a variable for a parameter arising from a
4406/// typedef.
4407ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
4408 SourceLocation Loc,
4409 QualType T) {
4410 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, 0,
4411 T, Context.getTrivialTypeSourceInfo(T, Loc),
4412 VarDecl::None, VarDecl::None, 0);
4413 Param->setImplicit();
4414 return Param;
4415}
4416
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00004417ParmVarDecl *Sema::CheckParameter(DeclContext *DC,
4418 TypeSourceInfo *TSInfo, QualType T,
4419 IdentifierInfo *Name,
4420 SourceLocation NameLoc,
Douglas Gregor16573fa2010-04-19 22:54:31 +00004421 VarDecl::StorageClass StorageClass,
4422 VarDecl::StorageClass StorageClassAsWritten) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00004423 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, NameLoc, Name,
4424 adjustParameterType(T), TSInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00004425 StorageClass, StorageClassAsWritten,
4426 0);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00004427
4428 // Parameters can not be abstract class types.
4429 // For record types, this is done by the AbstractClassUsageDiagnoser once
4430 // the class has been completely parsed.
4431 if (!CurContext->isRecord() &&
4432 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
4433 AbstractParamType))
4434 New->setInvalidDecl();
4435
4436 // Parameter declarators cannot be interface types. All ObjC objects are
4437 // passed by reference.
John McCallc12c5bb2010-05-15 11:32:37 +00004438 if (T->isObjCObjectType()) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00004439 Diag(NameLoc,
4440 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
4441 New->setInvalidDecl();
4442 }
4443
4444 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4445 // duration shall not be qualified by an address-space qualifier."
4446 // Since all parameters have automatic store duration, they can not have
4447 // an address space.
4448 if (T.getAddressSpace() != 0) {
4449 Diag(NameLoc, diag::err_arg_with_address_space);
4450 New->setInvalidDecl();
4451 }
4452
4453 return New;
4454}
4455
Douglas Gregora3a83512009-04-01 23:51:29 +00004456void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4457 SourceLocation LocAfterDecls) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004458 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4459 "Not a function declarator!");
4460 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00004461
Reid Spencer5f016e22007-07-11 17:01:13 +00004462 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
4463 // for a K&R function.
4464 if (!FTI.hasPrototype) {
Douglas Gregor26103482009-04-02 03:14:12 +00004465 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
4466 --i;
Chris Lattner04421082008-04-08 04:40:51 +00004467 if (FTI.ArgInfo[i].Param == 0) {
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00004468 llvm::SmallString<256> Code;
4469 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004470 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00004471 << ";\n";
Chris Lattner3c73c412008-11-19 08:23:25 +00004472 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregora3a83512009-04-01 23:51:29 +00004473 << FTI.ArgInfo[i].Ident
Douglas Gregor849b2432010-03-31 17:46:05 +00004474 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregora3a83512009-04-01 23:51:29 +00004475
Reid Spencer5f016e22007-07-11 17:01:13 +00004476 // Implicitly declare the argument as type 'int' for lack of a better
4477 // type.
Chris Lattner04421082008-04-08 04:40:51 +00004478 DeclSpec DS;
4479 const char* PrevSpec; // unused
John McCallfec54012009-08-03 20:12:06 +00004480 unsigned DiagID; // unused
Mike Stump1eb44332009-09-09 15:08:12 +00004481 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCallfec54012009-08-03 20:12:06 +00004482 PrevSpec, DiagID);
Chris Lattner04421082008-04-08 04:40:51 +00004483 Declarator ParamD(DS, Declarator::KNRTypeListContext);
4484 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00004485 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00004486 }
4487 }
Mike Stump1eb44332009-09-09 15:08:12 +00004488 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00004489}
4490
Chris Lattnerb28317a2009-03-28 19:18:32 +00004491Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
4492 Declarator &D) {
Douglas Gregorbe109b32009-01-23 16:23:13 +00004493 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4494 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4495 "Not a function declarator!");
4496 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4497
4498 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00004499 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00004500 }
Mike Stump1eb44332009-09-09 15:08:12 +00004501
Douglas Gregor584049d2008-12-15 23:53:10 +00004502 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00004503
Mike Stump1eb44332009-09-09 15:08:12 +00004504 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregore542c862009-06-23 23:11:28 +00004505 MultiTemplateParamsArg(*this),
4506 /*IsFunctionDefinition=*/true);
Chris Lattner682bf922009-03-29 16:50:03 +00004507 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004508}
4509
Anders Carlsson9f89dd72009-12-09 03:30:09 +00004510static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
4511 // Don't warn about invalid declarations.
4512 if (FD->isInvalidDecl())
4513 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00004514
Anders Carlsson9f89dd72009-12-09 03:30:09 +00004515 // Or declarations that aren't global.
4516 if (!FD->isGlobal())
4517 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00004518
Anders Carlsson9f89dd72009-12-09 03:30:09 +00004519 // Don't warn about C++ member functions.
4520 if (isa<CXXMethodDecl>(FD))
4521 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00004522
Anders Carlsson9f89dd72009-12-09 03:30:09 +00004523 // Don't warn about 'main'.
4524 if (FD->isMain())
4525 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00004526
Anders Carlsson9f89dd72009-12-09 03:30:09 +00004527 // Don't warn about inline functions.
4528 if (FD->isInlineSpecified())
4529 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00004530
4531 // Don't warn about function templates.
4532 if (FD->getDescribedFunctionTemplate())
4533 return false;
4534
4535 // Don't warn about function template specializations.
4536 if (FD->isFunctionTemplateSpecialization())
4537 return false;
4538
Anders Carlsson9f89dd72009-12-09 03:30:09 +00004539 bool MissingPrototype = true;
4540 for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
4541 Prev; Prev = Prev->getPreviousDeclaration()) {
4542 // Ignore any declarations that occur in function or method
4543 // scope, because they aren't visible from the header.
4544 if (Prev->getDeclContext()->isFunctionOrMethod())
4545 continue;
4546
4547 MissingPrototype = !Prev->getType()->isFunctionProtoType();
4548 break;
4549 }
4550
4551 return MissingPrototype;
4552}
4553
Chris Lattnerb28317a2009-03-28 19:18:32 +00004554Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00004555 // Clear the last template instantiation error context.
4556 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
4557
Douglas Gregor52591bf2009-06-24 00:54:41 +00004558 if (!D)
4559 return D;
Douglas Gregord83d0402009-08-22 00:34:47 +00004560 FunctionDecl *FD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004561
4562 if (FunctionTemplateDecl *FunTmpl
Douglas Gregord83d0402009-08-22 00:34:47 +00004563 = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
4564 FD = FunTmpl->getTemplatedDecl();
4565 else
4566 FD = cast<FunctionDecl>(D.getAs<Decl>());
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00004567
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00004568 // Enter a new function scope
4569 PushFunctionScope();
Mike Stump1eb44332009-09-09 15:08:12 +00004570
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00004571 // See if this is a redefinition.
Charles Davisf3f8d2a2010-02-18 02:00:42 +00004572 // But don't complain if we're in GNU89 mode and the previous definition
4573 // was an extern inline function.
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00004574 const FunctionDecl *Definition;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004575 if (FD->hasBody(Definition) &&
Charles Davisf3f8d2a2010-02-18 02:00:42 +00004576 !canRedefineFunction(Definition, getLangOptions())) {
Chris Lattner08631c52008-11-23 21:45:46 +00004577 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00004578 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00004579 }
4580
Douglas Gregorcda9c672009-02-16 17:45:42 +00004581 // Builtin functions cannot be defined.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00004582 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor655753a2009-02-17 16:03:01 +00004583 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00004584 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor655753a2009-02-17 16:03:01 +00004585 FD->setInvalidDecl();
4586 }
Douglas Gregorcda9c672009-02-16 17:45:42 +00004587 }
4588
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00004589 // The return type of a function definition must be complete
Douglas Gregore7450f52009-03-24 19:52:54 +00004590 // (C99 6.9.1p3, C++ [dcl.fct]p6).
4591 QualType ResultType = FD->getResultType();
4592 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner65e6a092009-04-29 05:12:23 +00004593 !FD->isInvalidDecl() &&
Douglas Gregore7450f52009-03-24 19:52:54 +00004594 RequireCompleteType(FD->getLocation(), ResultType,
4595 diag::err_func_def_incomplete_result))
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00004596 FD->setInvalidDecl();
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00004597
Douglas Gregor8499f3f2009-03-31 16:35:03 +00004598 // GNU warning -Wmissing-prototypes:
4599 // Warn if a global function is defined without a previous
4600 // prototype declaration. This warning is issued even if the
4601 // definition itself provides a prototype. The aim is to detect
4602 // global functions that fail to be declared in header files.
Anders Carlsson9f89dd72009-12-09 03:30:09 +00004603 if (ShouldWarnAboutMissingPrototype(FD))
4604 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Douglas Gregor8499f3f2009-03-31 16:35:03 +00004605
Douglas Gregore2c31ff2009-05-15 17:59:04 +00004606 if (FnBodyScope)
4607 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00004608
Chris Lattner04421082008-04-08 04:40:51 +00004609 // Check the validity of our function parameters
4610 CheckParmsForFunctionDef(FD);
4611
John McCall053f4bd2010-03-22 09:20:08 +00004612 bool ShouldCheckShadow =
4613 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
4614
Chris Lattner04421082008-04-08 04:40:51 +00004615 // Introduce our parameters into the function scope
4616 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
4617 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00004618 Param->setOwningFunction(FD);
4619
Chris Lattner04421082008-04-08 04:40:51 +00004620 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00004621 if (Param->getIdentifier() && FnBodyScope) {
4622 if (ShouldCheckShadow)
4623 CheckShadow(FnBodyScope, Param);
4624
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00004625 PushOnScopeChains(Param, FnBodyScope);
John McCall053f4bd2010-03-22 09:20:08 +00004626 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004627 }
Chris Lattner04421082008-04-08 04:40:51 +00004628
Anton Korobeynikov2f402702008-12-26 00:52:02 +00004629 // Checking attributes of current function definition
4630 // dllimport attribute.
Mike Stump1eb44332009-09-09 15:08:12 +00004631 if (FD->getAttr<DLLImportAttr>() &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004632 (!FD->getAttr<DLLExportAttr>())) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00004633 // dllimport attribute cannot be applied to definition.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004634 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00004635 Diag(FD->getLocation(),
4636 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
4637 << "dllimport";
4638 FD->setInvalidDecl();
Chris Lattnerb28317a2009-03-28 19:18:32 +00004639 return DeclPtrTy::make(FD);
Ted Kremenek12911a82010-02-21 05:12:53 +00004640 }
4641
4642 // Visual C++ appears to not think this is an issue, so only issue
4643 // a warning when Microsoft extensions are disabled.
4644 if (!LangOpts.Microsoft) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00004645 // If a symbol previously declared dllimport is later defined, the
4646 // attribute is ignored in subsequent references, and a warning is
4647 // emitted.
4648 Diag(FD->getLocation(),
4649 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4650 << FD->getNameAsCString() << "dllimport";
4651 }
4652 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00004653 return DeclPtrTy::make(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00004654}
4655
Douglas Gregor5077c382010-05-15 06:01:05 +00004656/// \brief Given the set of return statements within a function body,
4657/// compute the variables that are subject to the named return value
4658/// optimization.
4659///
4660/// Each of the variables that is subject to the named return value
4661/// optimization will be marked as NRVO variables in the AST, and any
4662/// return statement that has a marked NRVO variable as its NRVO candidate can
4663/// use the named return value optimization.
4664///
4665/// This function applies a very simplistic algorithm for NRVO: if every return
4666/// statement in the function has the same NRVO candidate, that candidate is
4667/// the NRVO variable.
4668///
4669/// FIXME: Employ a smarter algorithm that accounts for multiple return
4670/// statements and the lifetimes of the NRVO candidates. We should be able to
4671/// find a maximal set of NRVO variables.
4672static void ComputeNRVO(Stmt *Body, ReturnStmt **Returns, unsigned NumReturns) {
4673 const VarDecl *NRVOCandidate = 0;
4674 for (unsigned I = 0; I != NumReturns; ++I) {
4675 if (!Returns[I]->getNRVOCandidate())
4676 return;
4677
4678 if (!NRVOCandidate)
4679 NRVOCandidate = Returns[I]->getNRVOCandidate();
4680 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
4681 return;
4682 }
4683
4684 if (NRVOCandidate)
4685 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
4686}
4687
Chris Lattnerb28317a2009-03-28 19:18:32 +00004688Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
Douglas Gregore2c31ff2009-05-15 17:59:04 +00004689 return ActOnFinishFunctionBody(D, move(BodyArg), false);
4690}
4691
4692Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
4693 bool IsInstantiation) {
Chris Lattnerb28317a2009-03-28 19:18:32 +00004694 Decl *dcl = D.getAs<Decl>();
Sebastian Redld3a413d2009-04-26 20:35:05 +00004695 Stmt *Body = BodyArg.takeAs<Stmt>();
Douglas Gregord83d0402009-08-22 00:34:47 +00004696
4697 FunctionDecl *FD = 0;
4698 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
4699 if (FunTmpl)
4700 FD = FunTmpl->getTemplatedDecl();
4701 else
4702 FD = dyn_cast_or_null<FunctionDecl>(dcl);
4703
Ted Kremenekd064fdc2010-03-23 00:13:23 +00004704 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00004705
Douglas Gregord83d0402009-08-22 00:34:47 +00004706 if (FD) {
Chris Lattnera5251fc2009-04-18 09:36:27 +00004707 FD->setBody(Body);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00004708 if (FD->isMain()) {
Mike Stump5f28a1e2009-07-24 02:49:01 +00004709 // C and C++ allow for main to automagically return 0.
John McCall0cfeb632009-07-28 01:00:58 +00004710 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
4711 FD->setHasImplicitReturnZero(true);
Ted Kremenekd064fdc2010-03-23 00:13:23 +00004712 WP.disableCheckFallThrough();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00004713 }
Mike Stump1eb44332009-09-09 15:08:12 +00004714
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004715 if (!FD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00004716 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004717
4718 // If this is a constructor, we need a vtable.
4719 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
4720 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor5077c382010-05-15 06:01:05 +00004721
4722 ComputeNRVO(Body, FunctionScopes.back()->Returns.data(),
4723 FunctionScopes.back()->Returns.size());
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004724 }
4725
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00004726 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00004727 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattnerffed1632009-02-16 19:27:54 +00004728 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattnera5251fc2009-04-18 09:36:27 +00004729 MD->setBody(Body);
Argyrios Kyrtzidisa2e85ad2009-07-18 00:33:33 +00004730 MD->setEndLoc(Body->getLocEnd());
Douglas Gregore0762c92009-06-19 23:52:42 +00004731 if (!MD->isInvalidDecl())
4732 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004733 } else {
Chris Lattnerb28317a2009-03-28 19:18:32 +00004734 return DeclPtrTy();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004735 }
Douglas Gregore2c31ff2009-05-15 17:59:04 +00004736
Reid Spencer5f016e22007-07-11 17:01:13 +00004737 // Verify and clean out per-function state.
Eli Friedman8f17b662009-02-28 05:41:13 +00004738
Reid Spencer5f016e22007-07-11 17:01:13 +00004739 // Check goto/label use.
Steve Naroffcaaacec2009-03-13 15:38:40 +00004740 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00004741 I = getLabelMap().begin(), E = getLabelMap().end(); I != E; ++I) {
Chris Lattnere32f74c2009-04-18 19:30:02 +00004742 LabelStmt *L = I->second;
Mike Stump1eb44332009-09-09 15:08:12 +00004743
Reid Spencer5f016e22007-07-11 17:01:13 +00004744 // Verify that we have no forward references left. If so, there was a goto
4745 // or address of a label taken, but no definition of it. Label fwd
4746 // definitions are indicated with a null substmt.
Chris Lattnere32f74c2009-04-18 19:30:02 +00004747 if (L->getSubStmt() != 0)
4748 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00004749
Chris Lattnere32f74c2009-04-18 19:30:02 +00004750 // Emit error.
4751 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004752
Chris Lattnere32f74c2009-04-18 19:30:02 +00004753 // At this point, we have gotos that use the bogus label. Stitch it into
4754 // the function body so that they aren't leaked and that the AST is well
4755 // formed.
4756 if (Body == 0) {
Douglas Gregorff331c12010-07-25 18:17:45 +00004757 // The whole function wasn't parsed correctly.
Chris Lattnere32f74c2009-04-18 19:30:02 +00004758 continue;
Reid Spencer5f016e22007-07-11 17:01:13 +00004759 }
Mike Stump1eb44332009-09-09 15:08:12 +00004760
Chris Lattnere32f74c2009-04-18 19:30:02 +00004761 // Otherwise, the body is valid: we want to stitch the label decl into the
4762 // function somewhere so that it is properly owned and so that the goto
4763 // has a valid target. Do this by creating a new compound stmt with the
4764 // label in it.
Sebastian Redld3a413d2009-04-26 20:35:05 +00004765
Chris Lattnere32f74c2009-04-18 19:30:02 +00004766 // Give the label a sub-statement.
4767 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
Sebastian Redld3a413d2009-04-26 20:35:05 +00004768
4769 CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
4770 cast<CXXTryStmt>(Body)->getTryBlock() :
4771 cast<CompoundStmt>(Body);
Ted Kremenek4c9f7092010-03-12 22:22:36 +00004772 llvm::SmallVector<Stmt*, 64> Elements(Compound->body_begin(),
4773 Compound->body_end());
Chris Lattnere32f74c2009-04-18 19:30:02 +00004774 Elements.push_back(L);
Ted Kremenek4c9f7092010-03-12 22:22:36 +00004775 Compound->setStmts(Context, Elements.data(), Elements.size());
Reid Spencer5f016e22007-07-11 17:01:13 +00004776 }
Eli Friedman8f17b662009-02-28 05:41:13 +00004777
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00004778 if (Body) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00004779 // C++ constructors that have function-try-blocks can't have return
4780 // statements in the handlers of that block. (C++ [except.handle]p14)
4781 // Verify this.
4782 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
4783 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
4784
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00004785 // Verify that that gotos and switch cases don't jump into scopes illegally.
4786 // Verify that that gotos and switch cases don't jump into scopes illegally.
John McCalldae69ef2010-05-20 07:05:55 +00004787 if (FunctionNeedsScopeChecking() &&
John McCall8a2ca742010-05-20 07:13:26 +00004788 !dcl->isInvalidDecl() &&
John McCalldae69ef2010-05-20 07:05:55 +00004789 !hasAnyErrorsInThisFunction())
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00004790 DiagnoseInvalidJumps(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00004791
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00004792 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
John McCallef027fe2010-03-16 21:39:52 +00004793 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4794 Destructor->getParent());
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00004795
4796 // If any errors have occurred, clear out any temporaries that may have
4797 // been leftover. This ensures that these temporaries won't be picked up for
4798 // deletion in some later function.
4799 if (PP.getDiagnostics().hasErrorOccurred())
4800 ExprTemporaries.clear();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00004801 else if (!isa<FunctionTemplateDecl>(dcl)) {
4802 // Since the body is valid, issue any analysis-based warnings that are
4803 // enabled.
4804 QualType ResultType;
4805 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
4806 ResultType = FD->getResultType();
4807 }
4808 else {
4809 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(dcl);
4810 ResultType = MD->getResultType();
4811 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +00004812 AnalysisWarnings.IssueWarnings(WP, dcl);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00004813 }
4814
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00004815 assert(ExprTemporaries.empty() && "Leftover temporaries in function");
4816 }
4817
John McCall90f97892010-03-25 22:08:03 +00004818 if (!IsInstantiation)
4819 PopDeclContext();
4820
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00004821 PopFunctionOrBlockScope();
Anders Carlssonf8a9a792009-11-13 19:21:49 +00004822
Douglas Gregord5b57282009-11-15 07:07:58 +00004823 // If any errors have occurred, clear out any temporaries that may have
4824 // been leftover. This ensures that these temporaries won't be picked up for
4825 // deletion in some later function.
Chris Lattner6d97e5e2010-03-01 20:59:53 +00004826 if (getDiagnostics().hasErrorOccurred())
Douglas Gregord5b57282009-11-15 07:07:58 +00004827 ExprTemporaries.clear();
4828
Steve Naroffd6d054d2007-11-11 23:20:51 +00004829 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00004830}
4831
Reid Spencer5f016e22007-07-11 17:01:13 +00004832/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4833/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump1eb44332009-09-09 15:08:12 +00004834NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004835 IdentifierInfo &II, Scope *S) {
Douglas Gregor63935192009-03-02 00:19:53 +00004836 // Before we produce a declaration for an implicitly defined
4837 // function, see whether there was a locally-scoped declaration of
4838 // this name as a function or variable. If so, use that
4839 // (non-visible) declaration, and complain about it.
4840 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4841 = LocallyScopedExternalDecls.find(&II);
4842 if (Pos != LocallyScopedExternalDecls.end()) {
4843 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
4844 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
4845 return Pos->second;
4846 }
4847
Chris Lattner37d10842008-05-05 21:18:06 +00004848 // Extension in C99. Legal in C90, but warn about it.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004849 if (II.getName().startswith("__builtin_"))
Douglas Gregor9a8c9a22009-09-28 21:14:19 +00004850 Diag(Loc, diag::warn_builtin_unknown) << &II;
4851 else if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00004852 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00004853 else
Chris Lattner3c73c412008-11-19 08:23:25 +00004854 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Mike Stump1eb44332009-09-09 15:08:12 +00004855
Reid Spencer5f016e22007-07-11 17:01:13 +00004856 // Set a Declarator for the implicit definition: int foo();
4857 const char *Dummy;
4858 DeclSpec DS;
John McCallfec54012009-08-03 20:12:06 +00004859 unsigned DiagID;
4860 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +00004861 Error = Error; // Silence warning.
4862 assert(!Error && "Error setting up implicit decl!");
4863 Declarator D(DS, Declarator::BlockContext);
Sebastian Redl7dc81342009-04-29 17:30:04 +00004864 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
Sebastian Redl3cc97262009-05-31 11:47:27 +00004865 0, 0, false, SourceLocation(),
Argyrios Kyrtzidis82bf0102009-08-19 23:14:54 +00004866 false, 0,0,0, Loc, Loc, D),
Sebastian Redlab197ba2009-02-09 18:23:29 +00004867 SourceLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00004868 D.SetIdentifier(&II, Loc);
Sebastian Redlab197ba2009-02-09 18:23:29 +00004869
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00004870 // Insert this function into translation-unit scope.
4871
4872 DeclContext *PrevDC = CurContext;
4873 CurContext = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004874
4875 FunctionDecl *FD =
Douglas Gregor2e01cda2009-06-23 21:43:56 +00004876 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
Steve Naroffe2ef8152008-04-04 14:32:09 +00004877 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00004878
4879 CurContext = PrevDC;
4880
Douglas Gregor3c385e52009-02-14 18:57:46 +00004881 AddKnownFunctionAttributes(FD);
4882
Steve Naroffe2ef8152008-04-04 14:32:09 +00004883 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00004884}
4885
Douglas Gregor3c385e52009-02-14 18:57:46 +00004886/// \brief Adds any function attributes that we know a priori based on
4887/// the declaration of this function.
4888///
4889/// These attributes can apply both to implicitly-declared builtins
4890/// (like __builtin___printf_chk) or to library-declared functions
4891/// like NSLog or printf.
4892void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
4893 if (FD->isInvalidDecl())
4894 return;
4895
4896 // If this is a built-in function, map its builtin attributes to
4897 // actual attributes.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00004898 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00004899 // Handle printf-formatting attributes.
4900 unsigned FormatIdx;
4901 bool HasVAListArg;
4902 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004903 if (!FD->getAttr<FormatAttr>())
Ted Kremenek3d2c43e2010-02-11 05:28:37 +00004904 FD->addAttr(::new (Context) FormatAttr(Context, "printf", FormatIdx+1,
4905 HasVAListArg ? 0 : FormatIdx+2));
Douglas Gregor3c385e52009-02-14 18:57:46 +00004906 }
Ted Kremenekbee05c12010-07-16 02:11:15 +00004907 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
4908 HasVAListArg)) {
4909 if (!FD->getAttr<FormatAttr>())
4910 FD->addAttr(::new (Context) FormatAttr(Context, "scanf", FormatIdx+1,
4911 HasVAListArg ? 0 : FormatIdx+2));
4912 }
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00004913
4914 // Mark const if we don't care about errno and that is the only
4915 // thing preventing the function from being const. This allows
4916 // IRgen to use LLVM intrinsics for such functions.
4917 if (!getLangOptions().MathErrno &&
4918 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004919 if (!FD->getAttr<ConstAttr>())
4920 FD->addAttr(::new (Context) ConstAttr());
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00004921 }
Mike Stump0feecbb2009-07-27 19:14:18 +00004922
4923 if (Context.BuiltinInfo.isNoReturn(BuiltinID))
John McCall04a67a62010-02-05 21:31:56 +00004924 FD->setType(Context.getNoReturnType(FD->getType()));
Chris Lattner551f7082009-12-30 22:06:22 +00004925 if (Context.BuiltinInfo.isNoThrow(BuiltinID))
4926 FD->addAttr(::new (Context) NoThrowAttr());
4927 if (Context.BuiltinInfo.isConst(BuiltinID))
4928 FD->addAttr(::new (Context) ConstAttr());
Douglas Gregor3c385e52009-02-14 18:57:46 +00004929 }
4930
4931 IdentifierInfo *Name = FD->getIdentifier();
4932 if (!Name)
4933 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004934 if ((!getLangOptions().CPlusPlus &&
Douglas Gregor3c385e52009-02-14 18:57:46 +00004935 FD->getDeclContext()->isTranslationUnit()) ||
4936 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00004937 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregor3c385e52009-02-14 18:57:46 +00004938 LinkageSpecDecl::lang_c)) {
4939 // Okay: this could be a libc/libm/Objective-C function we know
4940 // about.
4941 } else
4942 return;
4943
Douglas Gregor21e072b2009-04-22 20:56:09 +00004944 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
Mike Stump523a8fd2009-07-28 00:07:08 +00004945 // FIXME: NSLog and NSLogv should be target specific
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004946 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00004947 // FIXME: We known better than our headers.
Ted Kremenek3d2c43e2010-02-11 05:28:37 +00004948 const_cast<FormatAttr *>(Format)->setType(Context, "printf");
Mike Stump1eb44332009-09-09 15:08:12 +00004949 } else
Ted Kremenek3d2c43e2010-02-11 05:28:37 +00004950 FD->addAttr(::new (Context) FormatAttr(Context, "printf", 1,
Eli Friedmand7dad722009-06-10 04:01:38 +00004951 Name->isStr("NSLogv") ? 0 : 2));
Douglas Gregor21e072b2009-04-22 20:56:09 +00004952 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump523a8fd2009-07-28 00:07:08 +00004953 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump1eb44332009-09-09 15:08:12 +00004954 // target-specific builtins, perhaps?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004955 if (!FD->getAttr<FormatAttr>())
Ted Kremenek3d2c43e2010-02-11 05:28:37 +00004956 FD->addAttr(::new (Context) FormatAttr(Context, "printf", 2,
Eli Friedmand7dad722009-06-10 04:01:38 +00004957 Name->isStr("vasprintf") ? 0 : 3));
Mike Stump782fa302009-07-28 02:25:19 +00004958 }
Douglas Gregor3c385e52009-02-14 18:57:46 +00004959}
Reid Spencer5f016e22007-07-11 17:01:13 +00004960
John McCallba6a9bd2009-10-24 08:00:42 +00004961TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCalla93c9342009-12-07 02:54:59 +00004962 TypeSourceInfo *TInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004963 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00004964 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump1eb44332009-09-09 15:08:12 +00004965
John McCalla93c9342009-12-07 02:54:59 +00004966 if (!TInfo) {
John McCallba6a9bd2009-10-24 08:00:42 +00004967 assert(D.isInvalidType() && "no declarator info for valid type");
John McCalla93c9342009-12-07 02:54:59 +00004968 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +00004969 }
4970
Reid Spencer5f016e22007-07-11 17:01:13 +00004971 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00004972 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
4973 D.getIdentifierLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +00004974 D.getIdentifier(),
John McCalla93c9342009-12-07 02:54:59 +00004975 TInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004976
John McCall2191b202009-09-05 06:31:47 +00004977 if (const TagType *TT = T->getAs<TagType>()) {
Anders Carlsson4843e582009-03-10 17:07:44 +00004978 TagDecl *TD = TT->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004979
Anders Carlsson4843e582009-03-10 17:07:44 +00004980 // If the TagDecl that the TypedefDecl points to is an anonymous decl
4981 // keep track of the TypedefDecl.
4982 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
4983 TD->setTypedefForAnonDecl(NewTD);
4984 }
4985
Chris Lattnereaaebc72009-04-25 08:06:05 +00004986 if (D.isInvalidType())
Steve Naroff5912a352007-08-28 20:14:24 +00004987 NewTD->setInvalidDecl();
4988 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00004989}
4990
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004991
4992/// \brief Determine whether a tag with a given kind is acceptable
4993/// as a redeclaration of the given tag declaration.
4994///
4995/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00004996bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004997 TagTypeKind NewTag,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004998 SourceLocation NewTagLoc,
4999 const IdentifierInfo &Name) {
5000 // C++ [dcl.type.elab]p3:
5001 // The class-key or enum keyword present in the
5002 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005003 // declaration to which the name in the elaborated-type-specifier
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005004 // refers. This rule also applies to the form of
5005 // elaborated-type-specifier that declares a class-name or
5006 // friend class since it can be construed as referring to the
5007 // definition of the class. Thus, in any
5008 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005009 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005010 // used to refer to a union (clause 9), and either the class or
5011 // struct class-key shall be used to refer to a class (clause 9)
5012 // declared using the class or struct class-key.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005013 TagTypeKind OldTag = Previous->getTagKind();
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005014 if (OldTag == NewTag)
5015 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005016
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005017 if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
5018 (NewTag == TTK_Struct || NewTag == TTK_Class)) {
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005019 // Warn about the struct/class tag mismatch.
5020 bool isTemplate = false;
5021 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
5022 isTemplate = Record->getDescribedClassTemplate();
5023
5024 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005025 << (NewTag == TTK_Class)
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005026 << isTemplate << &Name
Douglas Gregor849b2432010-03-31 17:46:05 +00005027 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005028 OldTag == TTK_Class? "class" : "struct");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005029 Diag(Previous->getLocation(), diag::note_previous_use);
5030 return true;
5031 }
5032 return false;
5033}
5034
Steve Naroff08d92e42007-09-15 18:49:24 +00005035/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00005036/// former case, Name will be non-null. In the later case, Name will be null.
John McCall0f434ec2009-07-31 02:45:11 +00005037/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +00005038/// reference/declaration/definition of a tag.
John McCall0f434ec2009-07-31 02:45:11 +00005039Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005040 SourceLocation KWLoc, CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005041 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregor402abb52009-05-28 23:31:59 +00005042 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005043 MultiTemplateParamsArg TemplateParameterLists,
John McCallc4e70192009-09-11 04:59:25 +00005044 bool &OwnedDecl, bool &IsDependent) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005045 // If this is not a definition, it must have a name.
John McCall0f434ec2009-07-31 02:45:11 +00005046 assert((Name != 0 || TUK == TUK_Definition) &&
Reid Spencer5f016e22007-07-11 17:01:13 +00005047 "Nameless record must be a definition!");
Douglas Gregoraaba5e32009-02-04 19:02:06 +00005048
Douglas Gregor402abb52009-05-28 23:31:59 +00005049 OwnedDecl = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005050 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00005051
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005052 // FIXME: Check explicit specializations more carefully.
5053 bool isExplicitSpecialization = false;
Abramo Bagnara9b934882010-06-12 08:15:14 +00005054 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00005055 bool Invalid = false;
John McCall0f434ec2009-07-31 02:45:11 +00005056 if (TUK != TUK_Reference) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005057 if (TemplateParameterList *TemplateParams
5058 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
5059 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005060 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00005061 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00005062 isExplicitSpecialization,
5063 Invalid)) {
Abramo Bagnara9b934882010-06-12 08:15:14 +00005064 // All but one template parameter lists have been matching.
5065 --NumMatchedTemplateParamLists;
5066
Douglas Gregord85bea22009-09-26 06:47:28 +00005067 if (TemplateParams->size() > 0) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005068 // This is a declaration or definition of a class template (which may
5069 // be a member of another template).
Douglas Gregor0167f3c2010-07-14 23:14:12 +00005070 if (Invalid)
5071 return DeclPtrTy();
5072
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005073 OwnedDecl = false;
John McCall0f434ec2009-07-31 02:45:11 +00005074 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005075 SS, Name, NameLoc, Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00005076 TemplateParams,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005077 AS);
Douglas Gregor05396e22009-08-25 17:23:04 +00005078 TemplateParameterLists.release();
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005079 return Result.get();
5080 } else {
Douglas Gregorf6b11852009-10-08 15:14:33 +00005081 // The "template<>" header is extraneous.
5082 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005083 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorf6b11852009-10-08 15:14:33 +00005084 isExplicitSpecialization = true;
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005085 }
Mike Stump1eb44332009-09-09 15:08:12 +00005086 }
5087 }
5088
Douglas Gregor4920f1f2009-01-12 22:49:06 +00005089 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00005090 DeclContext *DC = CurContext;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005091 bool isStdBadAlloc = false;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005092
Chandler Carruth7bf36002010-03-01 21:17:36 +00005093 RedeclarationKind Redecl = ForRedeclaration;
5094 if (TUK == TUK_Friend || TUK == TUK_Reference)
5095 Redecl = NotForRedeclaration;
John McCall68263142009-11-18 22:49:29 +00005096
5097 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
John McCall6e247262009-10-10 05:48:19 +00005098
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005099 if (Name && SS.isNotEmpty()) {
5100 // We have a nested-name tag ('struct foo::bar').
5101
5102 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00005103 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005104 Name = 0;
5105 goto CreateNewDecl;
5106 }
5107
John McCallc4e70192009-09-11 04:59:25 +00005108 // If this is a friend or a reference to a class in a dependent
5109 // context, don't try to make a decl for it.
5110 if (TUK == TUK_Friend || TUK == TUK_Reference) {
5111 DC = computeDeclContext(SS, false);
5112 if (!DC) {
5113 IsDependent = true;
5114 return DeclPtrTy();
5115 }
John McCall77bb1aa2010-05-01 00:40:08 +00005116 } else {
5117 DC = computeDeclContext(SS, true);
5118 if (!DC) {
5119 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
5120 << SS.getRange();
5121 return DeclPtrTy();
5122 }
John McCallc4e70192009-09-11 04:59:25 +00005123 }
5124
John McCall77bb1aa2010-05-01 00:40:08 +00005125 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005126 return DeclPtrTy::make((Decl *)0);
5127
Douglas Gregor1931b442009-02-03 00:34:39 +00005128 SearchDC = DC;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00005129 // Look-up name inside 'foo::'.
John McCall68263142009-11-18 22:49:29 +00005130 LookupQualifiedName(Previous, DC);
John McCall6e247262009-10-10 05:48:19 +00005131
John McCall68263142009-11-18 22:49:29 +00005132 if (Previous.isAmbiguous())
John McCall6e247262009-10-10 05:48:19 +00005133 return DeclPtrTy();
John McCall6e247262009-10-10 05:48:19 +00005134
John McCall68263142009-11-18 22:49:29 +00005135 if (Previous.empty()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +00005136 // Name lookup did not find anything. However, if the
5137 // nested-name-specifier refers to the current instantiation,
5138 // and that current instantiation has any dependent base
5139 // classes, we might find something at instantiation time: treat
5140 // this as a dependent elaborated-type-specifier.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005141 if (Previous.wasNotFoundInCurrentInstantiation()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +00005142 IsDependent = true;
5143 return DeclPtrTy();
5144 }
5145
5146 // A tag 'foo::bar' must already exist.
Douglas Gregor1eabb7d2010-03-31 23:17:41 +00005147 Diag(NameLoc, diag::err_not_tag_in_scope)
5148 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005149 Name = 0;
Douglas Gregord0c87372009-05-27 17:30:49 +00005150 Invalid = true;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005151 goto CreateNewDecl;
5152 }
Chris Lattnercf79b012009-01-21 02:38:50 +00005153 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005154 // If this is a named struct, check to see if there was a previous forward
5155 // declaration or definition.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005156 // FIXME: We're looking into outer scopes here, even when we
5157 // shouldn't be. Doing so can result in ambiguities that we
5158 // shouldn't be diagnosing.
John McCall68263142009-11-18 22:49:29 +00005159 LookupName(Previous, S);
5160
5161 // Note: there used to be some attempt at recovery here.
5162 if (Previous.isAmbiguous())
5163 return DeclPtrTy();
Douglas Gregor72de6672009-01-08 20:45:30 +00005164
John McCall0f434ec2009-07-31 02:45:11 +00005165 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor72de6672009-01-08 20:45:30 +00005166 // FIXME: This makes sure that we ignore the contexts associated
5167 // with C structs, unions, and enums when looking for a matching
5168 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +00005169 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +00005170 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
5171 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +00005172 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005173 }
5174
John McCall68263142009-11-18 22:49:29 +00005175 if (Previous.isSingleResult() &&
5176 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00005177 // Maybe we will complain about the shadowed template parameter.
John McCall68263142009-11-18 22:49:29 +00005178 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor72c3f312008-12-05 18:15:24 +00005179 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +00005180 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +00005181 }
5182
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005183 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
5184 DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) {
5185 // This is a declaration of or a reference to "std::bad_alloc".
5186 isStdBadAlloc = true;
5187
John McCall68263142009-11-18 22:49:29 +00005188 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005189 // std::bad_alloc has been implicitly declared (but made invisible to
5190 // name lookup). Fill in this implicit declaration as the previous
5191 // declaration, so that the declarations get chained appropriately.
John McCall68263142009-11-18 22:49:29 +00005192 Previous.addDecl(StdBadAlloc);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005193 }
5194 }
John McCall68263142009-11-18 22:49:29 +00005195
John McCall9c86b512010-03-25 21:28:06 +00005196 // If we didn't find a previous declaration, and this is a reference
5197 // (or friend reference), move to the correct scope. In C++, we
5198 // also need to do a redeclaration lookup there, just in case
5199 // there's a shadow friend decl.
5200 if (Name && Previous.empty() &&
5201 (TUK == TUK_Reference || TUK == TUK_Friend)) {
5202 if (Invalid) goto CreateNewDecl;
5203 assert(SS.isEmpty());
5204
5205 if (TUK == TUK_Reference) {
5206 // C++ [basic.scope.pdecl]p5:
5207 // -- for an elaborated-type-specifier of the form
5208 //
5209 // class-key identifier
5210 //
5211 // if the elaborated-type-specifier is used in the
5212 // decl-specifier-seq or parameter-declaration-clause of a
5213 // function defined in namespace scope, the identifier is
5214 // declared as a class-name in the namespace that contains
5215 // the declaration; otherwise, except as a friend
5216 // declaration, the identifier is declared in the smallest
5217 // non-class, non-function-prototype scope that contains the
5218 // declaration.
5219 //
5220 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
5221 // C structs and unions.
5222 //
5223 // It is an error in C++ to declare (rather than define) an enum
5224 // type, including via an elaborated type specifier. We'll
5225 // diagnose that later; for now, declare the enum in the same
5226 // scope as we would have picked for any other tag type.
5227 //
5228 // GNU C also supports this behavior as part of its incomplete
5229 // enum types extension, while GNU C++ does not.
5230 //
5231 // Find the context where we'll be declaring the tag.
5232 // FIXME: We would like to maintain the current DeclContext as the
5233 // lexical context,
5234 while (SearchDC->isRecord())
5235 SearchDC = SearchDC->getParent();
5236
5237 // Find the scope where we'll be declaring the tag.
5238 while (S->isClassScope() ||
5239 (getLangOptions().CPlusPlus &&
5240 S->isFunctionPrototypeScope()) ||
5241 ((S->getFlags() & Scope::DeclScope) == 0) ||
5242 (S->getEntity() &&
5243 ((DeclContext *)S->getEntity())->isTransparentContext()))
5244 S = S->getParent();
5245 } else {
5246 assert(TUK == TUK_Friend);
5247 // C++ [namespace.memdef]p3:
5248 // If a friend declaration in a non-local class first declares a
5249 // class or function, the friend class or function is a member of
5250 // the innermost enclosing namespace.
5251 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCall9c86b512010-03-25 21:28:06 +00005252 }
5253
John McCall0d6b1642010-04-23 18:46:30 +00005254 // In C++, we need to do a redeclaration lookup to properly
5255 // diagnose some problems.
John McCall9c86b512010-03-25 21:28:06 +00005256 if (getLangOptions().CPlusPlus) {
5257 Previous.setRedeclarationKind(ForRedeclaration);
5258 LookupQualifiedName(Previous, SearchDC);
5259 }
5260 }
5261
John McCall68263142009-11-18 22:49:29 +00005262 if (!Previous.empty()) {
Douglas Gregor57265e32010-04-12 16:00:01 +00005263 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCall0d6b1642010-04-23 18:46:30 +00005264
5265 // It's okay to have a tag decl in the same scope as a typedef
5266 // which hides a tag decl in the same scope. Finding this
5267 // insanity with a redeclaration lookup can only actually happen
5268 // in C++.
5269 //
5270 // This is also okay for elaborated-type-specifiers, which is
5271 // technically forbidden by the current standard but which is
5272 // okay according to the likely resolution of an open issue;
5273 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
5274 if (getLangOptions().CPlusPlus) {
5275 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(PrevDecl)) {
5276 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
5277 TagDecl *Tag = TT->getDecl();
5278 if (Tag->getDeclName() == Name &&
Douglas Gregorc8fd2da2010-04-27 16:26:47 +00005279 Tag->getDeclContext()->getLookupContext()
5280 ->Equals(TD->getDeclContext()->getLookupContext())) {
John McCall0d6b1642010-04-23 18:46:30 +00005281 PrevDecl = Tag;
5282 Previous.clear();
5283 Previous.addDecl(Tag);
5284 }
5285 }
5286 }
5287 }
5288
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005289 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00005290 // If this is a use of a previous tag, or if the tag is already declared
5291 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005292 // rementions the tag), reuse the decl.
John McCall67d1a672009-08-06 02:15:43 +00005293 if (TUK == TUK_Reference || TUK == TUK_Friend ||
5294 isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00005295 // Make sure that this wasn't declared as an enum and now used as a
5296 // struct or something similar.
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005297 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005298 bool SafeToContinue
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005299 = (PrevTagDecl->getTagKind() != TTK_Enum &&
5300 Kind != TTK_Enum);
Douglas Gregora3a83512009-04-01 23:51:29 +00005301 if (SafeToContinue)
Mike Stump1eb44332009-09-09 15:08:12 +00005302 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00005303 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +00005304 << FixItHint::CreateReplacement(SourceRange(KWLoc),
5305 PrevTagDecl->getKindName());
Douglas Gregora3a83512009-04-01 23:51:29 +00005306 else
5307 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall68263142009-11-18 22:49:29 +00005308 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +00005309
Mike Stump1eb44332009-09-09 15:08:12 +00005310 if (SafeToContinue)
Douglas Gregora3a83512009-04-01 23:51:29 +00005311 Kind = PrevTagDecl->getTagKind();
5312 else {
5313 // Recover by making this an anonymous redefinition.
5314 Name = 0;
John McCall68263142009-11-18 22:49:29 +00005315 Previous.clear();
Douglas Gregora3a83512009-04-01 23:51:29 +00005316 Invalid = true;
5317 }
5318 }
5319
5320 if (!Invalid) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005321 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00005322
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005323 // FIXME: In the future, return a variant or some other clue
5324 // for the consumer of this Decl to know it doesn't own it.
5325 // For our current ASTs this shouldn't be a problem, but will
5326 // need to be changed with DeclGroups.
Douglas Gregore1aa9f32010-06-08 21:27:36 +00005327 if ((TUK == TUK_Reference && !PrevTagDecl->getFriendObjectKind()) ||
5328 TUK == TUK_Friend)
John McCall68263142009-11-18 22:49:29 +00005329 return DeclPtrTy::make(PrevTagDecl);
Douglas Gregoraaba5e32009-02-04 19:02:06 +00005330
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005331 // Diagnose attempts to redefine a tag.
John McCall0f434ec2009-07-31 02:45:11 +00005332 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00005333 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005334 // If we're defining a specialization and the previous definition
5335 // is from an implicit instantiation, don't emit an error
5336 // here; we'll catch this in the general case below.
5337 if (!isExplicitSpecialization ||
5338 !isa<CXXRecordDecl>(Def) ||
5339 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
5340 == TSK_ExplicitSpecialization) {
5341 Diag(NameLoc, diag::err_redefinition) << Name;
5342 Diag(Def->getLocation(), diag::note_previous_definition);
5343 // If this is a redefinition, recover by making this
5344 // struct be anonymous, which will make any later
5345 // references get the previous definition.
5346 Name = 0;
John McCall68263142009-11-18 22:49:29 +00005347 Previous.clear();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005348 Invalid = true;
5349 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005350 } else {
5351 // If the type is currently being defined, complain
5352 // about a nested redefinition.
5353 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
5354 if (Tag->isBeingDefined()) {
5355 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump1eb44332009-09-09 15:08:12 +00005356 Diag(PrevTagDecl->getLocation(),
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005357 diag::note_previous_definition);
5358 Name = 0;
John McCall68263142009-11-18 22:49:29 +00005359 Previous.clear();
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005360 Invalid = true;
5361 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005362 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005363
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005364 // Okay, this is definition of a previously declared or referenced
5365 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005366 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005367 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005368 // If we get here we have (another) forward declaration or we
John McCall67d1a672009-08-06 02:15:43 +00005369 // have a definition. Just create a new decl.
5370
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005371 } else {
5372 // If we get here, this is a definition of a new tag type in a nested
Mike Stump1eb44332009-09-09 15:08:12 +00005373 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005374 // new decl/type. We set PrevDecl to NULL so that the entities
5375 // have distinct types.
John McCall68263142009-11-18 22:49:29 +00005376 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +00005377 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005378 // If we get here, we're going to create a new Decl. If PrevDecl
5379 // is non-NULL, it's a definition of the tag declared by
5380 // PrevDecl. If it's NULL, we have a new definition.
John McCall0d6b1642010-04-23 18:46:30 +00005381
5382
5383 // Otherwise, PrevDecl is not a tag, but was found with tag
5384 // lookup. This is only actually possible in C++, where a few
5385 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005386 } else {
John McCall0d6b1642010-04-23 18:46:30 +00005387 assert(getLangOptions().CPlusPlus);
5388
5389 // Use a better diagnostic if an elaborated-type-specifier
5390 // found the wrong kind of type on the first
5391 // (non-redeclaration) lookup.
5392 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
5393 !Previous.isForRedeclaration()) {
5394 unsigned Kind = 0;
5395 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
5396 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
5397 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
5398 Diag(PrevDecl->getLocation(), diag::note_declared_at);
5399 Invalid = true;
5400
5401 // Otherwise, only diagnose if the declaration is in scope.
5402 } else if (!isDeclInScope(PrevDecl, SearchDC, S)) {
5403 // do nothing
5404
5405 // Diagnose implicit declarations introduced by elaborated types.
5406 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
5407 unsigned Kind = 0;
5408 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
5409 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
5410 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
5411 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
5412 Invalid = true;
5413
5414 // Otherwise it's a declaration. Call out a particularly common
5415 // case here.
5416 } else if (isa<TypedefDecl>(PrevDecl)) {
5417 Diag(NameLoc, diag::err_tag_definition_of_typedef)
5418 << Name
5419 << cast<TypedefDecl>(PrevDecl)->getUnderlyingType();
5420 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
5421 Invalid = true;
5422
5423 // Otherwise, diagnose.
5424 } else {
5425 // The tag name clashes with something else in the target scope,
5426 // issue an error and recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00005427 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00005428 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00005429 Name = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005430 Invalid = true;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00005431 }
John McCall0d6b1642010-04-23 18:46:30 +00005432
5433 // The existing declaration isn't relevant to us; we're in a
5434 // new scope, so clear out the previous declaration.
5435 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +00005436 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005437 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00005438
Chris Lattnercc98eac2008-12-17 07:13:27 +00005439CreateNewDecl:
Mike Stump1eb44332009-09-09 15:08:12 +00005440
John McCall68263142009-11-18 22:49:29 +00005441 TagDecl *PrevDecl = 0;
5442 if (Previous.isSingleResult())
5443 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
5444
Reid Spencer5f016e22007-07-11 17:01:13 +00005445 // If there is an identifier, use the location of the identifier as the
5446 // location of the decl, otherwise use the location of the struct/union
5447 // keyword.
5448 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00005449
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005450 // Otherwise, create a new declaration. If there is a previous
5451 // declaration of the same entity, the two will be linked via
5452 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00005453 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00005454
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005455 if (Kind == TTK_Enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005456 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
5457 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor741dd9a2009-07-21 14:46:17 +00005458 New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005459 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00005460 // If this is an undefined enum, warn.
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +00005461 if (TUK != TUK_Definition && !Invalid) {
5462 TagDecl *Def;
5463 if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
5464 Diag(Loc, diag::ext_forward_ref_enum_def)
5465 << New;
5466 Diag(Def->getLocation(), diag::note_previous_definition);
5467 } else {
5468 Diag(Loc,
5469 getLangOptions().CPlusPlus? diag::err_forward_ref_enum
5470 : diag::ext_forward_ref_enum);
5471 }
Douglas Gregor80711a22009-03-06 18:34:03 +00005472 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00005473 } else {
5474 // struct/union/class
5475
Reid Spencer5f016e22007-07-11 17:01:13 +00005476 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
5477 // struct X { int A; } D; D should chain to X.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005478 if (getLangOptions().CPlusPlus) {
Ted Kremenek2b345eb2008-09-05 17:39:33 +00005479 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor741dd9a2009-07-21 14:46:17 +00005480 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005481 cast_or_null<CXXRecordDecl>(PrevDecl));
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005482
5483 if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit()))
5484 StdBadAlloc = cast<CXXRecordDecl>(New);
5485 } else
Douglas Gregor741dd9a2009-07-21 14:46:17 +00005486 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005487 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005488 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005489
John McCallb6217662010-03-15 10:12:16 +00005490 // Maybe add qualifier info.
5491 if (SS.isNotEmpty()) {
Fariborz Jahanian4fb20532010-05-14 21:35:02 +00005492 if (SS.isSet()) {
5493 NestedNameSpecifier *NNS
5494 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5495 New->setQualifierInfo(NNS, SS.getRange());
Abramo Bagnara9b934882010-06-12 08:15:14 +00005496 if (NumMatchedTemplateParamLists > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00005497 New->setTemplateParameterListsInfo(Context,
5498 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00005499 (TemplateParameterList**) TemplateParameterLists.release());
5500 }
Fariborz Jahanian4fb20532010-05-14 21:35:02 +00005501 }
5502 else
5503 Invalid = true;
John McCallb6217662010-03-15 10:12:16 +00005504 }
5505
Daniel Dunbar9f21f892010-05-27 01:53:40 +00005506 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
5507 // Add alignment attributes if necessary; these attributes are checked when
5508 // the ASTContext lays out the structure.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005509 //
5510 // It is important for implementing the correct semantics that this
5511 // happen here (in act on tag decl). The #pragma pack stack is
5512 // maintained as a result of parser callbacks which can occur at
5513 // many points during the parsing of a struct declaration (because
5514 // the #pragma tokens are effectively skipped over during the
5515 // parsing of the struct).
Daniel Dunbar9f21f892010-05-27 01:53:40 +00005516 AddAlignmentAttributesForRecord(RD);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005517 }
5518
Douglas Gregorf6b11852009-10-08 15:14:33 +00005519 // If this is a specialization of a member class (of a class template),
5520 // check the specialization.
John McCall68263142009-11-18 22:49:29 +00005521 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorf6b11852009-10-08 15:14:33 +00005522 Invalid = true;
Daniel Dunbar9f21f892010-05-27 01:53:40 +00005523
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005524 if (Invalid)
5525 New->setInvalidDecl();
5526
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005527 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005528 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005529
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005530 // If we're declaring or defining a tag in function prototype scope
5531 // in C, note that this type can only be used within the function.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00005532 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
5533 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
5534
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005535 // Set the lexical context. If the tag has a C++ scope specifier, the
5536 // lexical context will be different from the semantic context.
Douglas Gregor1931b442009-02-03 00:34:39 +00005537 New->setLexicalDeclContext(CurContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005538
John McCall02cace72009-08-28 07:59:38 +00005539 // Mark this as a friend decl if applicable.
5540 if (TUK == TUK_Friend)
John McCall68263142009-11-18 22:49:29 +00005541 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
John McCall02cace72009-08-28 07:59:38 +00005542
Anders Carlsson0cf88302009-03-26 01:19:02 +00005543 // Set the access specifier.
John McCall9c86b512010-03-25 21:28:06 +00005544 if (!Invalid && SearchDC->isRecord())
Douglas Gregord0c87372009-05-27 17:30:49 +00005545 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor06c0fec2009-03-25 22:00:53 +00005546
John McCall0f434ec2009-07-31 02:45:11 +00005547 if (TUK == TUK_Definition)
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005548 New->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00005549
Reid Spencer5f016e22007-07-11 17:01:13 +00005550 // If this has an identifier, add it to the scope stack.
John McCalld7eff682009-09-02 00:55:30 +00005551 if (TUK == TUK_Friend) {
John McCall82b9fb82009-09-02 19:32:14 +00005552 // We might be replacing an existing declaration in the lookup tables;
5553 // if so, borrow its access specifier.
5554 if (PrevDecl)
5555 New->setAccess(PrevDecl->getAccess());
5556
John McCall9c86b512010-03-25 21:28:06 +00005557 DeclContext *DC = New->getDeclContext()->getLookupContext();
5558 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
5559 if (Name) // can be null along some error paths
John McCalld7eff682009-09-02 00:55:30 +00005560 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
5561 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCalld7eff682009-09-02 00:55:30 +00005562 } else if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00005563 S = getNonFieldDeclScope(S);
Douglas Gregor1931b442009-02-03 00:34:39 +00005564 PushOnScopeChains(New, S);
Douglas Gregor4920f1f2009-01-12 22:49:06 +00005565 } else {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005566 CurContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00005567 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00005568
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005569 // If this is the C FILE type, notify the AST context.
5570 if (IdentifierInfo *II = New->getIdentifier())
5571 if (!New->isInvalidDecl() &&
Mike Stump782fa302009-07-28 02:25:19 +00005572 New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005573 II->isStr("FILE"))
5574 Context.setFILEDecl(New);
Mike Stump1eb44332009-09-09 15:08:12 +00005575
Douglas Gregor402abb52009-05-28 23:31:59 +00005576 OwnedDecl = true;
Chris Lattnerb28317a2009-03-28 19:18:32 +00005577 return DeclPtrTy::make(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00005578}
5579
Chris Lattnerb28317a2009-03-28 19:18:32 +00005580void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +00005581 AdjustDeclIfTemplate(TagD);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005582 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
Douglas Gregor48c89f42010-04-24 16:38:41 +00005583
Douglas Gregor72de6672009-01-08 20:45:30 +00005584 // Enter the tag context.
5585 PushDeclContext(S, Tag);
John McCallf9368152009-12-20 07:58:13 +00005586}
Douglas Gregor72de6672009-01-08 20:45:30 +00005587
John McCallf9368152009-12-20 07:58:13 +00005588void Sema::ActOnStartCXXMemberDeclarations(Scope *S, DeclPtrTy TagD,
5589 SourceLocation LBraceLoc) {
5590 AdjustDeclIfTemplate(TagD);
5591 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD.getAs<Decl>());
Douglas Gregor72de6672009-01-08 20:45:30 +00005592
John McCallf9368152009-12-20 07:58:13 +00005593 FieldCollector->StartClass();
5594
5595 if (!Record->getIdentifier())
5596 return;
5597
5598 // C++ [class]p2:
5599 // [...] The class-name is also inserted into the scope of the
5600 // class itself; this is known as the injected-class-name. For
5601 // purposes of access checking, the injected-class-name is treated
5602 // as if it were a public member name.
5603 CXXRecordDecl *InjectedClassName
5604 = CXXRecordDecl::Create(Context, Record->getTagKind(),
5605 CurContext, Record->getLocation(),
5606 Record->getIdentifier(),
5607 Record->getTagKeywordLoc(),
5608 Record);
5609 InjectedClassName->setImplicit();
5610 InjectedClassName->setAccess(AS_public);
5611 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
5612 InjectedClassName->setDescribedClassTemplate(Template);
5613 PushOnScopeChains(InjectedClassName, S);
5614 assert(InjectedClassName->isInjectedClassName() &&
5615 "Broken injected-class-name");
Douglas Gregor72de6672009-01-08 20:45:30 +00005616}
5617
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +00005618void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
5619 SourceLocation RBraceLoc) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +00005620 AdjustDeclIfTemplate(TagD);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005621 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +00005622 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor72de6672009-01-08 20:45:30 +00005623
5624 if (isa<CXXRecordDecl>(Tag))
5625 FieldCollector->FinishClass();
5626
5627 // Exit this scope of this tag's definition.
5628 PopDeclContext();
Douglas Gregoradda8462010-01-06 17:00:51 +00005629
Douglas Gregor72de6672009-01-08 20:45:30 +00005630 // Notify the consumer that we've defined a tag.
5631 Consumer.HandleTagDeclDefinition(Tag);
5632}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00005633
John McCalldb7bb4a2010-03-17 00:38:33 +00005634void Sema::ActOnTagDefinitionError(Scope *S, DeclPtrTy TagD) {
5635 AdjustDeclIfTemplate(TagD);
5636 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
John McCalldb7bb4a2010-03-17 00:38:33 +00005637 Tag->setInvalidDecl();
5638
John McCalla8cab012010-03-17 19:25:57 +00005639 // We're undoing ActOnTagStartDefinition here, not
5640 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
5641 // the FieldCollector.
John McCalldb7bb4a2010-03-17 00:38:33 +00005642
5643 PopDeclContext();
5644}
5645
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00005646// Note that FieldName may be null for anonymous bitfields.
Mike Stump1eb44332009-09-09 15:08:12 +00005647bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Eli Friedman1d954f62009-08-15 21:55:26 +00005648 QualType FieldTy, const Expr *BitWidth,
5649 bool *ZeroWidth) {
5650 // Default to true; that shouldn't confuse checks for emptiness
5651 if (ZeroWidth)
5652 *ZeroWidth = true;
5653
Chris Lattner24793662009-03-05 22:45:59 +00005654 // C99 6.7.2.1p4 - verify the field type.
Chris Lattner8b963ef2009-03-05 23:01:03 +00005655 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005656 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner24793662009-03-05 22:45:59 +00005657 // Handle incomplete types with specific error.
Douglas Gregora03aca82009-03-10 21:58:27 +00005658 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
5659 return true;
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00005660 if (FieldName)
5661 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
5662 << FieldName << FieldTy << BitWidth->getSourceRange();
5663 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
5664 << FieldTy << BitWidth->getSourceRange();
Chris Lattner24793662009-03-05 22:45:59 +00005665 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005666
5667 // If the bit-width is type- or value-dependent, don't try to check
5668 // it now.
5669 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
5670 return false;
5671
Anders Carlsson9f1e5722008-12-06 20:33:04 +00005672 llvm::APSInt Value;
5673 if (VerifyIntegerConstantExpression(BitWidth, &Value))
5674 return true;
5675
Eli Friedman1d954f62009-08-15 21:55:26 +00005676 if (Value != 0 && ZeroWidth)
5677 *ZeroWidth = false;
5678
Chris Lattnercd087072008-12-12 04:56:04 +00005679 // Zero-width bitfield is ok for anonymous field.
5680 if (Value == 0 && FieldName)
5681 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00005682
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00005683 if (Value.isSigned() && Value.isNegative()) {
5684 if (FieldName)
Mike Stump1eb44332009-09-09 15:08:12 +00005685 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00005686 << FieldName << Value.toString(10);
5687 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
5688 << Value.toString(10);
5689 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00005690
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005691 if (!FieldTy->isDependentType()) {
5692 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00005693 if (Value.getZExtValue() > TypeSize) {
Anders Carlsson72468ec2010-04-16 15:16:32 +00005694 if (!getLangOptions().CPlusPlus) {
5695 if (FieldName)
5696 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
5697 << FieldName << (unsigned)Value.getZExtValue()
5698 << (unsigned)TypeSize;
5699
5700 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
5701 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
5702 }
5703
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00005704 if (FieldName)
Anders Carlsson72468ec2010-04-16 15:16:32 +00005705 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
5706 << FieldName << (unsigned)Value.getZExtValue()
5707 << (unsigned)TypeSize;
5708 else
5709 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
5710 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00005711 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005712 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00005713
5714 return false;
5715}
5716
Steve Naroff08d92e42007-09-15 18:49:24 +00005717/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00005718/// to create a FieldDecl object for it.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005719Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
Mike Stump1eb44332009-09-09 15:08:12 +00005720 SourceLocation DeclStart,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005721 Declarator &D, ExprTy *BitfieldWidth) {
5722 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
5723 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
5724 AS_public);
5725 return DeclPtrTy::make(Res);
Chris Lattner24793662009-03-05 22:45:59 +00005726}
5727
5728/// HandleField - Analyze a field of a C struct or a C++ data member.
5729///
5730FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
5731 SourceLocation DeclStart,
Douglas Gregor4dd55f52009-03-11 20:50:30 +00005732 Declarator &D, Expr *BitWidth,
5733 AccessSpecifier AS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005734 IdentifierInfo *II = D.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +00005735 SourceLocation Loc = DeclStart;
5736 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00005737
John McCallbf1a0282010-06-04 23:28:52 +00005738 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5739 QualType T = TInfo->getType();
Chris Lattner6491f472009-04-12 22:15:02 +00005740 if (getLangOptions().CPlusPlus)
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005741 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +00005742
Eli Friedman85a53192009-04-07 19:37:57 +00005743 DiagnoseFunctionSpecifiers(D);
5744
Eli Friedman63054b32009-04-19 20:27:55 +00005745 if (D.getDeclSpec().isThreadSpecified())
5746 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5747
Douglas Gregorc83c6872010-04-15 22:33:43 +00005748 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall7d384dd2009-11-18 07:57:50 +00005749 ForRedeclaration);
Douglas Gregorc19ee3e2009-06-17 23:37:01 +00005750
5751 if (PrevDecl && PrevDecl->isTemplateParameter()) {
5752 // Maybe we will complain about the shadowed template parameter.
5753 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5754 // Just pretend that we didn't see the previous declaration.
5755 PrevDecl = 0;
5756 }
5757
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005758 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
5759 PrevDecl = 0;
5760
Steve Naroffea218b82009-07-14 14:58:18 +00005761 bool Mutable
5762 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
5763 SourceLocation TSSL = D.getSourceRange().getBegin();
5764 FieldDecl *NewFD
John McCalla93c9342009-12-07 02:54:59 +00005765 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
Steve Naroffea218b82009-07-14 14:58:18 +00005766 AS, PrevDecl, &D);
Rafael Espindola01620702010-03-21 22:56:43 +00005767
5768 if (NewFD->isInvalidDecl())
5769 Record->setInvalidDecl();
5770
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005771 if (NewFD->isInvalidDecl() && PrevDecl) {
5772 // Don't introduce NewFD into scope; there's already something
5773 // with the same name in the same scope.
5774 } else if (II) {
5775 PushOnScopeChains(NewFD, S);
5776 } else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005777 Record->addDecl(NewFD);
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005778
5779 return NewFD;
5780}
5781
5782/// \brief Build a new FieldDecl and check its well-formedness.
5783///
5784/// This routine builds a new FieldDecl given the fields name, type,
5785/// record, etc. \p PrevDecl should refer to any previous declaration
5786/// with the same name and in the same scope as the field to be
5787/// created.
5788///
5789/// \returns a new FieldDecl.
5790///
Mike Stump1eb44332009-09-09 15:08:12 +00005791/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00005792FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCalla93c9342009-12-07 02:54:59 +00005793 TypeSourceInfo *TInfo,
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005794 RecordDecl *Record, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005795 bool Mutable, Expr *BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +00005796 SourceLocation TSSL,
Douglas Gregor4dd55f52009-03-11 20:50:30 +00005797 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005798 Declarator *D) {
5799 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Naroff5912a352007-08-28 20:14:24 +00005800 bool InvalidDecl = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +00005801 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redl64b45f72009-01-05 20:52:13 +00005802
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005803 // If we receive a broken type, recover by assuming 'int' and
5804 // marking this declaration as invalid.
5805 if (T.isNull()) {
5806 InvalidDecl = true;
5807 T = Context.IntTy;
5808 }
5809
Eli Friedman721e77d2009-12-07 00:22:08 +00005810 QualType EltTy = Context.getBaseElementType(T);
5811 if (!EltTy->isDependentType() &&
5812 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete))
5813 InvalidDecl = true;
5814
Reid Spencer5f016e22007-07-11 17:01:13 +00005815 // C99 6.7.2.1p8: A member of a structure or union may have any type other
5816 // than a variably modified type.
Eli Friedman721e77d2009-12-07 00:22:08 +00005817 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedman1ca48132009-02-21 00:44:51 +00005818 bool SizeIsNegative;
5819 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
5820 SizeIsNegative);
5821 if (!FixedTy.isNull()) {
5822 Diag(Loc, diag::warn_illegal_constant_array_size);
5823 T = FixedTy;
5824 } else {
5825 if (SizeIsNegative)
5826 Diag(Loc, diag::err_typecheck_negative_array_size);
5827 else
5828 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedman1ca48132009-02-21 00:44:51 +00005829 InvalidDecl = true;
5830 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005831 }
Mike Stump1eb44332009-09-09 15:08:12 +00005832
Anders Carlsson4681ebd2009-03-22 20:18:17 +00005833 // Fields can not have abstract class types
Eli Friedman721e77d2009-12-07 00:22:08 +00005834 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
5835 diag::err_abstract_type_in_decl,
5836 AbstractFieldType))
Anders Carlsson4681ebd2009-03-22 20:18:17 +00005837 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00005838
Eli Friedman1d954f62009-08-15 21:55:26 +00005839 bool ZeroWidth = false;
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005840 // If this is declared as a bit-field, check the bit-field.
Eli Friedman721e77d2009-12-07 00:22:08 +00005841 if (!InvalidDecl && BitWidth &&
5842 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005843 InvalidDecl = true;
5844 DeleteExpr(BitWidth);
5845 BitWidth = 0;
Eli Friedman1d954f62009-08-15 21:55:26 +00005846 ZeroWidth = false;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00005847 }
Mike Stump1eb44332009-09-09 15:08:12 +00005848
John McCall4bde1e12010-06-04 08:34:12 +00005849 // Check that 'mutable' is consistent with the type of the declaration.
5850 if (!InvalidDecl && Mutable) {
5851 unsigned DiagID = 0;
5852 if (T->isReferenceType())
5853 DiagID = diag::err_mutable_reference;
5854 else if (T.isConstQualified())
5855 DiagID = diag::err_mutable_const;
5856
5857 if (DiagID) {
5858 SourceLocation ErrLoc = Loc;
5859 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
5860 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
5861 Diag(ErrLoc, DiagID);
5862 Mutable = false;
5863 InvalidDecl = true;
5864 }
5865 }
5866
John McCalla93c9342009-12-07 02:54:59 +00005867 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00005868 BitWidth, Mutable);
Chris Lattnereaaebc72009-04-25 08:06:05 +00005869 if (InvalidDecl)
5870 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00005871
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005872 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
5873 Diag(Loc, diag::err_duplicate_member) << II;
5874 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5875 NewFD->setInvalidDecl();
Douglas Gregor72de6672009-01-08 20:45:30 +00005876 }
5877
John McCall86ff3082010-02-04 22:26:26 +00005878 if (!InvalidDecl && getLangOptions().CPlusPlus) {
Eli Friedman1d954f62009-08-15 21:55:26 +00005879 CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
5880
5881 if (!T->isPODType())
5882 CXXRecord->setPOD(false);
5883 if (!ZeroWidth)
5884 CXXRecord->setEmpty(false);
5885
Ted Kremenek6217b802009-07-29 21:53:49 +00005886 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Douglas Gregor1f2023a2009-07-22 18:25:24 +00005887 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
Douglas Gregord27e50c2010-06-16 16:54:04 +00005888 if (RDecl->getDefinition()) {
5889 if (!RDecl->hasTrivialConstructor())
5890 CXXRecord->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +00005891 if (!RDecl->hasTrivialCopyConstructor())
Douglas Gregord27e50c2010-06-16 16:54:04 +00005892 CXXRecord->setHasTrivialCopyConstructor(false);
5893 if (!RDecl->hasTrivialCopyAssignment())
5894 CXXRecord->setHasTrivialCopyAssignment(false);
5895 if (!RDecl->hasTrivialDestructor())
5896 CXXRecord->setHasTrivialDestructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +00005897
Douglas Gregord27e50c2010-06-16 16:54:04 +00005898 // C++ 9.5p1: An object of a class with a non-trivial
5899 // constructor, a non-trivial copy constructor, a non-trivial
5900 // destructor, or a non-trivial copy assignment operator
5901 // cannot be a member of a union, nor can an array of such
5902 // objects.
5903 // TODO: C++0x alters this restriction significantly.
5904 if (Record->isUnion()) {
5905 // We check for copy constructors before constructors
5906 // because otherwise we'll never get complaints about
5907 // copy constructors.
5908
5909 CXXSpecialMember member = CXXInvalid;
5910 if (!RDecl->hasTrivialCopyConstructor())
5911 member = CXXCopyConstructor;
5912 else if (!RDecl->hasTrivialConstructor())
5913 member = CXXConstructor;
5914 else if (!RDecl->hasTrivialCopyAssignment())
5915 member = CXXCopyAssignment;
5916 else if (!RDecl->hasTrivialDestructor())
5917 member = CXXDestructor;
5918
5919 if (member != CXXInvalid) {
5920 Diag(Loc, diag::err_illegal_union_member) << Name << member;
5921 DiagnoseNontrivial(RT, member);
5922 NewFD->setInvalidDecl();
5923 }
Douglas Gregor1f2023a2009-07-22 18:25:24 +00005924 }
5925 }
5926 }
5927 }
5928
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005929 // FIXME: We need to pass in the attributes given an AST
5930 // representation, not a parser representation.
5931 if (D)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005932 // FIXME: What to pass instead of TUScope?
5933 ProcessDeclAttributes(TUScope, NewFD, *D);
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005934
Fariborz Jahanianf6123ca2009-02-19 00:22:47 +00005935 if (T.isObjCGCWeak())
Fariborz Jahanianed7e9ef2009-02-18 18:14:41 +00005936 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlssonad148062008-02-16 00:29:18 +00005937
Douglas Gregor4dd55f52009-03-11 20:50:30 +00005938 NewFD->setAccess(AS);
5939
5940 // C++ [dcl.init.aggr]p1:
5941 // An aggregate is an array or a class (clause 9) with [...] no
5942 // private or protected non-static data members (clause 11).
5943 // A POD must be an aggregate.
5944 if (getLangOptions().CPlusPlus &&
5945 (AS == AS_private || AS == AS_protected)) {
5946 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
5947 CXXRecord->setAggregate(false);
5948 CXXRecord->setPOD(false);
5949 }
5950
Steve Naroff5912a352007-08-28 20:14:24 +00005951 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00005952}
5953
Douglas Gregor1f2023a2009-07-22 18:25:24 +00005954/// DiagnoseNontrivial - Given that a class has a non-trivial
5955/// special member, figure out why.
5956void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
5957 QualType QT(T, 0U);
5958 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
5959
5960 // Check whether the member was user-declared.
5961 switch (member) {
Douglas Gregor66dd9392010-04-22 14:36:26 +00005962 case CXXInvalid:
5963 break;
5964
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00005965 case CXXConstructor:
Douglas Gregor1f2023a2009-07-22 18:25:24 +00005966 if (RD->hasUserDeclaredConstructor()) {
5967 typedef CXXRecordDecl::ctor_iterator ctor_iter;
Sebastian Redl38fd4d02009-10-25 22:31:45 +00005968 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
5969 const FunctionDecl *body = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00005970 ci->hasBody(body);
Anders Carlsson10dc0f82010-04-20 23:32:58 +00005971 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
Douglas Gregor1f2023a2009-07-22 18:25:24 +00005972 SourceLocation CtorLoc = ci->getLocation();
5973 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5974 return;
5975 }
Sebastian Redl38fd4d02009-10-25 22:31:45 +00005976 }
Douglas Gregor1f2023a2009-07-22 18:25:24 +00005977
5978 assert(0 && "found no user-declared constructors");
5979 return;
5980 }
5981 break;
5982
5983 case CXXCopyConstructor:
5984 if (RD->hasUserDeclaredCopyConstructor()) {
5985 SourceLocation CtorLoc =
5986 RD->getCopyConstructor(Context, 0)->getLocation();
5987 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5988 return;
5989 }
5990 break;
5991
5992 case CXXCopyAssignment:
5993 if (RD->hasUserDeclaredCopyAssignment()) {
5994 // FIXME: this should use the location of the copy
5995 // assignment, not the type.
5996 SourceLocation TyLoc = RD->getSourceRange().getBegin();
5997 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
5998 return;
5999 }
6000 break;
6001
6002 case CXXDestructor:
6003 if (RD->hasUserDeclaredDestructor()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00006004 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006005 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
6006 return;
6007 }
6008 break;
6009 }
6010
6011 typedef CXXRecordDecl::base_class_iterator base_iter;
6012
6013 // Virtual bases and members inhibit trivial copying/construction,
6014 // but not trivial destruction.
6015 if (member != CXXDestructor) {
6016 // Check for virtual bases. vbases includes indirect virtual bases,
6017 // so we just iterate through the direct bases.
6018 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
6019 if (bi->isVirtual()) {
6020 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
6021 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
6022 return;
6023 }
6024
6025 // Check for virtual methods.
6026 typedef CXXRecordDecl::method_iterator meth_iter;
6027 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
6028 ++mi) {
6029 if (mi->isVirtual()) {
6030 SourceLocation MLoc = mi->getSourceRange().getBegin();
6031 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
6032 return;
6033 }
6034 }
6035 }
Mike Stump1eb44332009-09-09 15:08:12 +00006036
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006037 bool (CXXRecordDecl::*hasTrivial)() const;
6038 switch (member) {
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00006039 case CXXConstructor:
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006040 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
6041 case CXXCopyConstructor:
6042 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
6043 case CXXCopyAssignment:
6044 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
6045 case CXXDestructor:
6046 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
6047 default:
6048 assert(0 && "unexpected special member"); return;
6049 }
6050
6051 // Check for nontrivial bases (and recurse).
6052 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006053 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
Sebastian Redl9994a342009-10-25 17:03:50 +00006054 assert(BaseRT && "Don't know how to handle dependent bases");
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006055 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
6056 if (!(BaseRecTy->*hasTrivial)()) {
6057 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
6058 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
6059 DiagnoseNontrivial(BaseRT, member);
6060 return;
6061 }
6062 }
Mike Stump1eb44332009-09-09 15:08:12 +00006063
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006064 // Check for nontrivial members (and recurse).
6065 typedef RecordDecl::field_iterator field_iter;
6066 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
6067 ++fi) {
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00006068 QualType EltTy = Context.getBaseElementType((*fi)->getType());
Ted Kremenek6217b802009-07-29 21:53:49 +00006069 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006070 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
6071
6072 if (!(EltRD->*hasTrivial)()) {
6073 SourceLocation FLoc = (*fi)->getLocation();
6074 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
6075 DiagnoseNontrivial(EltRT, member);
6076 return;
6077 }
6078 }
6079 }
6080
6081 assert(0 && "found no explanation for non-trivial member");
6082}
6083
Mike Stump1eb44332009-09-09 15:08:12 +00006084/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanian89204a12007-10-01 16:53:59 +00006085/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006086static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00006087TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00006088 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00006089 default: assert(0 && "Unknown visitibility kind");
6090 case tok::objc_private: return ObjCIvarDecl::Private;
6091 case tok::objc_public: return ObjCIvarDecl::Public;
6092 case tok::objc_protected: return ObjCIvarDecl::Protected;
6093 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00006094 }
6095}
6096
Mike Stump1eb44332009-09-09 15:08:12 +00006097/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00006098/// in order to create an IvarDecl object for it.
Chris Lattnerb28317a2009-03-28 19:18:32 +00006099Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00006100 SourceLocation DeclStart,
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00006101 DeclPtrTy IntfDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006102 Declarator &D, ExprTy *BitfieldWidth,
6103 tok::ObjCKeywordKind Visibility) {
Mike Stump1eb44332009-09-09 15:08:12 +00006104
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006105 IdentifierInfo *II = D.getIdentifier();
6106 Expr *BitWidth = (Expr*)BitfieldWidth;
6107 SourceLocation Loc = DeclStart;
6108 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00006109
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006110 // FIXME: Unnamed fields can be handled in various different ways, for
6111 // example, unnamed unions inject all members into the struct namespace!
Mike Stump1eb44332009-09-09 15:08:12 +00006112
John McCallbf1a0282010-06-04 23:28:52 +00006113 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6114 QualType T = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00006115
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006116 if (BitWidth) {
Steve Naroff63359c82009-02-20 17:57:11 +00006117 // 6.7.2.1p3, 6.7.2.1p4
Chris Lattner24793662009-03-05 22:45:59 +00006118 if (VerifyBitField(Loc, II, T, BitWidth)) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00006119 D.setInvalidType();
Chris Lattner24793662009-03-05 22:45:59 +00006120 DeleteExpr(BitWidth);
6121 BitWidth = 0;
6122 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006123 } else {
6124 // Not a bitfield.
Mike Stump1eb44332009-09-09 15:08:12 +00006125
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006126 // validate II.
Mike Stump1eb44332009-09-09 15:08:12 +00006127
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006128 }
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +00006129 if (T->isReferenceType()) {
6130 Diag(Loc, diag::err_ivar_reference_type);
6131 D.setInvalidType();
6132 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006133 // C99 6.7.2.1p8: A member of a structure or union may have any type other
6134 // than a variably modified type.
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +00006135 else if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00006136 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnereaaebc72009-04-25 08:06:05 +00006137 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006138 }
Mike Stump1eb44332009-09-09 15:08:12 +00006139
Ted Kremenekb8db21d2008-07-23 18:04:17 +00006140 // Get the visibility (access control) for this ivar.
Mike Stump1eb44332009-09-09 15:08:12 +00006141 ObjCIvarDecl::AccessControl ac =
Ted Kremenekb8db21d2008-07-23 18:04:17 +00006142 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
6143 : ObjCIvarDecl::None;
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00006144 // Must set ivar's DeclContext to its enclosing interface.
Daniel Dunbara19331f2010-04-02 18:29:09 +00006145 ObjCContainerDecl *EnclosingDecl = IntfDecl.getAs<ObjCContainerDecl>();
6146 ObjCContainerDecl *EnclosingContext;
Mike Stump1eb44332009-09-09 15:08:12 +00006147 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00006148 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
6149 // Case of ivar declared in an implementation. Context is that of its class.
Daniel Dunbara19331f2010-04-02 18:29:09 +00006150 EnclosingContext = IMPDecl->getClassInterface();
6151 assert(EnclosingContext && "Implementation has no class interface!");
Fariborz Jahanian0bd04592010-04-06 22:43:48 +00006152 } else {
6153 if (ObjCCategoryDecl *CDecl =
6154 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
6155 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
6156 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
6157 return DeclPtrTy();
6158 }
6159 }
Daniel Dunbara19331f2010-04-02 18:29:09 +00006160 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +00006161 }
Mike Stump1eb44332009-09-09 15:08:12 +00006162
Ted Kremenekb8db21d2008-07-23 18:04:17 +00006163 // Construct the decl.
Mike Stump1eb44332009-09-09 15:08:12 +00006164 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00006165 EnclosingContext, Loc, II, T,
John McCalla93c9342009-12-07 02:54:59 +00006166 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump1eb44332009-09-09 15:08:12 +00006167
Douglas Gregor72de6672009-01-08 20:45:30 +00006168 if (II) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00006169 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall7d384dd2009-11-18 07:57:50 +00006170 ForRedeclaration);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00006171 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor72de6672009-01-08 20:45:30 +00006172 && !isa<TagDecl>(PrevDecl)) {
6173 Diag(Loc, diag::err_duplicate_member) << II;
6174 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
6175 NewID->setInvalidDecl();
6176 }
6177 }
6178
Ted Kremenekb8db21d2008-07-23 18:04:17 +00006179 // Process attributes attached to the ivar.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006180 ProcessDeclAttributes(S, NewID, D);
Mike Stump1eb44332009-09-09 15:08:12 +00006181
Chris Lattnereaaebc72009-04-25 08:06:05 +00006182 if (D.isInvalidType())
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006183 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00006184
Douglas Gregor72de6672009-01-08 20:45:30 +00006185 if (II) {
6186 // FIXME: When interfaces are DeclContexts, we'll need to add
6187 // these to the interface.
Chris Lattnerb28317a2009-03-28 19:18:32 +00006188 S->AddDecl(DeclPtrTy::make(NewID));
Douglas Gregor72de6672009-01-08 20:45:30 +00006189 IdResolver.AddDecl(NewID);
6190 }
6191
Chris Lattnerb28317a2009-03-28 19:18:32 +00006192 return DeclPtrTy::make(NewID);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006193}
6194
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00006195void Sema::ActOnFields(Scope* S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006196 SourceLocation RecLoc, DeclPtrTy RecDecl,
6197 DeclPtrTy *Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00006198 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00006199 AttributeList *Attr) {
Chris Lattnerb28317a2009-03-28 19:18:32 +00006200 Decl *EnclosingDecl = RecDecl.getAs<Decl>();
Steve Naroff74216642007-09-14 22:20:54 +00006201 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump1eb44332009-09-09 15:08:12 +00006202
Chris Lattner1829a6d2009-02-23 22:00:08 +00006203 // If the decl this is being inserted into is invalid, then it may be a
6204 // redeclaration or some other bogus case. Don't try to add fields to it.
6205 if (EnclosingDecl->isInvalidDecl()) {
6206 // FIXME: Deallocate fields?
6207 return;
6208 }
6209
Mike Stump1eb44332009-09-09 15:08:12 +00006210
Reid Spencer5f016e22007-07-11 17:01:13 +00006211 // Verify that all the fields are okay.
6212 unsigned NumNamedMembers = 0;
6213 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00006214
Chris Lattner1829a6d2009-02-23 22:00:08 +00006215 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00006216 for (unsigned i = 0; i != NumFields; ++i) {
Chris Lattnerb28317a2009-03-28 19:18:32 +00006217 FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00006218
Reid Spencer5f016e22007-07-11 17:01:13 +00006219 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00006220 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00006221
Douglas Gregor72de6672009-01-08 20:45:30 +00006222 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00006223 // Remember all fields written by the user.
6224 RecFields.push_back(FD);
6225 }
Mike Stump1eb44332009-09-09 15:08:12 +00006226
Chris Lattner24793662009-03-05 22:45:59 +00006227 // If the field is already invalid for some reason, don't emit more
6228 // diagnostics about it.
Eli Friedman721e77d2009-12-07 00:22:08 +00006229 if (FD->isInvalidDecl()) {
6230 EnclosingDecl->setInvalidDecl();
Chris Lattner24793662009-03-05 22:45:59 +00006231 continue;
Eli Friedman721e77d2009-12-07 00:22:08 +00006232 }
Mike Stump1eb44332009-09-09 15:08:12 +00006233
Douglas Gregore7450f52009-03-24 19:52:54 +00006234 // C99 6.7.2.1p2:
6235 // A structure or union shall not contain a member with
6236 // incomplete or function type (hence, a structure shall not
6237 // contain an instance of itself, but may contain a pointer to
6238 // an instance of itself), except that the last member of a
6239 // structure with more than one named member may have incomplete
6240 // array type; such a structure (and any union containing,
6241 // possibly recursively, a member that is such a structure)
6242 // shall not be a member of a structure or an element of an
6243 // array.
Chris Lattner02c642e2007-07-31 21:33:24 +00006244 if (FDTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006245 // Field declared as a function.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006246 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006247 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00006248 FD->setInvalidDecl();
6249 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00006250 continue;
Douglas Gregore7450f52009-03-24 19:52:54 +00006251 } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
6252 Record && Record->isStruct()) {
6253 // Flexible array member.
6254 if (NumNamedMembers < 1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006255 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006256 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00006257 FD->setInvalidDecl();
6258 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00006259 continue;
6260 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00006261 if (!FD->getType()->isDependentType() &&
6262 !Context.getBaseElementType(FD->getType())->isPODType()) {
6263 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanian2c0a5402010-05-26 20:46:24 +00006264 << FD->getDeclName() << FD->getType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00006265 FD->setInvalidDecl();
6266 EnclosingDecl->setInvalidDecl();
6267 continue;
6268 }
6269
Reid Spencer5f016e22007-07-11 17:01:13 +00006270 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00006271 if (Record)
6272 Record->setHasFlexibleArrayMember(true);
Douglas Gregore7450f52009-03-24 19:52:54 +00006273 } else if (!FDTy->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006274 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregore7450f52009-03-24 19:52:54 +00006275 diag::err_field_incomplete)) {
6276 // Incomplete type
6277 FD->setInvalidDecl();
6278 EnclosingDecl->setInvalidDecl();
6279 continue;
Ted Kremenek6217b802009-07-29 21:53:49 +00006280 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006281 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
6282 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00006283 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006284 Record->setHasFlexibleArrayMember(true);
6285 } else {
6286 // If this is a struct/class and this is not the last element, reject
6287 // it. Note that GCC supports variable sized arrays in the middle of
6288 // structures.
Douglas Gregore4f3e062009-03-06 23:41:27 +00006289 if (i != NumFields-1)
6290 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattner740782a2009-04-25 18:52:45 +00006291 << FD->getDeclName() << FD->getType();
Douglas Gregore4f3e062009-03-06 23:41:27 +00006292 else {
6293 // We support flexible arrays at the end of structs in
6294 // other structs as an extension.
6295 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
6296 << FD->getDeclName();
6297 if (Record)
6298 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00006299 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006300 }
6301 }
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00006302 if (Record && FDTTy->getDecl()->hasObjectMember())
6303 Record->setHasObjectMember(true);
John McCallc12c5bb2010-05-15 11:32:37 +00006304 } else if (FDTy->isObjCObjectType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006305 /// A field cannot be an Objective-c object
Steve Naroffccef3712009-02-20 22:59:16 +00006306 Diag(FD->getLocation(), diag::err_statically_allocated_object);
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00006307 FD->setInvalidDecl();
6308 EnclosingDecl->setInvalidDecl();
6309 continue;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006310 } else if (getLangOptions().ObjC1 &&
6311 getLangOptions().getGCMode() != LangOptions::NonGC &&
6312 Record &&
6313 (FD->getType()->isObjCObjectPointerType() ||
6314 FD->getType().isObjCGCStrong()))
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00006315 Record->setHasObjectMember(true);
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006316 else if (Context.getAsArrayType(FD->getType())) {
6317 QualType BaseType = Context.getBaseElementType(FD->getType());
6318 if (Record && BaseType->isRecordType() &&
6319 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
6320 Record->setHasObjectMember(true);
6321 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006322 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00006323 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00006324 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00006325 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00006326
Reid Spencer5f016e22007-07-11 17:01:13 +00006327 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00006328 if (Record) {
Douglas Gregor838db382010-02-11 01:19:42 +00006329 Record->completeDefinition();
Chris Lattnere1e79852008-02-06 00:51:33 +00006330 } else {
Jay Foadbeaaccd2009-05-21 09:52:38 +00006331 ObjCIvarDecl **ClsFields =
6332 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00006333 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner38af2de2009-02-20 21:35:13 +00006334 ID->setLocEnd(RBrac);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00006335 // Add ivar's to class's DeclContext.
6336 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
6337 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006338 ID->addDecl(ClsFields[i]);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00006339 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00006340 // Must enforce the rule that ivars in the base classes may not be
6341 // duplicates.
Fariborz Jahanianf914b972010-02-23 23:41:11 +00006342 if (ID->getSuperClass())
6343 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump1eb44332009-09-09 15:08:12 +00006344 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattner1829a6d2009-02-23 22:00:08 +00006345 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006346 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00006347 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
6348 // Ivar declared in @implementation never belongs to the implementation.
6349 // Only it is in implementation's lexical context.
Douglas Gregor8f36aba2009-04-23 03:23:08 +00006350 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00006351 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +00006352 } else if (ObjCCategoryDecl *CDecl =
6353 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +00006354 // case of ivars in class extension; all other cases have been
6355 // reported as errors elsewhere.
6356 // FIXME. Class extension does not have a LocEnd field.
6357 // CDecl->setLocEnd(RBrac);
6358 // Add ivar's to class extension's DeclContext.
6359 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
6360 ClsFields[i]->setLexicalDeclContext(CDecl);
6361 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +00006362 }
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00006363 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00006364 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00006365
6366 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006367 ProcessDeclAttributeList(S, Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00006368}
6369
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006370/// \brief Determine whether the given integral value is representable within
6371/// the given type T.
6372static bool isRepresentableIntegerValue(ASTContext &Context,
6373 llvm::APSInt &Value,
6374 QualType T) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00006375 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregoraf68d4e2010-04-15 15:53:31 +00006376 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006377
6378 if (Value.isUnsigned() || Value.isNonNegative())
6379 return Value.getActiveBits() < BitWidth;
6380
6381 return Value.getMinSignedBits() <= BitWidth;
6382}
6383
6384// \brief Given an integral type, return the next larger integral type
6385// (or a NULL type of no such type exists).
6386static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
6387 // FIXME: Int128/UInt128 support, which also needs to be introduced into
6388 // enum checking below.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00006389 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006390 const unsigned NumTypes = 4;
6391 QualType SignedIntegralTypes[NumTypes] = {
6392 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
6393 };
6394 QualType UnsignedIntegralTypes[NumTypes] = {
6395 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
6396 Context.UnsignedLongLongTy
6397 };
6398
6399 unsigned BitWidth = Context.getTypeSize(T);
6400 QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes
6401 : UnsignedIntegralTypes;
6402 for (unsigned I = 0; I != NumTypes; ++I)
6403 if (Context.getTypeSize(Types[I]) > BitWidth)
6404 return Types[I];
6405
6406 return QualType();
6407}
6408
Douglas Gregor879fd492009-03-17 19:05:46 +00006409EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
6410 EnumConstantDecl *LastEnumConst,
6411 SourceLocation IdLoc,
6412 IdentifierInfo *Id,
6413 ExprArg val) {
6414 Expr *Val = (Expr *)val.get();
6415
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006416 unsigned IntWidth = Context.Target.getIntWidth();
6417 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor879fd492009-03-17 19:05:46 +00006418 QualType EltTy;
Douglas Gregor4912c342009-11-06 00:03:12 +00006419 if (Val) {
Douglas Gregor9b9edd62010-03-02 17:53:14 +00006420 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregor4912c342009-11-06 00:03:12 +00006421 EltTy = Context.DependentTy;
6422 else {
Douglas Gregor4912c342009-11-06 00:03:12 +00006423 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
6424 SourceLocation ExpLoc;
Douglas Gregor9b9edd62010-03-02 17:53:14 +00006425 if (!Val->isValueDependent() &&
6426 VerifyIntegerConstantExpression(Val, &EnumVal)) {
Douglas Gregor4912c342009-11-06 00:03:12 +00006427 Val = 0;
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006428 } else {
6429 if (!getLangOptions().CPlusPlus) {
6430 // C99 6.7.2.2p2:
6431 // The expression that defines the value of an enumeration constant
6432 // shall be an integer constant expression that has a value
6433 // representable as an int.
6434
6435 // Complain if the value is not representable in an int.
6436 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
6437 Diag(IdLoc, diag::ext_enum_value_not_int)
6438 << EnumVal.toString(10) << Val->getSourceRange()
Douglas Gregor19c15252010-02-17 22:40:11 +00006439 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006440 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
6441 // Force the type of the expression to 'int'.
6442 ImpCastExprToType(Val, Context.IntTy, CastExpr::CK_IntegralCast);
6443
6444 if (Val != val.get()) {
6445 val.release();
6446 val = Val;
6447 }
6448 }
6449 }
6450
6451 // C++0x [dcl.enum]p5:
6452 // If the underlying type is not fixed, the type of each enumerator
6453 // is the type of its initializing value:
6454 // - If an initializer is specified for an enumerator, the
6455 // initializing value has the same type as the expression.
Douglas Gregor4912c342009-11-06 00:03:12 +00006456 EltTy = Val->getType();
6457 }
Douglas Gregor879fd492009-03-17 19:05:46 +00006458 }
6459 }
Mike Stump1eb44332009-09-09 15:08:12 +00006460
Douglas Gregor879fd492009-03-17 19:05:46 +00006461 if (!Val) {
Eli Friedmaned0716b2009-12-11 01:34:50 +00006462 if (Enum->isDependentType())
6463 EltTy = Context.DependentTy;
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006464 else if (!LastEnumConst) {
6465 // C++0x [dcl.enum]p5:
6466 // If the underlying type is not fixed, the type of each enumerator
6467 // is the type of its initializing value:
6468 // - If no initializer is specified for the first enumerator, the
6469 // initializing value has an unspecified integral type.
6470 //
6471 // GCC uses 'int' for its unspecified integral type, as does
6472 // C99 6.7.2.2p3.
6473 EltTy = Context.IntTy;
6474 } else {
Douglas Gregor879fd492009-03-17 19:05:46 +00006475 // Assign the last value + 1.
6476 EnumVal = LastEnumConst->getInitVal();
6477 ++EnumVal;
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006478 EltTy = LastEnumConst->getType();
Douglas Gregor879fd492009-03-17 19:05:46 +00006479
6480 // Check for overflow on increment.
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006481 if (EnumVal < LastEnumConst->getInitVal()) {
6482 // C++0x [dcl.enum]p5:
6483 // If the underlying type is not fixed, the type of each enumerator
6484 // is the type of its initializing value:
6485 //
6486 // - Otherwise the type of the initializing value is the same as
6487 // the type of the initializing value of the preceding enumerator
6488 // unless the incremented value is not representable in that type,
6489 // in which case the type is an unspecified integral type
6490 // sufficient to contain the incremented value. If no such type
6491 // exists, the program is ill-formed.
6492 QualType T = getNextLargerIntegralType(Context, EltTy);
6493 if (T.isNull()) {
6494 // There is no integral type larger enough to represent this
6495 // value. Complain, then allow the value to wrap around.
6496 EnumVal = LastEnumConst->getInitVal();
6497 EnumVal.zext(EnumVal.getBitWidth() * 2);
6498 Diag(IdLoc, diag::warn_enumerator_too_large)
6499 << EnumVal.toString(10);
6500 } else {
6501 EltTy = T;
6502 }
6503
6504 // Retrieve the last enumerator's value, extent that type to the
6505 // type that is supposed to be large enough to represent the incremented
6506 // value, then increment.
6507 EnumVal = LastEnumConst->getInitVal();
6508 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
Douglas Gregoraf68d4e2010-04-15 15:53:31 +00006509 EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006510 ++EnumVal;
6511
6512 // If we're not in C++, diagnose the overflow of enumerator values,
6513 // which in C99 means that the enumerator value is not representable in
6514 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
6515 // permits enumerator values that are representable in some larger
6516 // integral type.
6517 if (!getLangOptions().CPlusPlus && !T.isNull())
6518 Diag(IdLoc, diag::warn_enum_value_overflow);
6519 } else if (!getLangOptions().CPlusPlus &&
6520 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
6521 // Enforce C99 6.7.2.2p2 even when we compute the next value.
6522 Diag(IdLoc, diag::ext_enum_value_not_int)
6523 << EnumVal.toString(10) << 1;
6524 }
Douglas Gregor879fd492009-03-17 19:05:46 +00006525 }
6526 }
Mike Stump1eb44332009-09-09 15:08:12 +00006527
Douglas Gregor9b9edd62010-03-02 17:53:14 +00006528 if (!EltTy->isDependentType()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006529 // Make the enumerator value match the signedness and size of the
6530 // enumerator's type.
Douglas Gregoraf68d4e2010-04-15 15:53:31 +00006531 EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006532 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
6533 }
Douglas Gregor4912c342009-11-06 00:03:12 +00006534
Douglas Gregor879fd492009-03-17 19:05:46 +00006535 val.release();
6536 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump1eb44332009-09-09 15:08:12 +00006537 Val, EnumVal);
Douglas Gregor879fd492009-03-17 19:05:46 +00006538}
6539
6540
Chris Lattnerb28317a2009-03-28 19:18:32 +00006541Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
6542 DeclPtrTy lastEnumConst,
6543 SourceLocation IdLoc,
6544 IdentifierInfo *Id,
6545 SourceLocation EqualLoc, ExprTy *val) {
6546 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00006547 EnumConstantDecl *LastEnumConst =
Chris Lattnerb28317a2009-03-28 19:18:32 +00006548 cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00006549 Expr *Val = static_cast<Expr*>(val);
6550
Chris Lattner31e05722007-08-26 06:24:45 +00006551 // The scope passed in may not be a decl scope. Zip up the scope tree until
6552 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00006553 S = getNonFieldDeclScope(S);
Mike Stump1eb44332009-09-09 15:08:12 +00006554
Reid Spencer5f016e22007-07-11 17:01:13 +00006555 // Verify that there isn't already something declared with this name in this
6556 // scope.
Douglas Gregorc83c6872010-04-15 22:33:43 +00006557 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregore39fe722010-01-19 06:06:57 +00006558 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +00006559 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00006560 // Maybe we will complain about the shadowed template parameter.
6561 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
6562 // Just pretend that we didn't see the previous declaration.
6563 PrevDecl = 0;
6564 }
6565
6566 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00006567 // When in C++, we may get a TagDecl with the same name; in this case the
6568 // enum constant will 'hide' the tag.
6569 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
6570 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00006571 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006572 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00006573 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00006574 else
Chris Lattner3c73c412008-11-19 08:23:25 +00006575 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00006576 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00006577 return DeclPtrTy();
Reid Spencer5f016e22007-07-11 17:01:13 +00006578 }
6579 }
6580
Douglas Gregor879fd492009-03-17 19:05:46 +00006581 EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
6582 IdLoc, Id, Owned(Val));
Chris Lattner421a23d2007-08-27 21:16:18 +00006583
Reid Spencer5f016e22007-07-11 17:01:13 +00006584 // Register this decl in the current scope stack.
John McCall92f88312010-01-23 00:46:32 +00006585 if (New) {
6586 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor879fd492009-03-17 19:05:46 +00006587 PushOnScopeChains(New, S);
John McCall92f88312010-01-23 00:46:32 +00006588 }
Douglas Gregor45579f52008-12-17 02:04:30 +00006589
Chris Lattnerb28317a2009-03-28 19:18:32 +00006590 return DeclPtrTy::make(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00006591}
6592
Mike Stumpc6e35aa2009-05-16 07:06:02 +00006593void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
6594 SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006595 DeclPtrTy *Elements, unsigned NumElements,
6596 Scope *S, AttributeList *Attr) {
Chris Lattnerb28317a2009-03-28 19:18:32 +00006597 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
Douglas Gregor074149e2009-01-05 19:45:36 +00006598 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006599
6600 if (Attr)
6601 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump1eb44332009-09-09 15:08:12 +00006602
Eli Friedmaned0716b2009-12-11 01:34:50 +00006603 if (Enum->isDependentType()) {
6604 for (unsigned i = 0; i != NumElements; ++i) {
6605 EnumConstantDecl *ECD =
6606 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6607 if (!ECD) continue;
6608
6609 ECD->setType(EnumType);
6610 }
6611
John McCall1b5a6182010-05-06 08:49:23 +00006612 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmaned0716b2009-12-11 01:34:50 +00006613 return;
6614 }
6615
Chris Lattnere37f0be2007-08-28 05:10:31 +00006616 // TODO: If the result value doesn't fit in an int, it must be a long or long
6617 // long value. ISO C does not support this, but GCC does as an extension,
6618 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00006619 unsigned IntWidth = Context.Target.getIntWidth();
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006620 unsigned CharWidth = Context.Target.getCharWidth();
6621 unsigned ShortWidth = Context.Target.getShortWidth();
Mike Stump1eb44332009-09-09 15:08:12 +00006622
Chris Lattnerac609682007-08-28 06:15:15 +00006623 // Verify that all the values are okay, compute the size of the values, and
6624 // reverse the list.
6625 unsigned NumNegativeBits = 0;
6626 unsigned NumPositiveBits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006627
Chris Lattnerac609682007-08-28 06:15:15 +00006628 // Keep track of whether all elements have type int.
6629 bool AllElementsInt = true;
Mike Stump1eb44332009-09-09 15:08:12 +00006630
Reid Spencer5f016e22007-07-11 17:01:13 +00006631 for (unsigned i = 0; i != NumElements; ++i) {
6632 EnumConstantDecl *ECD =
Chris Lattnerb28317a2009-03-28 19:18:32 +00006633 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00006634 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump1eb44332009-09-09 15:08:12 +00006635
Chris Lattner211a30e2007-08-28 05:27:00 +00006636 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump1eb44332009-09-09 15:08:12 +00006637
Chris Lattnerac609682007-08-28 06:15:15 +00006638 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00006639 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00006640 NumPositiveBits = std::max(NumPositiveBits,
6641 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00006642 else
Chris Lattner21dd8212008-01-14 21:47:29 +00006643 NumNegativeBits = std::max(NumNegativeBits,
6644 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00006645
Chris Lattnerac609682007-08-28 06:15:15 +00006646 // Keep track of whether every enum element has type int (very commmon).
6647 if (AllElementsInt)
Mike Stump1eb44332009-09-09 15:08:12 +00006648 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006649 }
Mike Stump1eb44332009-09-09 15:08:12 +00006650
Chris Lattnerac609682007-08-28 06:15:15 +00006651 // Figure out the type that should be used for this enum.
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006652 // FIXME: Support -fshort-enums.
Chris Lattnerac609682007-08-28 06:15:15 +00006653 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006654 unsigned BestWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006655
John McCall842aef82009-12-09 09:09:27 +00006656 // C++0x N3000 [conv.prom]p3:
6657 // An rvalue of an unscoped enumeration type whose underlying
6658 // type is not fixed can be converted to an rvalue of the first
6659 // of the following types that can represent all the values of
6660 // the enumeration: int, unsigned int, long int, unsigned long
6661 // int, long long int, or unsigned long long int.
6662 // C99 6.4.4.3p2:
6663 // An identifier declared as an enumeration constant has type int.
6664 // The C99 rule is modified by a gcc extension
6665 QualType BestPromotionType;
6666
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006667 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
6668
Chris Lattnerac609682007-08-28 06:15:15 +00006669 if (NumNegativeBits) {
Mike Stump1eb44332009-09-09 15:08:12 +00006670 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerac609682007-08-28 06:15:15 +00006671 // int/long/longlong) that fits.
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006672 // If it's packed, check also if it fits a char or a short.
6673 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall842aef82009-12-09 09:09:27 +00006674 BestType = Context.SignedCharTy;
6675 BestWidth = CharWidth;
Mike Stump1eb44332009-09-09 15:08:12 +00006676 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006677 NumPositiveBits < ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +00006678 BestType = Context.ShortTy;
6679 BestWidth = ShortWidth;
6680 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00006681 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006682 BestWidth = IntWidth;
6683 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00006684 BestWidth = Context.Target.getLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +00006685
John McCall842aef82009-12-09 09:09:27 +00006686 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00006687 BestType = Context.LongTy;
John McCall842aef82009-12-09 09:09:27 +00006688 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00006689 BestWidth = Context.Target.getLongLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +00006690
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006691 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00006692 Diag(Enum->getLocation(), diag::warn_enum_too_large);
6693 BestType = Context.LongLongTy;
6694 }
6695 }
John McCall842aef82009-12-09 09:09:27 +00006696 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerac609682007-08-28 06:15:15 +00006697 } else {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00006698 // If there is no negative value, figure out the smallest type that fits
6699 // all of the enumerator values.
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006700 // If it's packed, check also if it fits a char or a short.
6701 if (Packed && NumPositiveBits <= CharWidth) {
John McCall842aef82009-12-09 09:09:27 +00006702 BestType = Context.UnsignedCharTy;
6703 BestPromotionType = Context.IntTy;
6704 BestWidth = CharWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006705 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +00006706 BestType = Context.UnsignedShortTy;
6707 BestPromotionType = Context.IntTy;
6708 BestWidth = ShortWidth;
6709 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00006710 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006711 BestWidth = IntWidth;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00006712 BestPromotionType
6713 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6714 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006715 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00006716 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00006717 BestType = Context.UnsignedLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00006718 BestPromotionType
6719 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6720 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00006721 } else {
6722 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006723 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00006724 "How could an initializer get larger than ULL?");
6725 BestType = Context.UnsignedLongLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00006726 BestPromotionType
6727 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6728 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerac609682007-08-28 06:15:15 +00006729 }
6730 }
Mike Stump1eb44332009-09-09 15:08:12 +00006731
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006732 // Loop over all of the enumerator constants, changing their types to match
6733 // the type of the enum if needed.
6734 for (unsigned i = 0; i != NumElements; ++i) {
6735 EnumConstantDecl *ECD =
Chris Lattnerb28317a2009-03-28 19:18:32 +00006736 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006737 if (!ECD) continue; // Already issued a diagnostic.
6738
6739 // Standard C says the enumerators have int type, but we allow, as an
6740 // extension, the enumerators to be larger than int size. If each
6741 // enumerator value fits in an int, type it as an int, otherwise type it the
6742 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
6743 // that X has type 'int', not 'unsigned'.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006744
6745 // Determine whether the value fits into an int.
6746 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006747
6748 // If it fits into an integer type, force it. Otherwise force it to match
6749 // the enum decl type.
6750 QualType NewTy;
6751 unsigned NewWidth;
6752 bool NewSign;
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006753 if (!getLangOptions().CPlusPlus &&
6754 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006755 NewTy = Context.IntTy;
6756 NewWidth = IntWidth;
6757 NewSign = true;
6758 } else if (ECD->getType() == BestType) {
6759 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006760 if (getLangOptions().CPlusPlus)
6761 // C++ [dcl.enum]p4: Following the closing brace of an
6762 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +00006763 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006764 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006765 continue;
6766 } else {
6767 NewTy = BestType;
6768 NewWidth = BestWidth;
6769 NewSign = BestType->isSignedIntegerType();
6770 }
6771
6772 // Adjust the APSInt value.
6773 InitVal.extOrTrunc(NewWidth);
6774 InitVal.setIsSigned(NewSign);
6775 ECD->setInitVal(InitVal);
Mike Stump1eb44332009-09-09 15:08:12 +00006776
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006777 // Adjust the Expr initializer and type.
Chris Lattner13fd4162009-01-15 19:19:42 +00006778 if (ECD->getInitExpr())
Mike Stump1eb44332009-09-09 15:08:12 +00006779 ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
Eli Friedman73c39ab2009-10-20 08:27:19 +00006780 CastExpr::CK_IntegralCast,
Mike Stump1eb44332009-09-09 15:08:12 +00006781 ECD->getInitExpr(),
Anders Carlssonf1b48b72010-04-24 16:57:13 +00006782 CXXBaseSpecifierArray(),
Sebastian Redl906082e2010-07-20 04:20:21 +00006783 ImplicitCastExpr::RValue));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006784 if (getLangOptions().CPlusPlus)
6785 // C++ [dcl.enum]p4: Following the closing brace of an
6786 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +00006787 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006788 ECD->setType(EnumType);
6789 else
6790 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006791 }
Mike Stump1eb44332009-09-09 15:08:12 +00006792
John McCall1b5a6182010-05-06 08:49:23 +00006793 Enum->completeDefinition(BestType, BestPromotionType,
6794 NumPositiveBits, NumNegativeBits);
Reid Spencer5f016e22007-07-11 17:01:13 +00006795}
6796
Chris Lattnerb28317a2009-03-28 19:18:32 +00006797Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
6798 ExprArg expr) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00006799 StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
Sebastian Redl798d1192008-12-13 16:23:55 +00006800
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00006801 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
6802 Loc, AsmString);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006803 CurContext->addDecl(New);
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00006804 return DeclPtrTy::make(New);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00006805}
Eli Friedmanc49f19b2009-06-05 02:44:36 +00006806
6807void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
6808 SourceLocation PragmaLoc,
6809 SourceLocation NameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00006810 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedmanc49f19b2009-06-05 02:44:36 +00006811
Eli Friedmanc49f19b2009-06-05 02:44:36 +00006812 if (PrevDecl) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006813 PrevDecl->addAttr(::new (Context) WeakAttr());
Ryan Flynne25ff832009-07-30 03:15:39 +00006814 } else {
6815 (void)WeakUndeclaredIdentifiers.insert(
6816 std::pair<IdentifierInfo*,WeakInfo>
6817 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedmanc49f19b2009-06-05 02:44:36 +00006818 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +00006819}
6820
6821void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
6822 IdentifierInfo* AliasName,
6823 SourceLocation PragmaLoc,
6824 SourceLocation NameLoc,
6825 SourceLocation AliasNameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00006826 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
6827 LookupOrdinaryName);
Ryan Flynne25ff832009-07-30 03:15:39 +00006828 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedmanc49f19b2009-06-05 02:44:36 +00006829
Eli Friedmanc49f19b2009-06-05 02:44:36 +00006830 if (PrevDecl) {
Ryan Flynne25ff832009-07-30 03:15:39 +00006831 if (!PrevDecl->hasAttr<AliasAttr>())
6832 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynn7b1fdbd2009-07-31 02:52:19 +00006833 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynne25ff832009-07-30 03:15:39 +00006834 } else {
6835 (void)WeakUndeclaredIdentifiers.insert(
6836 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedmanc49f19b2009-06-05 02:44:36 +00006837 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +00006838}