blob: 4a7be55366a992686491a8c035571a8073563d28 [file] [log] [blame]
Chris Lattner697e5d62006-11-09 06:32:27 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner697e5d62006-11-09 06:32:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCallcc14d1f2010-08-24 08:50:51 +000017#include "clang/Sema/CXXFieldCollector.h"
18#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Douglas Gregor844cb502011-03-01 18:12:44 +000020#include "TypeLocBuilder.h"
Anders Carlsson7a241ba2008-07-03 04:20:39 +000021#include "clang/AST/APValue.h"
Chris Lattner622c1932008-02-06 00:51:33 +000022#include "clang/AST/ASTConsumer.h"
Chris Lattner5c5fbcc2006-12-03 08:41:30 +000023#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
John McCall28a0cf72010-08-25 07:42:41 +000025#include "clang/AST/DeclCXX.h"
John McCallde6836a2010-08-24 07:21:54 +000026#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000027#include "clang/AST/DeclTemplate.h"
Chandler Carruth33bf3e72011-03-27 09:46:56 +000028#include "clang/AST/EvaluatedExprVisitor.h"
Chris Lattner2c6fcf52008-06-26 18:38:35 +000029#include "clang/AST/ExprCXX.h"
Sebastian Redla7b98a72009-04-26 20:35:05 +000030#include "clang/AST/StmtCXX.h"
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000031#include "clang/AST/CharUnits.h"
John McCall8b0666c2010-08-20 18:27:03 +000032#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor15e56022009-10-13 23:27:22 +000034#include "clang/Parse/ParseDiagnostic.h"
Anders Carlssond624e162009-08-26 23:45:07 +000035#include "clang/Basic/PartialDiagnostic.h"
Steve Naroffe101f952008-01-30 23:46:05 +000036#include "clang/Basic/SourceManager.h"
Anders Carlssond624e162009-08-26 23:45:07 +000037#include "clang/Basic/TargetInfo.h"
Steve Naroffe101f952008-01-30 23:46:05 +000038// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner622c1932008-02-06 00:51:33 +000039#include "clang/Lex/Preprocessor.h"
Mike Stump11289f42009-09-09 15:08:12 +000040#include "clang/Lex/HeaderSearch.h"
Douglas Gregor08142532011-08-26 23:56:07 +000041#include "clang/Lex/ModuleLoader.h"
John McCall0e21fcc2009-12-24 09:58:38 +000042#include "llvm/ADT/Triple.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000043#include <algorithm>
Douglas Gregor56fbc372009-09-28 21:14:19 +000044#include <cstring>
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000045#include <functional>
Chris Lattner697e5d62006-11-09 06:32:27 +000046using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000047using namespace sema;
Chris Lattner697e5d62006-11-09 06:32:27 +000048
Richard Smithcd1c0552011-07-01 19:46:12 +000049Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
50 if (OwnedType) {
51 Decl *Group[2] = { OwnedType, Ptr };
52 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
53 }
54
John McCall48871652010-08-21 09:40:31 +000055 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner5bbb3c82009-03-29 16:50:03 +000056}
57
Douglas Gregorec6e1892009-02-04 19:16:12 +000058/// \brief If the identifier refers to a type name within this scope,
59/// return the declaration of that type.
60///
61/// This routine performs ordinary name lookup of the identifier II
62/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor9817f4a2009-02-09 15:09:02 +000063/// determine whether the name refers to a type. If so, returns an
64/// opaque pointer (actually a QualType) corresponding to that
65/// type. Otherwise, returns NULL.
Douglas Gregorec6e1892009-02-04 19:16:12 +000066///
67/// If name lookup results in an ambiguity, this routine will complain
68/// and then return NULL.
John McCallba7bf592010-08-24 05:47:05 +000069ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
70 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian87967422011-02-08 18:05:59 +000071 bool isClassName, bool HasTrailingDot,
Douglas Gregor844cb502011-03-01 18:12:44 +000072 ParsedType ObjectTypePtr,
73 bool WantNontrivialTypeSourceInfo) {
Douglas Gregora25d65d2009-11-20 22:03:38 +000074 // Determine where we will perform name lookup.
75 DeclContext *LookupCtx = 0;
76 if (ObjectTypePtr) {
John McCallba7bf592010-08-24 05:47:05 +000077 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregora25d65d2009-11-20 22:03:38 +000078 if (ObjectType->isRecordType())
79 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +000080 } else if (SS && SS->isNotEmpty()) {
Douglas Gregora25d65d2009-11-20 22:03:38 +000081 LookupCtx = computeDeclContext(*SS, false);
82
83 if (!LookupCtx) {
84 if (isDependentScopeSpecifier(*SS)) {
85 // C++ [temp.res]p3:
86 // A qualified-id that refers to a type and in which the
87 // nested-name-specifier depends on a template-parameter (14.6.2)
88 // shall be prefixed by the keyword typename to indicate that the
89 // qualified-id denotes a type, forming an
90 // elaborated-type-specifier (7.1.5.3).
91 //
92 // We therefore do not perform any name lookup if the result would
93 // refer to a member of an unknown specialization.
94 if (!isClassName)
John McCallba7bf592010-08-24 05:47:05 +000095 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +000096
John McCallc392f372010-06-11 00:33:02 +000097 // We know from the grammar that this name refers to a type,
98 // so build a dependent node to describe the type.
Douglas Gregor844cb502011-03-01 18:12:44 +000099 if (WantNontrivialTypeSourceInfo)
100 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
101
102 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
John McCallba7bf592010-08-24 05:47:05 +0000103 QualType T =
Douglas Gregor844cb502011-03-01 18:12:44 +0000104 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000105 II, NameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +0000106
107 return ParsedType::make(T);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000108 }
109
John McCallba7bf592010-08-24 05:47:05 +0000110 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000111 }
112
John McCall0b66eb32010-05-01 00:40:08 +0000113 if (!LookupCtx->isDependentContext() &&
114 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallba7bf592010-08-24 05:47:05 +0000115 return ParsedType();
Douglas Gregor5e0962f2009-08-26 18:27:52 +0000116 }
Eli Friedman9025ec22009-12-21 01:42:38 +0000117
118 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
119 // lookup for class-names.
120 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
121 LookupOrdinaryName;
122 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000123 if (LookupCtx) {
124 // Perform "qualified" name lookup into the declaration context we
125 // computed, which is either the type of the base of a member access
126 // expression or the declaration context associated with a prior
127 // nested-name-specifier.
128 LookupQualifiedName(Result, LookupCtx);
Douglas Gregorc9f9b862009-05-11 19:58:34 +0000129
Douglas Gregora25d65d2009-11-20 22:03:38 +0000130 if (ObjectTypePtr && Result.empty()) {
131 // C++ [basic.lookup.classref]p3:
132 // If the unqualified-id is ~type-name, the type-name is looked up
133 // in the context of the entire postfix-expression. If the type T of
134 // the object expression is of a class type C, the type-name is also
135 // looked up in the scope of class C. At least one of the lookups shall
136 // find a name that refers to (possibly cv-qualified) T.
137 LookupName(Result, S);
138 }
139 } else {
140 // Perform unqualified name lookup.
141 LookupName(Result, S);
142 }
143
Chris Lattnera3778332009-02-16 22:07:16 +0000144 NamedDecl *IIDecl = 0;
John McCall27b18f82009-11-17 02:14:36 +0000145 switch (Result.getResultKind()) {
Chris Lattnera3778332009-02-16 22:07:16 +0000146 case LookupResult::NotFound:
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000147 case LookupResult::NotFoundInCurrentInstantiation:
Chris Lattnera3778332009-02-16 22:07:16 +0000148 case LookupResult::FoundOverloaded:
John McCalle61f2ba2009-11-18 02:36:19 +0000149 case LookupResult::FoundUnresolvedValue:
John McCall58cc69d2010-01-27 01:50:18 +0000150 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000151 return ParsedType();
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000152
Chris Lattnere40853a2009-10-25 22:09:09 +0000153 case LookupResult::Ambiguous:
John McCall6538c932009-10-10 05:48:19 +0000154 // Recover from type-hiding ambiguities by hiding the type. We'll
155 // do the lookup again when looking for an object, and we can
156 // diagnose the error then. If we don't do this, then the error
157 // about hiding the type will be immediately followed by an error
158 // that only makes sense if the identifier was treated like a type.
John McCall27b18f82009-11-17 02:14:36 +0000159 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
160 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000161 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000162 }
John McCall6538c932009-10-10 05:48:19 +0000163
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000164 // Look to see if we have a type anywhere in the list of results.
165 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
166 Res != ResEnd; ++Res) {
167 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump11289f42009-09-09 15:08:12 +0000168 if (!IIDecl ||
169 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor712a3512009-04-13 15:14:38 +0000170 IIDecl->getLocation().getRawEncoding())
171 IIDecl = *Res;
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000172 }
173 }
174
175 if (!IIDecl) {
176 // None of the entities we found is a type, so there is no way
177 // to even assume that the result is a type. In this case, don't
178 // complain about the ambiguity. The parser will either try to
179 // perform this lookup again (e.g., as an object name), which
180 // will produce the ambiguity, or will complain that it expected
181 // a type name.
John McCall27b18f82009-11-17 02:14:36 +0000182 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000183 return ParsedType();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000184 }
185
186 // We found a type within the ambiguous lookup; diagnose the
187 // ambiguity and then return that type. This might be the right
188 // answer, or it might not be, but it suppresses any attempt to
189 // perform the name lookup again.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000190 break;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000191
Chris Lattnera3778332009-02-16 22:07:16 +0000192 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +0000193 IIDecl = Result.getFoundDecl();
Chris Lattnera3778332009-02-16 22:07:16 +0000194 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000195 }
196
Chris Lattner17e15f12009-10-25 17:16:46 +0000197 assert(IIDecl && "Didn't find decl");
John McCall28a6aea2009-11-04 02:18:39 +0000198
Chris Lattner17e15f12009-10-25 17:16:46 +0000199 QualType T;
200 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall28a6aea2009-11-04 02:18:39 +0000201 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCall27b18f82009-11-17 02:14:36 +0000202
Chris Lattner17e15f12009-10-25 17:16:46 +0000203 if (T.isNull())
204 T = Context.getTypeDeclType(TD);
205
Douglas Gregor844cb502011-03-01 18:12:44 +0000206 if (SS && SS->isNotEmpty()) {
207 if (WantNontrivialTypeSourceInfo) {
208 // Construct a type with type-source information.
209 TypeLocBuilder Builder;
210 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
211
212 T = getElaboratedType(ETK_None, *SS, T);
213 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
214 ElabTL.setKeywordLoc(SourceLocation());
215 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
216 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
217 } else {
218 T = getElaboratedType(ETK_None, *SS, T);
219 }
220 }
Chris Lattner17e15f12009-10-25 17:16:46 +0000221 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian08891f52011-03-08 19:12:46 +0000222 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian87967422011-02-08 18:05:59 +0000223 if (!HasTrailingDot)
224 T = Context.getObjCInterfaceType(IDecl);
225 }
226
227 if (T.isNull()) {
John McCall27b18f82009-11-17 02:14:36 +0000228 // If it's not plausibly a type, suppress diagnostics.
229 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000230 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000231 }
John McCallba7bf592010-08-24 05:47:05 +0000232 return ParsedType::make(T);
Chris Lattnere168f762006-11-10 05:29:30 +0000233}
234
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000235/// isTagName() - This method is called *for error recovery purposes only*
236/// to determine if the specified name is a valid tag name ("struct foo"). If
237/// so, this returns the TST for the tag corresponding to it (TST_enum,
238/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
239/// where the user forgot to specify the tag.
240DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
241 // Do a tag name lookup in this scope.
John McCall27b18f82009-11-17 02:14:36 +0000242 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
243 LookupName(R, S, false);
244 R.suppressDiagnostics();
245 if (R.getResultKind() == LookupResult::Found)
John McCall67c00872009-12-02 08:25:40 +0000246 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000247 switch (TD->getTagKind()) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000248 default: return DeclSpec::TST_unspecified;
249 case TTK_Struct: return DeclSpec::TST_struct;
250 case TTK_Union: return DeclSpec::TST_union;
251 case TTK_Class: return DeclSpec::TST_class;
252 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000253 }
254 }
Mike Stump11289f42009-09-09 15:08:12 +0000255
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000256 return DeclSpec::TST_unspecified;
257}
258
Francois Pichet48c946e2011-04-13 02:38:49 +0000259/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
260/// if a CXXScopeSpec's type is equal to the type of one of the base classes
261/// then downgrade the missing typename error to a warning.
262/// This is needed for MSVC compatibility; Example:
263/// @code
264/// template<class T> class A {
265/// public:
266/// typedef int TYPE;
267/// };
268/// template<class T> class B : public A<T> {
269/// public:
270/// A<T>::TYPE a; // no typename required because A<T> is a base class.
271/// };
272/// @endcode
273bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS) {
274 if (CurContext->isRecord()) {
Francois Pichetefc283c2011-04-13 02:44:57 +0000275 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet48c946e2011-04-13 02:38:49 +0000276
277 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
278 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
279 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
280 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
281 return true;
282 }
283 return false;
284}
285
Douglas Gregor15e56022009-10-13 23:27:22 +0000286bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
287 SourceLocation IILoc,
288 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000289 CXXScopeSpec *SS,
John McCallba7bf592010-08-24 05:47:05 +0000290 ParsedType &SuggestedType) {
Douglas Gregor15e56022009-10-13 23:27:22 +0000291 // We don't have anything to suggest (yet).
John McCallba7bf592010-08-24 05:47:05 +0000292 SuggestedType = ParsedType();
Douglas Gregor15e56022009-10-13 23:27:22 +0000293
Douglas Gregor2d435302009-12-30 17:04:44 +0000294 // There may have been a typo in the name of the type. Look up typo
295 // results, in case we have something that we can suggest.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000296 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc),
297 LookupOrdinaryName, S, SS, NULL,
298 false, CTC_Type)) {
299 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
300 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
Douglas Gregor2d435302009-12-30 17:04:44 +0000301
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000302 if (Corrected.isKeyword()) {
303 // We corrected to a keyword.
304 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
305 Diag(IILoc, diag::err_unknown_typename_suggest)
306 << &II << CorrectedQuotedStr;
307 return true;
308 } else {
309 NamedDecl *Result = Corrected.getCorrectionDecl();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000310 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
311 !Result->isInvalidDecl()) {
312 // We found a similarly-named type or interface; suggest that.
313 if (!SS || !SS->isSet())
314 Diag(IILoc, diag::err_unknown_typename_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000315 << &II << CorrectedQuotedStr
316 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000317 else if (DeclContext *DC = computeDeclContext(*SS, false))
318 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000319 << &II << DC << CorrectedQuotedStr << SS->getRange()
320 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000321 else
322 llvm_unreachable("could not have corrected a typo here");
Douglas Gregor2d435302009-12-30 17:04:44 +0000323
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000324 Diag(Result->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000325 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000326
Douglas Gregor844cb502011-03-01 18:12:44 +0000327 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
328 false, false, ParsedType(),
329 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000330 return true;
331 }
Douglas Gregor2d435302009-12-30 17:04:44 +0000332 }
333 }
334
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000335 if (getLangOptions().CPlusPlus) {
336 // See if II is a class template that the user forgot to pass arguments to.
337 UnqualifiedId Name;
338 Name.setIdentifier(&II, IILoc);
339 CXXScopeSpec EmptySS;
340 TemplateTy TemplateResult;
Douglas Gregor786123d2010-05-21 23:18:07 +0000341 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000342 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000343 Name, ParsedType(), true, TemplateResult,
Douglas Gregor786123d2010-05-21 23:18:07 +0000344 MemberOfUnknownSpecialization) == TNK_Type_template) {
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000345 TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
346 Diag(IILoc, diag::err_template_missing_args) << TplName;
347 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
348 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
349 << TplDecl->getTemplateParameters()->getSourceRange();
350 }
351 return true;
352 }
353 }
354
Douglas Gregor15e56022009-10-13 23:27:22 +0000355 // FIXME: Should we move the logic that tries to recover from a missing tag
356 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
357
Douglas Gregor2d435302009-12-30 17:04:44 +0000358 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Douglas Gregor15e56022009-10-13 23:27:22 +0000359 Diag(IILoc, diag::err_unknown_typename) << &II;
360 else if (DeclContext *DC = computeDeclContext(*SS, false))
361 Diag(IILoc, diag::err_typename_nested_not_found)
362 << &II << DC << SS->getRange();
363 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000364 unsigned DiagID = diag::err_typename_missing;
365 if (getLangOptions().Microsoft && isMicrosoftMissingTypename(SS))
Francois Pichet93921652011-04-22 08:25:24 +0000366 DiagID = diag::warn_typename_missing;
Francois Pichet48c946e2011-04-13 02:38:49 +0000367
368 Diag(SS->getRange().getBegin(), DiagID)
Daniel Dunbar07d07852009-10-18 21:17:35 +0000369 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000370 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000371 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Douglas Gregorf7d77712010-06-16 22:31:08 +0000372 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc).get();
Douglas Gregor15e56022009-10-13 23:27:22 +0000373 } else {
374 assert(SS && SS->isInvalid() &&
375 "Invalid scope specifier has already been diagnosed");
376 }
377
378 return true;
379}
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000380
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000381/// \brief Determine whether the given result set contains either a type name
382/// or
383static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
384 bool CheckTemplate = R.getSema().getLangOptions().CPlusPlus &&
385 NextToken.is(tok::less);
386
387 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
388 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
389 return true;
390
391 if (CheckTemplate && isa<TemplateDecl>(*I))
392 return true;
393 }
394
395 return false;
396}
397
398Sema::NameClassification Sema::ClassifyName(Scope *S,
399 CXXScopeSpec &SS,
400 IdentifierInfo *&Name,
401 SourceLocation NameLoc,
402 const Token &NextToken) {
403 DeclarationNameInfo NameInfo(Name, NameLoc);
404 ObjCMethodDecl *CurMethod = getCurMethodDecl();
405
406 if (NextToken.is(tok::coloncolon)) {
407 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
408 QualType(), false, SS, 0, false);
409
410 }
411
412 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
413 LookupParsedName(Result, S, &SS, !CurMethod);
414
415 // Perform lookup for Objective-C instance variables (including automatically
416 // synthesized instance variables), if we're in an Objective-C method.
417 // FIXME: This lookup really, really needs to be folded in to the normal
418 // unqualified lookup mechanism.
419 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
420 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorb90f5182011-04-25 15:05:41 +0000421 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000422 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000423 }
424
425 bool SecondTry = false;
426 bool IsFilteredTemplateName = false;
427
428Corrected:
429 switch (Result.getResultKind()) {
430 case LookupResult::NotFound:
431 // If an unqualified-id is followed by a '(', then we have a function
432 // call.
433 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
434 // In C++, this is an ADL-only call.
435 // FIXME: Reference?
436 if (getLangOptions().CPlusPlus)
437 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
438
439 // C90 6.3.2.2:
440 // If the expression that precedes the parenthesized argument list in a
441 // function call consists solely of an identifier, and if no
442 // declaration is visible for this identifier, the identifier is
443 // implicitly declared exactly as if, in the innermost block containing
444 // the function call, the declaration
445 //
446 // extern int identifier ();
447 //
448 // appeared.
449 //
450 // We also allow this in C99 as an extension.
451 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
452 Result.addDecl(D);
453 Result.resolveKind();
454 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
455 }
456 }
457
458 // In C, we first see whether there is a tag type by the same name, in
459 // which case it's likely that the user just forget to write "enum",
460 // "struct", or "union".
461 if (!getLangOptions().CPlusPlus && !SecondTry) {
462 Result.clear(LookupTagName);
463 LookupParsedName(Result, S, &SS);
464 if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) {
465 const char *TagName = 0;
466 const char *FixItTagName = 0;
467 switch (Tag->getTagKind()) {
468 case TTK_Class:
469 TagName = "class";
470 FixItTagName = "class ";
471 break;
472
473 case TTK_Enum:
474 TagName = "enum";
475 FixItTagName = "enum ";
476 break;
477
478 case TTK_Struct:
479 TagName = "struct";
480 FixItTagName = "struct ";
481 break;
482
483 case TTK_Union:
484 TagName = "union";
485 FixItTagName = "union ";
486 break;
487 }
488
489 Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
490 << Name << TagName << getLangOptions().CPlusPlus
491 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
492 break;
493 }
494
495 Result.clear(LookupOrdinaryName);
496 }
497
498 // Perform typo correction to determine if there is another name that is
499 // close to this name.
500 if (!SecondTry) {
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000501 SecondTry = true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000502 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
503 Result.getLookupKind(), S, &SS)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000504 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
505 unsigned QualifiedDiag = diag::err_no_member_suggest;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000506 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
507 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
Douglas Gregor5e16c162011-04-27 03:47:06 +0000508
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000509 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000510 NamedDecl *UnderlyingFirstDecl
511 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
Douglas Gregor5e16c162011-04-27 03:47:06 +0000512 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000513 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000514 UnqualifiedDiag = diag::err_no_template_suggest;
515 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000516 } else if (UnderlyingFirstDecl &&
517 (isa<TypeDecl>(UnderlyingFirstDecl) ||
518 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
519 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000520 UnqualifiedDiag = diag::err_unknown_typename_suggest;
521 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
522 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000523
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000524 if (SS.isEmpty())
Douglas Gregor5e16c162011-04-27 03:47:06 +0000525 Diag(NameLoc, UnqualifiedDiag)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000526 << Name << CorrectedQuotedStr
527 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000528 else
Douglas Gregor5e16c162011-04-27 03:47:06 +0000529 Diag(NameLoc, QualifiedDiag)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000530 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000531 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000532 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000533
534 // Update the name, so that the caller has the new name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000535 Name = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000536
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000537 // Also update the LookupResult...
538 // FIXME: This should probably go away at some point
539 Result.clear();
540 Result.setLookupName(Corrected.getCorrection());
541 if (FirstDecl) Result.addDecl(FirstDecl);
542
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000543 // Typo correction corrected to a keyword.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000544 if (Corrected.isKeyword())
545 return Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000546
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000547 if (FirstDecl)
548 Diag(FirstDecl->getLocation(), diag::note_previous_decl)
549 << CorrectedQuotedStr;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000550
551 // If we found an Objective-C instance variable, let
552 // LookupInObjCMethod build the appropriate expression to
553 // reference the ivar.
554 // FIXME: This is a gross hack.
555 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
556 Result.clear();
557 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
558 return move(E);
559 }
560
561 goto Corrected;
562 }
563 }
564
565 // We failed to correct; just fall through and let the parser deal with it.
566 Result.suppressDiagnostics();
567 return NameClassification::Unknown();
568
569 case LookupResult::NotFoundInCurrentInstantiation:
570 // We performed name lookup into the current instantiation, and there were
571 // dependent bases, so we treat this result the same way as any other
572 // dependent nested-name-specifier.
573
574 // C++ [temp.res]p2:
575 // A name used in a template declaration or definition and that is
576 // dependent on a template-parameter is assumed not to name a type
577 // unless the applicable name lookup finds a type name or the name is
578 // qualified by the keyword typename.
579 //
580 // FIXME: If the next token is '<', we might want to ask the parser to
581 // perform some heroics to see if we actually have a
582 // template-argument-list, which would indicate a missing 'template'
583 // keyword here.
584 return BuildDependentDeclRefExpr(SS, NameInfo, /*TemplateArgs=*/0);
585
586 case LookupResult::Found:
587 case LookupResult::FoundOverloaded:
588 case LookupResult::FoundUnresolvedValue:
589 break;
590
591 case LookupResult::Ambiguous:
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000592 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
593 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000594 // C++ [temp.local]p3:
595 // A lookup that finds an injected-class-name (10.2) can result in an
596 // ambiguity in certain cases (for example, if it is found in more than
597 // one base class). If all of the injected-class-names that are found
598 // refer to specializations of the same class template, and if the name
599 // is followed by a template-argument-list, the reference refers to the
600 // class template itself and not a specialization thereof, and is not
601 // ambiguous.
602 //
603 // This filtering can make an ambiguous result into an unambiguous one,
604 // so try again after filtering out template names.
605 FilterAcceptableTemplateNames(Result);
606 if (!Result.isAmbiguous()) {
607 IsFilteredTemplateName = true;
608 break;
609 }
610 }
611
612 // Diagnose the ambiguity and return an error.
613 return NameClassification::Error();
614 }
615
616 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
617 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
618 // C++ [temp.names]p3:
619 // After name lookup (3.4) finds that a name is a template-name or that
620 // an operator-function-id or a literal- operator-id refers to a set of
621 // overloaded functions any member of which is a function template if
622 // this is followed by a <, the < is always taken as the delimiter of a
623 // template-argument-list and never as the less-than operator.
624 if (!IsFilteredTemplateName)
625 FilterAcceptableTemplateNames(Result);
626
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000627 if (!Result.empty()) {
628 bool IsFunctionTemplate;
629 TemplateName Template;
630 if (Result.end() - Result.begin() > 1) {
631 IsFunctionTemplate = true;
632 Template = Context.getOverloadedTemplateName(Result.begin(),
633 Result.end());
634 } else {
635 TemplateDecl *TD
636 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
637 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
638
639 if (SS.isSet() && !SS.isInvalid())
640 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000641 /*TemplateKeyword=*/false,
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000642 TD);
643 else
644 Template = TemplateName(TD);
645 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000646
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000647 if (IsFunctionTemplate) {
648 // Function templates always go through overload resolution, at which
649 // point we'll perform the various checks (e.g., accessibility) we need
650 // to based on which function we selected.
651 Result.suppressDiagnostics();
652
653 return NameClassification::FunctionTemplate(Template);
654 }
655
656 return NameClassification::TypeTemplate(Template);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000657 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000658 }
659
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000660 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000661 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
662 DiagnoseUseOfDecl(Type, NameLoc);
663 QualType T = Context.getTypeDeclType(Type);
664 return ParsedType::make(T);
665 }
666
667 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
668 if (!Class) {
669 // FIXME: It's unfortunate that we don't have a Type node for handling this.
670 if (ObjCCompatibleAliasDecl *Alias
671 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
672 Class = Alias->getClassInterface();
673 }
674
675 if (Class) {
676 DiagnoseUseOfDecl(Class, NameLoc);
677
678 if (NextToken.is(tok::period)) {
679 // Interface. <something> is parsed as a property reference expression.
680 // Just return "unknown" as a fall-through for now.
681 Result.suppressDiagnostics();
682 return NameClassification::Unknown();
683 }
684
685 QualType T = Context.getObjCInterfaceType(Class);
686 return ParsedType::make(T);
687 }
688
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000689 if (!Result.empty() && (*Result.begin())->isCXXClassMember())
690 return BuildPossibleImplicitMemberExpr(SS, Result, 0);
691
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000692 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
693 return BuildDeclarationNameExpr(SS, Result, ADL);
694}
695
John McCall5ed6e8f2009-08-18 00:00:49 +0000696// Determines the context to return to after temporarily entering a
697// context. This depends in an unnecessarily complicated way on the
698// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000699DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000700
John McCall5ed6e8f2009-08-18 00:00:49 +0000701 // Functions defined inline within classes aren't parsed until we've
702 // finished parsing the top-level class, so the top-level class is
703 // the context we'll need to return to.
704 if (isa<FunctionDecl>(DC)) {
705 DC = DC->getLexicalParent();
706
707 // A function not defined within a class will always return to its
708 // lexical context.
709 if (!isa<CXXRecordDecl>(DC))
710 return DC;
711
712 // A C++ inline method/friend is parsed *after* the topmost class
713 // it was declared in is fully parsed ("complete"); the topmost
714 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000715 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000716 DC = RD;
717
718 // Return the declaration context of the topmost class the inline method is
719 // declared in.
720 return DC;
721 }
722
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000723 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000724}
725
Douglas Gregor91f84212008-12-11 16:49:14 +0000726void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000727 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000728 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000729 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000730 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000731}
732
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000733void Sema::PopDeclContext() {
734 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000735
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000736 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000737 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000738}
739
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000740/// EnterDeclaratorContext - Used when we must lookup names in the context
741/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000742///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000743void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000744 // C++0x [basic.lookup.unqual]p13:
745 // A name used in the definition of a static data member of class
746 // X (after the qualified-id of the static member) is looked up as
747 // if the name was used in a member function of X.
748 // C++0x [basic.lookup.unqual]p14:
749 // If a variable member of a namespace is defined outside of the
750 // scope of its namespace then any name used in the definition of
751 // the variable member (after the declarator-id) is looked up as
752 // if the definition of the variable member occurred in its
753 // namespace.
754 // Both of these imply that we should push a scope whose context
755 // is the semantic context of the declaration. We can't use
756 // PushDeclContext here because that context is not necessarily
757 // lexically contained in the current context. Fortunately,
758 // the containing scope should have the appropriate information.
759
760 assert(!S->getEntity() && "scope already has entity");
761
762#ifndef NDEBUG
763 Scope *Ancestor = S->getParent();
764 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
765 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
766#endif
767
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000768 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000769 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000770}
771
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000772void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000773 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000774
John McCall6df5fef2009-12-19 10:49:29 +0000775 // Switch back to the lexical context. The safety of this is
776 // enforced by an assert in EnterDeclaratorContext.
777 Scope *Ancestor = S->getParent();
778 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
779 CurContext = (DeclContext*) Ancestor->getEntity();
780
781 // We don't need to do anything with the scope, which is going to
782 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000783}
784
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000785
786void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
787 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
788 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
789 // We assume that the caller has already called
790 // ActOnReenterTemplateScope
791 FD = TFD->getTemplatedDecl();
792 }
793 if (!FD)
794 return;
795
796 PushDeclContext(S, FD);
797 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
798 ParmVarDecl *Param = FD->getParamDecl(P);
799 // If the parameter has an identifier, then add it to the scope
800 if (Param->getIdentifier()) {
801 S->AddDecl(Param);
802 IdResolver.AddDecl(Param);
803 }
804 }
805}
806
807
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000808/// \brief Determine whether we allow overloading of the function
809/// PrevDecl with another declaration.
810///
811/// This routine determines whether overloading is possible, not
812/// whether some new function is actually an overload. It will return
813/// true in C++ (where we can always provide overloads) or, as an
814/// extension, in C when the previous function is already an
815/// overloaded function declaration or has the "overloadable"
816/// attribute.
John McCall1f82f242009-11-18 22:49:29 +0000817static bool AllowOverloadingOfFunction(LookupResult &Previous,
818 ASTContext &Context) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000819 if (Context.getLangOptions().CPlusPlus)
820 return true;
821
John McCall1f82f242009-11-18 22:49:29 +0000822 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000823 return true;
824
John McCall1f82f242009-11-18 22:49:29 +0000825 return (Previous.getResultKind() == LookupResult::Found
826 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000827}
828
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000829/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +0000830void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +0000831 // Move up the scope chain until we find the nearest enclosing
832 // non-transparent context. The declaration will be introduced into this
833 // scope.
Mike Stump11289f42009-09-09 15:08:12 +0000834 while (S->getEntity() &&
Douglas Gregor07665a62009-01-05 19:45:36 +0000835 ((DeclContext *)S->getEntity())->isTransparentContext())
836 S = S->getParent();
837
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000838 // Add scoped declarations into their context, so that they can be
839 // found later. Declarations without a context won't be inserted
840 // into any context.
John McCall759e32b2009-08-31 22:39:49 +0000841 if (AddToContext)
842 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000843
Chandler Carruthf50ef6e2010-02-21 07:08:09 +0000844 // Out-of-line definitions shouldn't be pushed into scope in C++.
845 // Out-of-line variable and function definitions shouldn't even in C.
846 if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
847 D->isOutOfLine())
848 return;
849
850 // Template instantiations should also not be pushed into scope.
851 if (isa<FunctionDecl>(D) &&
852 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +0000853 return;
854
John McCall9f3059a2009-10-09 21:13:30 +0000855 // If this replaces anything in the current scope,
856 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
857 IEnd = IdResolver.end();
858 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +0000859 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
860 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +0000861 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000862
John McCall9f3059a2009-10-09 21:13:30 +0000863 // Should only need to replace one decl.
864 break;
Douglas Gregor38feed82009-04-24 02:57:34 +0000865 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000866 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000867
John McCall48871652010-08-21 09:40:31 +0000868 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +0000869
870 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
871 // Implicitly-generated labels may end up getting generated in an order that
872 // isn't strictly lexical, which breaks name lookup. Be careful to insert
873 // the label at the appropriate place in the identifier chain.
874 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +0000875 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +0000876 if (IDC == CurContext) {
877 if (!S->isDeclScope(*I))
878 continue;
879 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +0000880 break;
881 }
882
Douglas Gregor46c04e72011-03-16 16:39:03 +0000883 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +0000884 } else {
885 IdResolver.AddDecl(D);
886 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000887}
888
Douglas Gregordb446112011-03-07 16:54:27 +0000889bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
890 bool ExplicitInstantiationOrSpecialization) {
891 return IdResolver.isDeclInScope(D, Ctx, Context, S,
892 ExplicitInstantiationOrSpecialization);
Douglas Gregor505ad492009-09-28 00:47:05 +0000893}
894
John McCallcc14d1f2010-08-24 08:50:51 +0000895Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
896 DeclContext *TargetDC = DC->getPrimaryContext();
897 do {
898 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
899 if (ScopeDC->getPrimaryContext() == TargetDC)
900 return S;
901 } while ((S = S->getParent()));
902
903 return 0;
904}
905
John McCall1f82f242009-11-18 22:49:29 +0000906static bool isOutOfScopePreviousDeclaration(NamedDecl *,
907 DeclContext*,
908 ASTContext&);
909
910/// Filters out lookup results that don't fall within the given scope
911/// as determined by isDeclInScope.
Richard Smith3f1b5d02011-05-05 21:57:07 +0000912void Sema::FilterLookupForScope(LookupResult &R,
913 DeclContext *Ctx, Scope *S,
914 bool ConsiderLinkage,
915 bool ExplicitInstantiationOrSpecialization) {
John McCall1f82f242009-11-18 22:49:29 +0000916 LookupResult::Filter F = R.makeFilter();
917 while (F.hasNext()) {
918 NamedDecl *D = F.next();
919
Richard Smith3f1b5d02011-05-05 21:57:07 +0000920 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
John McCall1f82f242009-11-18 22:49:29 +0000921 continue;
922
923 if (ConsiderLinkage &&
Richard Smith3f1b5d02011-05-05 21:57:07 +0000924 isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +0000925 continue;
926
927 F.erase();
928 }
929
930 F.done();
931}
932
933static bool isUsingDecl(NamedDecl *D) {
934 return isa<UsingShadowDecl>(D) ||
935 isa<UnresolvedUsingTypenameDecl>(D) ||
936 isa<UnresolvedUsingValueDecl>(D);
937}
938
939/// Removes using shadow declarations from the lookup results.
940static void RemoveUsingDecls(LookupResult &R) {
941 LookupResult::Filter F = R.makeFilter();
942 while (F.hasNext())
943 if (isUsingDecl(F.next()))
944 F.erase();
945
946 F.done();
947}
948
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000949/// \brief Check for this common pattern:
950/// @code
951/// class S {
952/// S(const S&); // DO NOT IMPLEMENT
953/// void operator=(const S&); // DO NOT IMPLEMENT
954/// };
955/// @endcode
956static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
957 // FIXME: Should check for private access too but access is set after we get
958 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +0000959 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000960 return false;
961
962 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
963 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +0000964 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
965 return Method->isCopyAssignmentOperator();
966 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000967}
968
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000969bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
970 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +0000971
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000972 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
973 return false;
974
975 // Ignore class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +0000976 if (D->getDeclContext()->isDependentContext() ||
977 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000978 return false;
979
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000980 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000981 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
982 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000983
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000984 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
985 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
986 return false;
987 } else {
988 // 'static inline' functions are used in headers; don't warn.
John McCall8e7d6562010-08-26 03:08:43 +0000989 if (FD->getStorageClass() == SC_Static &&
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000990 FD->isInlineSpecified())
991 return false;
992 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000993
Alexis Hunt4a8ea102011-05-06 20:44:56 +0000994 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +0000995 Context.DeclMustBeEmitted(FD))
996 return false;
John McCalld37d35b2010-10-27 01:41:35 +0000997 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
998 if (!VD->isFileVarDecl() ||
999 VD->getType().isConstant(Context) ||
1000 Context.DeclMustBeEmitted(VD))
1001 return false;
1002
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001003 if (VD->isStaticDataMember() &&
1004 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1005 return false;
1006
John McCalld37d35b2010-10-27 01:41:35 +00001007 } else {
1008 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001009 }
1010
John McCalld37d35b2010-10-27 01:41:35 +00001011 // Only warn for unused decls internal to the translation unit.
1012 if (D->getLinkage() == ExternalLinkage)
1013 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001014
John McCalld37d35b2010-10-27 01:41:35 +00001015 return true;
1016}
1017
1018void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001019 if (!D)
1020 return;
1021
1022 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1023 const FunctionDecl *First = FD->getFirstDeclaration();
1024 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1025 return; // First should already be in the vector.
1026 }
1027
1028 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1029 const VarDecl *First = VD->getFirstDeclaration();
1030 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1031 return; // First should already be in the vector.
1032 }
1033
1034 if (ShouldWarnIfUnusedFileScopedDecl(D))
1035 UnusedFileScopedDecls.push_back(D);
1036 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001037
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001038static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001039 if (D->isInvalidDecl())
1040 return false;
1041
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001042 if (D->isUsed() || D->hasAttr<UnusedAttr>())
1043 return false;
John McCall67da35c2010-02-04 22:26:26 +00001044
Chris Lattnercab02a62011-02-17 20:34:02 +00001045 if (isa<LabelDecl>(D))
1046 return true;
1047
John McCall67da35c2010-02-04 22:26:26 +00001048 // White-list anything that isn't a local variable.
1049 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1050 !D->getDeclContext()->isFunctionOrMethod())
1051 return false;
1052
1053 // Types of valid local variables should be complete, so this should succeed.
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001054 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001055
1056 // White-list anything with an __attribute__((unused)) type.
1057 QualType Ty = VD->getType();
1058
1059 // Only look at the outermost level of typedef.
1060 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
1061 if (TT->getDecl()->hasAttr<UnusedAttr>())
1062 return false;
1063 }
1064
Douglas Gregor14f232e2010-05-08 23:05:03 +00001065 // If we failed to complete the type for some reason, or if the type is
1066 // dependent, don't diagnose the variable.
1067 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001068 return false;
1069
John McCallcef15822010-03-31 02:47:45 +00001070 if (const TagType *TT = Ty->getAs<TagType>()) {
1071 const TagDecl *Tag = TT->getDecl();
1072 if (Tag->hasAttr<UnusedAttr>())
1073 return false;
1074
1075 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Douglas Gregor14f232e2010-05-08 23:05:03 +00001076 // FIXME: Checking for the presence of a user-declared constructor
1077 // isn't completely accurate; we'd prefer to check that the initializer
1078 // has no side effects.
1079 if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001080 return false;
1081 }
1082 }
John McCallcef15822010-03-31 02:47:45 +00001083
1084 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001085 }
1086
John McCall67da35c2010-02-04 22:26:26 +00001087 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001088}
1089
Anna Zaks964f4c62011-07-28 20:52:06 +00001090static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1091 FixItHint &Hint) {
1092 if (isa<LabelDecl>(D)) {
1093 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1094 tok::colon, Ctx.getSourceManager(), Ctx.getLangOptions(), true);
1095 if (AfterColon.isInvalid())
1096 return;
1097 Hint = FixItHint::CreateRemoval(CharSourceRange::
1098 getCharRange(D->getLocStart(), AfterColon));
1099 }
1100 return;
1101}
1102
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001103/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1104/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001105void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaks964f4c62011-07-28 20:52:06 +00001106 FixItHint Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001107 if (!ShouldDiagnoseUnusedDecl(D))
1108 return;
1109
Anna Zaks964f4c62011-07-28 20:52:06 +00001110 GenerateFixForUnusedDecl(D, Context, Hint);
1111
Chris Lattnercab02a62011-02-17 20:34:02 +00001112 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001113 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001114 DiagID = diag::warn_unused_exception_param;
1115 else if (isa<LabelDecl>(D))
1116 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001117 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001118 DiagID = diag::warn_unused_variable;
1119
Anna Zaks964f4c62011-07-28 20:52:06 +00001120 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001121}
1122
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001123static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1124 // Verify that we have no forward references left. If so, there was a goto
1125 // or address of a label taken, but no definition of it. Label fwd
1126 // definitions are indicated with a null substmt.
1127 if (L->getStmt() == 0)
1128 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1129}
1130
Steve Naroffc62adb62007-10-09 22:01:59 +00001131void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001132 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001133 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001134 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001135
Chris Lattner302b4be2006-11-19 02:31:38 +00001136 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1137 I != E; ++I) {
John McCall48871652010-08-21 09:40:31 +00001138 Decl *TmpD = (*I);
Steve Naroff9324db12007-09-13 18:10:37 +00001139 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001140
Douglas Gregor91f84212008-12-11 16:49:14 +00001141 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1142 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001143
Douglas Gregor91f84212008-12-11 16:49:14 +00001144 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001145
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001146 // Diagnose unused variables in this scope.
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00001147 if (!S->hasErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001148 DiagnoseUnusedDecl(D);
1149
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001150 // If this was a forward reference to a label, verify it was defined.
1151 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1152 CheckPoppedLabel(LD, *this);
1153
Douglas Gregor91f84212008-12-11 16:49:14 +00001154 // Remove this name from our lexical scope.
1155 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001156 }
1157}
1158
Douglas Gregor1c283312010-08-11 12:19:30 +00001159/// \brief Look for an Objective-C class in the translation unit.
1160///
1161/// \param Id The name of the Objective-C class we're looking for. If
1162/// typo-correction fixes this name, the Id will be updated
1163/// to the fixed name.
1164///
1165/// \param IdLoc The location of the name in the translation unit.
1166///
1167/// \param TypoCorrection If true, this routine will attempt typo correction
1168/// if there is no class with the given name.
1169///
1170/// \returns The declaration of the named Objective-C class, or NULL if the
1171/// class could not be found.
1172ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1173 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001174 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001175 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1176 // creation from this context.
1177 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1178
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001179 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001180 // Perform typo correction at the given location, but only if we
1181 // find an Objective-C class name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001182 TypoCorrection C;
1183 if ((C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1184 TUScope, NULL, NULL, false, CTC_NoKeywords)) &&
1185 (IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>())) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001186 Diag(IdLoc, diag::err_undef_interface_suggest)
1187 << Id << IDecl->getDeclName()
1188 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1189 Diag(IDecl->getLocation(), diag::note_previous_decl)
1190 << IDecl->getDeclName();
1191
1192 Id = IDecl->getIdentifier();
1193 }
1194 }
1195
1196 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1197}
1198
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001199/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1200/// from S, where a non-field would be declared. This routine copes
1201/// with the difference between C and C++ scoping rules in structs and
1202/// unions. For example, the following code is well-formed in C but
1203/// ill-formed in C++:
1204/// @code
1205/// struct S6 {
1206/// enum { BAR } e;
1207/// };
Mike Stump11289f42009-09-09 15:08:12 +00001208///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001209/// void test_S6() {
1210/// struct S6 a;
1211/// a.e = BAR;
1212/// }
1213/// @endcode
1214/// For the declaration of BAR, this routine will return a different
1215/// scope. The scope S will be the scope of the unnamed enumeration
1216/// within S6. In C++, this routine will return the scope associated
1217/// with S6, because the enumeration's scope is a transparent
1218/// context but structures can contain non-field names. In C, this
1219/// routine will return the translation unit scope, since the
1220/// enumeration's scope is a transparent context and structures cannot
1221/// contain non-field names.
1222Scope *Sema::getNonFieldDeclScope(Scope *S) {
1223 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump11289f42009-09-09 15:08:12 +00001224 (S->getEntity() &&
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001225 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
1226 (S->isClassScope() && !getLangOptions().CPlusPlus))
1227 S = S->getParent();
1228 return S;
1229}
1230
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001231/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1232/// file scope. lazily create a decl for it. ForRedeclaration is true
1233/// if we're creating this built-in in anticipation of redeclaring the
1234/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001235NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001236 Scope *S, bool ForRedeclaration,
1237 SourceLocation Loc) {
Chris Lattner9561a0b2007-01-28 08:20:04 +00001238 Builtin::ID BID = (Builtin::ID)bid;
1239
Chris Lattnerecd79c62009-06-14 00:45:47 +00001240 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001241 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001242 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001243 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001244 // Okay
1245 break;
1246
Mike Stump93246cc2009-07-28 23:57:15 +00001247 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001248 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001249 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001250 << Context.BuiltinInfo.GetName(BID);
1251 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001252
Mike Stump93246cc2009-07-28 23:57:15 +00001253 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001254 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001255 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001256 << Context.BuiltinInfo.GetName(BID);
1257 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001258 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001259
1260 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1261 Diag(Loc, diag::ext_implicit_lib_function_decl)
1262 << Context.BuiltinInfo.GetName(BID)
1263 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001264 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001265 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
Chris Lattneraf73cf62009-04-16 03:59:32 +00001266 != Diagnostic::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001267 Diag(Loc, diag::note_please_include_header)
1268 << Context.BuiltinInfo.getHeaderName(BID)
1269 << Context.BuiltinInfo.GetName(BID);
1270 }
1271
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001272 FunctionDecl *New = FunctionDecl::Create(Context,
1273 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001274 Loc, Loc, II, R, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001275 SC_Extern,
1276 SC_None, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001277 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001278 New->setImplicit();
1279
Chris Lattner4dd27102008-05-05 22:18:14 +00001280 // Create Decl objects for each parameter, adding them to the
1281 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001282 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001283 SmallVector<ParmVarDecl*, 16> Params;
John McCall8fb0d9d2011-05-01 22:35:37 +00001284 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1285 ParmVarDecl *parm =
1286 ParmVarDecl::Create(Context, New, SourceLocation(),
1287 SourceLocation(), 0,
1288 FT->getArgType(i), /*TInfo=*/0,
1289 SC_None, SC_None, 0);
1290 parm->setScopeInfo(0, i);
1291 Params.push_back(parm);
1292 }
Douglas Gregord5058122010-02-11 01:19:42 +00001293 New->setParams(Params.data(), Params.size());
Chris Lattner4dd27102008-05-05 22:18:14 +00001294 }
Mike Stump11289f42009-09-09 15:08:12 +00001295
1296 AddKnownFunctionAttributes(New);
1297
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001298 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001299 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1300 // relate Scopes to DeclContexts, and probably eliminate CurContext
1301 // entirely, but we're not there yet.
1302 DeclContext *SavedContext = CurContext;
1303 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001304 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001305 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001306 return New;
1307}
1308
Richard Smithdda56e42011-04-15 14:24:37 +00001309/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001310/// same name and scope as a previous declaration 'Old'. Figure out
1311/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001312/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001313///
Richard Smithdda56e42011-04-15 14:24:37 +00001314void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001315 // If the new decl is known invalid already, don't bother doing any
1316 // merging checks.
1317 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001318
Steve Naroff44cfcb62008-09-09 14:32:20 +00001319 // Allow multiple definitions for ObjC built-in typedefs.
1320 // FIXME: Verify the underlying types are equivalent!
1321 if (getLangOptions().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001322 const IdentifierInfo *TypeID = New->getIdentifier();
1323 switch (TypeID->getLength()) {
1324 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001325 case 2:
Chris Lattner66e32812008-11-20 05:41:43 +00001326 if (!TypeID->isStr("id"))
1327 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001328 Context.setObjCIdRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001329 // Install the built-in type for 'id', ignoring the current definition.
1330 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1331 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001332 case 5:
1333 if (!TypeID->isStr("Class"))
1334 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001335 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001336 // Install the built-in type for 'Class', ignoring the current definition.
1337 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001338 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001339 case 3:
1340 if (!TypeID->isStr("SEL"))
1341 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001342 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001343 // Install the built-in type for 'SEL', ignoring the current definition.
1344 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001345 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001346 }
1347 // Fall through - the typedef name was not a builtin type.
1348 }
John McCall1f82f242009-11-18 22:49:29 +00001349
Douglas Gregorfb034662009-01-28 17:15:10 +00001350 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001351 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1352 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001353 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001354 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001355
1356 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001357 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001358 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001359
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001360 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001361 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001362
John McCall1f82f242009-11-18 22:49:29 +00001363 // If the old declaration is invalid, just give up here.
1364 if (Old->isInvalidDecl())
1365 return New->setInvalidDecl();
1366
Mike Stump11289f42009-09-09 15:08:12 +00001367 // Determine the "old" type we'll use for checking and diagnostics.
Douglas Gregorfb034662009-01-28 17:15:10 +00001368 QualType OldType;
Richard Smithdda56e42011-04-15 14:24:37 +00001369 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
Douglas Gregorfb034662009-01-28 17:15:10 +00001370 OldType = OldTypedef->getUnderlyingType();
1371 else
1372 OldType = Context.getTypeDeclType(Old);
1373
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001374 // If the typedef types are not identical, reject them in all languages and
1375 // with any extensions enabled.
Douglas Gregorfb034662009-01-28 17:15:10 +00001376
Mike Stump11289f42009-09-09 15:08:12 +00001377 if (OldType != New->getUnderlyingType() &&
1378 Context.getCanonicalType(OldType) !=
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001379 Context.getCanonicalType(New->getUnderlyingType())) {
Richard Smithdda56e42011-04-15 14:24:37 +00001380 int Kind = 0;
1381 if (isa<TypeAliasDecl>(Old))
1382 Kind = 1;
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00001383 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +00001384 << Kind << New->getUnderlyingType() << OldType;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001385 if (Old->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001386 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001387 return New->setInvalidDecl();
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001388 }
Mike Stump11289f42009-09-09 15:08:12 +00001389
John McCall91f1a022009-12-30 00:31:22 +00001390 // The types match. Link up the redeclaration chain if the old
1391 // declaration was a typedef.
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00001392 // FIXME: this is a potential source of weirdness if the type
John McCall91f1a022009-12-30 00:31:22 +00001393 // spellings don't match exactly.
Richard Smithdda56e42011-04-15 14:24:37 +00001394 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1395 New->setPreviousDeclaration(Typedef);
John McCall91f1a022009-12-30 00:31:22 +00001396
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001397 // __module_private__ is propagated to later declarations.
1398 if (Old->isModulePrivate())
1399 New->setModulePrivate();
1400
Steve Naroff7cae42b2009-07-10 23:34:53 +00001401 if (getLangOptions().Microsoft)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001402 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001403
Chris Lattner2581fc32009-04-17 22:04:20 +00001404 if (getLangOptions().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001405 // C++ [dcl.typedef]p2:
1406 // In a given non-class scope, a typedef specifier can be used to
1407 // redefine the name of any type declared in that scope to refer
1408 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001409 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001410 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001411
1412 // C++0x [dcl.typedef]p4:
1413 // In a given class scope, a typedef specifier can be used to redefine
1414 // any class-name declared in that scope that is not also a typedef-name
1415 // to refer to the type to which it already refers.
1416 //
1417 // This wording came in via DR424, which was a correction to the
1418 // wording in DR56, which accidentally banned code like:
1419 //
1420 // struct S {
1421 // typedef struct A { } A;
1422 // };
1423 //
1424 // in the C++03 standard. We implement the C++0x semantics, which
1425 // allow the above but disallow
1426 //
1427 // struct S {
1428 // typedef int I;
1429 // typedef int I;
1430 // };
1431 //
1432 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001433 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001434 return;
1435
Chris Lattner2581fc32009-04-17 22:04:20 +00001436 Diag(New->getLocation(), diag::err_redefinition)
1437 << New->getDeclName();
1438 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001439 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001440 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001441
Chris Lattner2581fc32009-04-17 22:04:20 +00001442 // If we have a redefinition of a typedef in C, emit a warning. This warning
1443 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001444 // -Wtypedef-redefinition. If either the original or the redefinition is
1445 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001446 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001447 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1448 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001449 return;
Mike Stump11289f42009-09-09 15:08:12 +00001450
Chris Lattner2581fc32009-04-17 22:04:20 +00001451 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1452 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001453 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001454 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001455}
1456
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001457/// DeclhasAttr - returns true if decl Declaration already has the target
1458/// attribute.
Mike Stump11289f42009-09-09 15:08:12 +00001459static bool
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001460DeclHasAttr(const Decl *D, const Attr *A) {
1461 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1462 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1463 if ((*i)->getKind() == A->getKind()) {
1464 // FIXME: Don't hardcode this check
1465 if (OA && isa<OwnershipAttr>(*i))
1466 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001467 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001468 }
Chris Lattner84966392008-03-03 03:28:21 +00001469
1470 return false;
1471}
1472
John McCallf79e87d2011-03-02 04:00:57 +00001473/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
1474static void mergeDeclAttributes(Decl *newDecl, const Decl *oldDecl,
John McCalld2930c22011-07-22 02:45:48 +00001475 ASTContext &C, bool mergeDeprecation = true) {
John McCallf79e87d2011-03-02 04:00:57 +00001476 if (!oldDecl->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001477 return;
John McCallf79e87d2011-03-02 04:00:57 +00001478
1479 bool foundAny = newDecl->hasAttrs();
1480
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001481 // Ensure that any moving of objects within the allocated map is done before
1482 // we process them.
John McCallf79e87d2011-03-02 04:00:57 +00001483 if (!foundAny) newDecl->setAttrs(AttrVec());
1484
Peter Collingbourneab8bc062011-01-21 02:08:36 +00001485 for (specific_attr_iterator<InheritableAttr>
John McCallf79e87d2011-03-02 04:00:57 +00001486 i = oldDecl->specific_attr_begin<InheritableAttr>(),
1487 e = oldDecl->specific_attr_end<InheritableAttr>(); i != e; ++i) {
John McCalld2930c22011-07-22 02:45:48 +00001488 // Ignore deprecated and unavailable attributes if requested.
1489 if (!mergeDeprecation &&
1490 (isa<DeprecatedAttr>(*i) || isa<UnavailableAttr>(*i)))
1491 continue;
1492
John McCallf79e87d2011-03-02 04:00:57 +00001493 if (!DeclHasAttr(newDecl, *i)) {
1494 InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(C));
1495 newAttr->setInherited(true);
1496 newDecl->addAttr(newAttr);
1497 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00001498 }
1499 }
John McCallf79e87d2011-03-02 04:00:57 +00001500
1501 if (!foundAny) newDecl->dropAttrs();
1502}
1503
1504/// mergeParamDeclAttributes - Copy attributes from the old parameter
1505/// to the new one.
1506static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1507 const ParmVarDecl *oldDecl,
1508 ASTContext &C) {
1509 if (!oldDecl->hasAttrs())
1510 return;
1511
1512 bool foundAny = newDecl->hasAttrs();
1513
1514 // Ensure that any moving of objects within the allocated map is
1515 // done before we process them.
1516 if (!foundAny) newDecl->setAttrs(AttrVec());
1517
1518 for (specific_attr_iterator<InheritableParamAttr>
1519 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1520 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1521 if (!DeclHasAttr(newDecl, *i)) {
1522 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1523 newAttr->setInherited(true);
1524 newDecl->addAttr(newAttr);
1525 foundAny = true;
1526 }
1527 }
1528
1529 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00001530}
1531
Dan Gohman28ade552010-07-26 21:25:24 +00001532namespace {
1533
Douglas Gregora74a2972009-03-06 22:43:54 +00001534/// Used in MergeFunctionDecl to keep track of function parameters in
1535/// C.
1536struct GNUCompatibleParamWarning {
1537 ParmVarDecl *OldParm;
1538 ParmVarDecl *NewParm;
1539 QualType PromotedType;
1540};
1541
Dan Gohman28ade552010-07-26 21:25:24 +00001542}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001543
1544/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00001545Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001546 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001547 if (Ctor->isDefaultConstructor())
1548 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00001549
1550 if (Ctor->isCopyConstructor())
1551 return Sema::CXXCopyConstructor;
1552
1553 if (Ctor->isMoveConstructor())
1554 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001555 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001556 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001557 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001558 return Sema::CXXCopyAssignment;
Sebastian Redle9c4e842011-09-04 18:14:28 +00001559 } else if (MD->isMoveAssignmentOperator()) {
1560 return Sema::CXXMoveAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001561 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001562
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001563 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001564}
1565
Sebastian Redl243d9052010-06-09 21:17:41 +00001566/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00001567/// only extern inline functions can be redefined, and even then only in
1568/// GNU89 mode.
1569static bool canRedefineFunction(const FunctionDecl *FD,
1570 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00001571 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
1572 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00001573 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00001574 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00001575}
1576
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001577/// MergeFunctionDecl - We just parsed a function 'New' from
1578/// declarator D which has the same name and scope as a previous
1579/// declaration 'Old'. Figure out how to resolve this situation,
1580/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001581///
1582/// In C++, New and Old must be declarations that are not
1583/// overloaded. Use IsOverload to determine whether New and Old are
1584/// overloaded, and to select the Old declaration that New should be
1585/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001586///
1587/// Returns true if there was an error, false otherwise.
1588bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00001589 // Verify the old decl was also a function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001590 FunctionDecl *Old = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001591 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001592 = dyn_cast<FunctionTemplateDecl>(OldD))
1593 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001594 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001595 Old = dyn_cast<FunctionDecl>(OldD);
Chris Lattnerc511efb2007-01-27 19:32:14 +00001596 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00001597 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1598 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1599 Diag(Shadow->getTargetDecl()->getLocation(),
1600 diag::note_using_decl_target);
1601 Diag(Shadow->getUsingDecl()->getLocation(),
1602 diag::note_using_decl) << 0;
1603 return true;
1604 }
1605
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00001606 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001607 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001608 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001609 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +00001610 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001611
1612 // Determine whether the previous declaration was a definition,
1613 // implicit declaration, or a declaration.
1614 diag::kind PrevDiag;
1615 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00001616 PrevDiag = diag::note_previous_definition;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001617 else if (Old->isImplicit())
1618 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00001619 else
Chris Lattner0369c572008-11-23 23:12:31 +00001620 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00001621
Chris Lattnerfc4379f2008-04-06 23:10:54 +00001622 QualType OldQType = Context.getCanonicalType(Old->getType());
1623 QualType NewQType = Context.getCanonicalType(New->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001624
Charles Davisfea48452010-02-18 02:00:42 +00001625 // Don't complain about this if we're in GNU89 mode and the old function
1626 // is an extern inline function.
Douglas Gregore62c0a42009-02-24 01:23:02 +00001627 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00001628 New->getStorageClass() == SC_Static &&
1629 Old->getStorageClass() != SC_Static &&
Charles Davisfea48452010-02-18 02:00:42 +00001630 !canRedefineFunction(Old, getLangOptions())) {
Francois Pichet6841a122011-04-22 19:50:06 +00001631 if (getLangOptions().Microsoft) {
1632 Diag(New->getLocation(), diag::warn_static_non_static) << New;
1633 Diag(Old->getLocation(), PrevDiag);
1634 } else {
1635 Diag(New->getLocation(), diag::err_static_non_static) << New;
1636 Diag(Old->getLocation(), PrevDiag);
1637 return true;
1638 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00001639 }
1640
John McCallcddbad02010-02-04 05:44:44 +00001641 // If a function is first declared with a calling convention, but is
1642 // later declared or defined without one, the second decl assumes the
1643 // calling convention of the first.
1644 //
1645 // For the new decl, we have to look at the NON-canonical type to tell the
1646 // difference between a function that really doesn't have a calling
1647 // convention and one that is declared cdecl. That's because in
1648 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1649 // because it is the default calling convention.
1650 //
1651 // Note also that we DO NOT return at this point, because we still have
1652 // other tests to run.
John McCall4f5019e2010-12-19 02:44:49 +00001653 const FunctionType *OldType = cast<FunctionType>(OldQType);
John McCallcddbad02010-02-04 05:44:44 +00001654 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
John McCall4f5019e2010-12-19 02:44:49 +00001655 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1656 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1657 bool RequiresAdjustment = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001658 if (OldTypeInfo.getCC() != CC_Default &&
1659 NewTypeInfo.getCC() == CC_Default) {
John McCall4f5019e2010-12-19 02:44:49 +00001660 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
1661 RequiresAdjustment = true;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001662 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1663 NewTypeInfo.getCC())) {
John McCallcddbad02010-02-04 05:44:44 +00001664 // Calling conventions really aren't compatible, so complain.
John McCallab26cfa2010-02-05 21:31:56 +00001665 Diag(New->getLocation(), diag::err_cconv_change)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001666 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1667 << (OldTypeInfo.getCC() == CC_Default)
1668 << (OldTypeInfo.getCC() == CC_Default ? "" :
1669 FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
John McCallab26cfa2010-02-05 21:31:56 +00001670 Diag(Old->getLocation(), diag::note_previous_declaration);
John McCallcddbad02010-02-04 05:44:44 +00001671 return true;
1672 }
1673
John McCallab26cfa2010-02-05 21:31:56 +00001674 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00001675 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
1676 NewTypeInfo = NewTypeInfo.withNoReturn(true);
1677 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00001678 }
1679
Douglas Gregor77e274f2010-06-18 21:30:25 +00001680 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00001681 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
1682 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
1683 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00001684 Diag(New->getLocation(), diag::err_regparm_mismatch)
1685 << NewType->getRegParmType()
1686 << OldType->getRegParmType();
1687 Diag(Old->getLocation(), diag::note_previous_declaration);
1688 return true;
1689 }
John McCall4f5019e2010-12-19 02:44:49 +00001690
1691 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
1692 RequiresAdjustment = true;
1693 }
1694
1695 if (RequiresAdjustment) {
1696 NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
1697 New->setType(QualType(NewType, 0));
1698 NewQType = Context.getCanonicalType(New->getType());
Douglas Gregor77e274f2010-06-18 21:30:25 +00001699 }
1700
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001701 if (getLangOptions().CPlusPlus) {
1702 // (C++98 13.1p2):
1703 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00001704 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001705 // cannot be overloaded.
John McCall4f5019e2010-12-19 02:44:49 +00001706 QualType OldReturnType = OldType->getResultType();
1707 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001708 QualType ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001709 if (OldReturnType != NewReturnType) {
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001710 if (NewReturnType->isObjCObjectPointerType()
1711 && OldReturnType->isObjCObjectPointerType())
1712 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1713 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00001714 if (New->isCXXClassMember() && New->isOutOfLine())
1715 Diag(New->getLocation(),
1716 diag::err_member_def_does_not_match_ret_type) << New;
1717 else
1718 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001719 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1720 return true;
1721 }
1722 else
1723 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001724 }
1725
1726 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
John McCall43314ab2010-04-13 07:45:41 +00001727 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001728 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00001729 // Preserve triviality.
1730 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00001731
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001732 // MSVC allows explicit template specialization at class scope:
1733 // 2 CXMethodDecls referring to the same function will be injected.
1734 // We don't want a redeclartion error.
1735 bool IsClassScopeExplicitSpecialization =
1736 OldMethod->isFunctionTemplateSpecialization() &&
1737 NewMethod->isFunctionTemplateSpecialization();
John McCall43314ab2010-04-13 07:45:41 +00001738 bool isFriend = NewMethod->getFriendObjectKind();
1739
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001740 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
1741 !IsClassScopeExplicitSpecialization) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001742 // -- Member function declarations with the same name and the
1743 // same parameter types cannot be overloaded if any of them
1744 // is a static member function declaration.
1745 if (OldMethod->isStatic() || NewMethod->isStatic()) {
1746 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1747 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1748 return true;
1749 }
1750
1751 // C++ [class.mem]p1:
1752 // [...] A member shall not be declared twice in the
1753 // member-specification, except that a nested class or member
1754 // class template can be declared and then later defined.
1755 unsigned NewDiag;
1756 if (isa<CXXConstructorDecl>(OldMethod))
1757 NewDiag = diag::err_constructor_redeclared;
1758 else if (isa<CXXDestructorDecl>(NewMethod))
1759 NewDiag = diag::err_destructor_redeclared;
1760 else if (isa<CXXConversionDecl>(NewMethod))
1761 NewDiag = diag::err_conv_function_redeclared;
1762 else
1763 NewDiag = diag::err_member_redeclared;
1764
1765 Diag(New->getLocation(), NewDiag);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001766 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00001767
1768 // Complain if this is an explicit declaration of a special
1769 // member that was initially declared implicitly.
1770 //
1771 // As an exception, it's okay to befriend such methods in order
1772 // to permit the implicit constructor/destructor/operator calls.
1773 } else if (OldMethod->isImplicit()) {
1774 if (isFriend) {
1775 NewMethod->setImplicit();
1776 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001777 Diag(NewMethod->getLocation(),
1778 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00001779 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001780 return true;
1781 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00001782 } else if (OldMethod->isExplicitlyDefaulted()) {
1783 Diag(NewMethod->getLocation(),
1784 diag::err_definition_of_explicitly_defaulted_member)
1785 << getSpecialMember(OldMethod);
1786 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001787 }
1788 }
1789
1790 // (C++98 8.3.5p3):
1791 // All declarations for a function shall agree exactly in both the
1792 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00001793 // We also want to respect all the extended bits except noreturn.
1794
1795 // noreturn should now match unless the old type info didn't have it.
1796 QualType OldQTypeForComparison = OldQType;
1797 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
1798 assert(OldQType == QualType(OldType, 0));
1799 const FunctionType *OldTypeForComparison
1800 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
1801 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
1802 assert(OldQTypeForComparison.isCanonical());
1803 }
1804
1805 if (OldQTypeForComparison == NewQType)
Douglas Gregore62c0a42009-02-24 01:23:02 +00001806 return MergeCompatibleFunctionDecls(New, Old);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001807
1808 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00001809 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001810
1811 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00001812 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001813 if (!getLangOptions().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00001814 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00001815 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1816 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001817 const FunctionProtoType *OldProto = 0;
1818 if (isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001819 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001820 // The old declaration provided a function prototype, but the
1821 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001822 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001823 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001824 OldProto->arg_type_end());
1825 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jay Foad7d0479f2009-05-21 09:52:38 +00001826 ParamTypes.data(), ParamTypes.size(),
John McCalldb40c7f2010-12-14 08:05:40 +00001827 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001828 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00001829 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001830
1831 // Synthesize a parameter for each argument type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001832 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00001833 for (FunctionProtoType::arg_type_iterator
1834 ParamType = OldProto->arg_type_begin(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001835 ParamEnd = OldProto->arg_type_end();
1836 ParamType != ParamEnd; ++ParamType) {
1837 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001838 SourceLocation(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001839 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00001840 *ParamType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001841 SC_None, SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001842 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00001843 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001844 Param->setImplicit();
1845 Params.push_back(Param);
1846 }
1847
Douglas Gregord5058122010-02-11 01:19:42 +00001848 New->setParams(Params.data(), Params.size());
Mike Stump11289f42009-09-09 15:08:12 +00001849 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001850
Douglas Gregore62c0a42009-02-24 01:23:02 +00001851 return MergeCompatibleFunctionDecls(New, Old);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001852 }
Chris Lattner45d561a2007-11-06 06:07:26 +00001853
Douglas Gregora74a2972009-03-06 22:43:54 +00001854 // GNU C permits a K&R definition to follow a prototype declaration
1855 // if the declared types of the parameters in the K&R definition
1856 // match the types in the prototype declaration, even when the
1857 // promoted types of the parameters from the K&R definition differ
1858 // from the types in the prototype. GCC then keeps the types from
1859 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001860 //
1861 // If a variadic prototype is followed by a non-variadic K&R definition,
1862 // the K&R definition becomes variadic. This is sort of an edge case, but
1863 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1864 // C99 6.9.1p8.
Douglas Gregora74a2972009-03-06 22:43:54 +00001865 if (!getLangOptions().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001866 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00001867 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001868 Old->getNumParams() == New->getNumParams()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001869 SmallVector<QualType, 16> ArgTypes;
1870 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00001871 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00001872 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001873 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00001874 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001875
Douglas Gregora74a2972009-03-06 22:43:54 +00001876 // Determine whether this is the GNU C extension.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001877 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1878 NewProto->getResultType());
1879 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00001880 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001881 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00001882 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1883 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00001884 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregora74a2972009-03-06 22:43:54 +00001885 NewProto->getArgType(Idx))) {
1886 ArgTypes.push_back(NewParm->getType());
1887 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00001888 NewParm->getType(),
1889 /*CompareUnqualified=*/true)) {
Mike Stump11289f42009-09-09 15:08:12 +00001890 GNUCompatibleParamWarning Warn
Douglas Gregora74a2972009-03-06 22:43:54 +00001891 = { OldParm, NewParm, NewProto->getArgType(Idx) };
1892 Warnings.push_back(Warn);
1893 ArgTypes.push_back(NewParm->getType());
1894 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001895 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00001896 }
1897
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001898 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00001899 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1900 Diag(Warnings[Warn].NewParm->getLocation(),
1901 diag::ext_param_promoted_not_compatible_with_prototype)
1902 << Warnings[Warn].PromotedType
1903 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00001904 if (Warnings[Warn].OldParm->getLocation().isValid())
1905 Diag(Warnings[Warn].OldParm->getLocation(),
1906 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00001907 }
1908
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001909 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1910 ArgTypes.size(),
John McCalldb40c7f2010-12-14 08:05:40 +00001911 OldProto->getExtProtoInfo()));
Douglas Gregora74a2972009-03-06 22:43:54 +00001912 return MergeCompatibleFunctionDecls(New, Old);
1913 }
1914
1915 // Fall through to diagnose conflicting types.
1916 }
1917
Steve Naroff17832a42008-01-16 15:01:34 +00001918 // A function that has already been declared has been redeclared or defined
1919 // with a different type- show appropriate diagnostic
Douglas Gregor15fc9562009-09-12 00:22:50 +00001920 if (unsigned BuiltinID = Old->getBuiltinID()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001921 // The user has declared a builtin function with an incompatible
1922 // signature.
1923 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1924 // The function the user is redeclaring is a library-defined
1925 // function like 'malloc' or 'printf'. Warn about the
Douglas Gregor893c2c92009-03-23 17:47:24 +00001926 // redeclaration, then pretend that we don't know about this
1927 // library built-in.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001928 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1929 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1930 << Old << Old->getType();
Douglas Gregor893c2c92009-03-23 17:47:24 +00001931 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1932 Old->setInvalidDecl();
1933 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001934 }
Steve Naroff17832a42008-01-16 15:01:34 +00001935
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001936 PrevDiag = diag::note_previous_builtin_declaration;
1937 }
1938
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001939 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001940 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001941 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00001942}
1943
Douglas Gregore62c0a42009-02-24 01:23:02 +00001944/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00001945/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00001946///
1947/// This routine handles the merging of attributes and other
1948/// properties of function declarations form the old declaration to
1949/// the new declaration, once we know that New is in fact a
1950/// redeclaration of Old.
1951///
1952/// \returns false
1953bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1954 // Merge the attributes
John McCallf79e87d2011-03-02 04:00:57 +00001955 mergeDeclAttributes(New, Old, Context);
Douglas Gregore62c0a42009-02-24 01:23:02 +00001956
1957 // Merge the storage class.
John McCall8e7d6562010-08-26 03:08:43 +00001958 if (Old->getStorageClass() != SC_Extern &&
1959 Old->getStorageClass() != SC_None)
Douglas Gregor76fe50c2009-04-28 06:37:30 +00001960 New->setStorageClass(Old->getStorageClass());
Douglas Gregore62c0a42009-02-24 01:23:02 +00001961
Douglas Gregore62c0a42009-02-24 01:23:02 +00001962 // Merge "pure" flag.
1963 if (Old->isPure())
1964 New->setPure();
1965
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001966 // __module_private__ is propagated to later declarations.
1967 if (Old->isModulePrivate())
1968 New->setModulePrivate();
1969
John McCallf79e87d2011-03-02 04:00:57 +00001970 // Merge attributes from the parameters. These can mismatch with K&R
1971 // declarations.
1972 if (New->getNumParams() == Old->getNumParams())
1973 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
1974 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
1975 Context);
1976
Douglas Gregore62c0a42009-02-24 01:23:02 +00001977 if (getLangOptions().CPlusPlus)
1978 return MergeCXXFunctionDecl(New, Old);
1979
1980 return false;
1981}
1982
John McCall31168b02011-06-15 23:02:42 +00001983
John McCallf79e87d2011-03-02 04:00:57 +00001984void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
1985 const ObjCMethodDecl *oldMethod) {
John McCalld2930c22011-07-22 02:45:48 +00001986 // We don't want to merge unavailable and deprecated attributes
1987 // except from interface to implementation.
1988 bool mergeDeprecation = isa<ObjCImplDecl>(newMethod->getDeclContext());
1989
John McCallf79e87d2011-03-02 04:00:57 +00001990 // Merge the attributes.
John McCalld2930c22011-07-22 02:45:48 +00001991 mergeDeclAttributes(newMethod, oldMethod, Context, mergeDeprecation);
John McCallf79e87d2011-03-02 04:00:57 +00001992
1993 // Merge attributes from the parameters.
1994 for (ObjCMethodDecl::param_iterator oi = oldMethod->param_begin(),
1995 ni = newMethod->param_begin(), ne = newMethod->param_end();
1996 ni != ne; ++ni, ++oi)
Douglas Gregor33823722011-06-11 01:09:30 +00001997 mergeParamDeclAttributes(*ni, *oi, Context);
John McCalld2930c22011-07-22 02:45:48 +00001998
Douglas Gregor33823722011-06-11 01:09:30 +00001999 CheckObjCMethodOverride(newMethod, oldMethod, true);
John McCallf79e87d2011-03-02 04:00:57 +00002000}
2001
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002002/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2003/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00002004/// emitting diagnostics as appropriate.
2005///
2006/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2007/// to here in AddInitializerToDecl and AddCXXDirectInitializerToDecl. We can't
2008/// check them before the initializer is attached.
2009///
2010void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
2011 if (New->isInvalidDecl() || Old->isInvalidDecl())
2012 return;
2013
2014 QualType MergedT;
2015 if (getLangOptions().CPlusPlus) {
2016 AutoType *AT = New->getType()->getContainedAutoType();
2017 if (AT && !AT->isDeduced()) {
2018 // We don't know what the new type is until the initializer is attached.
2019 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002020 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2021 // These could still be something that needs exception specs checked.
2022 return MergeVarDeclExceptionSpecs(New, Old);
2023 }
Richard Smith30482bc2011-02-20 03:19:35 +00002024 // C++ [basic.link]p10:
2025 // [...] the types specified by all declarations referring to a given
2026 // object or function shall be identical, except that declarations for an
2027 // array object can specify array types that differ by the presence or
2028 // absence of a major array bound (8.3.4).
2029 else if (Old->getType()->isIncompleteArrayType() &&
2030 New->getType()->isArrayType()) {
2031 CanQual<ArrayType> OldArray
2032 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2033 CanQual<ArrayType> NewArray
2034 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2035 if (OldArray->getElementType() == NewArray->getElementType())
2036 MergedT = New->getType();
2037 } else if (Old->getType()->isArrayType() &&
2038 New->getType()->isIncompleteArrayType()) {
2039 CanQual<ArrayType> OldArray
2040 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2041 CanQual<ArrayType> NewArray
2042 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2043 if (OldArray->getElementType() == NewArray->getElementType())
2044 MergedT = Old->getType();
2045 } else if (New->getType()->isObjCObjectPointerType()
2046 && Old->getType()->isObjCObjectPointerType()) {
2047 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2048 Old->getType());
2049 }
2050 } else {
2051 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2052 }
2053 if (MergedT.isNull()) {
2054 Diag(New->getLocation(), diag::err_redefinition_different_type)
2055 << New->getDeclName();
2056 Diag(Old->getLocation(), diag::note_previous_definition);
2057 return New->setInvalidDecl();
2058 }
2059 New->setType(MergedT);
2060}
2061
Chris Lattner01564d92007-01-27 19:27:06 +00002062/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2063/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2064/// situation, merging decls or emitting diagnostics as appropriate.
2065///
Mike Stump11289f42009-09-09 15:08:12 +00002066/// Tentative definition rules (C99 6.9.2p2) are checked by
2067/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00002068/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00002069///
John McCall1f82f242009-11-18 22:49:29 +00002070void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2071 // If the new decl is already invalid, don't do any other checking.
2072 if (New->isInvalidDecl())
2073 return;
Mike Stump11289f42009-09-09 15:08:12 +00002074
Chris Lattnerc511efb2007-01-27 19:32:14 +00002075 // Verify the old decl was also a variable.
John McCall1f82f242009-11-18 22:49:29 +00002076 VarDecl *Old = 0;
2077 if (!Previous.isSingleResult() ||
2078 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Chris Lattner651d42d2008-11-20 06:38:18 +00002079 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002080 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00002081 Diag(Previous.getRepresentativeDecl()->getLocation(),
2082 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002083 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002084 }
Chris Lattner84966392008-03-03 03:28:21 +00002085
Douglas Gregor2c7d9292010-08-30 14:32:14 +00002086 // C++ [class.mem]p1:
2087 // A member shall not be declared twice in the member-specification [...]
2088 //
2089 // Here, we need only consider static data members.
2090 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2091 Diag(New->getLocation(), diag::err_duplicate_member)
2092 << New->getIdentifier();
2093 Diag(Old->getLocation(), diag::note_previous_declaration);
2094 New->setInvalidDecl();
2095 }
2096
John McCallf79e87d2011-03-02 04:00:57 +00002097 mergeDeclAttributes(New, Old, Context);
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002098 // Warn if an already-declared variable is made a weak_import in a subsequent declaration
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00002099 if (New->getAttr<WeakImportAttr>() &&
2100 Old->getStorageClass() == SC_None &&
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002101 !Old->getAttr<WeakImportAttr>()) {
2102 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2103 Diag(Old->getLocation(), diag::note_previous_definition);
2104 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00002105 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002106 }
Chris Lattner84966392008-03-03 03:28:21 +00002107
Richard Smith30482bc2011-02-20 03:19:35 +00002108 // Merge the types.
2109 MergeVarDeclTypes(New, Old);
2110 if (New->isInvalidDecl())
2111 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00002112
Steve Naroff1e787362008-01-30 00:44:01 +00002113 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
John McCall8e7d6562010-08-26 03:08:43 +00002114 if (New->getStorageClass() == SC_Static &&
2115 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002116 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002117 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002118 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00002119 }
Mike Stump11289f42009-09-09 15:08:12 +00002120 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00002121 // For an identifier declared with the storage-class specifier
2122 // extern in a scope in which a prior declaration of that
2123 // identifier is visible,23) if the prior declaration specifies
2124 // internal or external linkage, the linkage of the identifier at
2125 // the later declaration is the same as the linkage specified at
2126 // the prior declaration. If no prior declaration is visible, or
2127 // if the prior declaration specifies no linkage, then the
2128 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00002129 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00002130 /* Okay */;
John McCall8e7d6562010-08-26 03:08:43 +00002131 else if (New->getStorageClass() != SC_Static &&
2132 Old->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002133 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002134 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002135 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00002136 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00002137
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00002138 // Check if extern is followed by non-extern and vice-versa.
2139 if (New->hasExternalStorage() &&
2140 !Old->hasLinkage() && Old->isLocalVarDecl()) {
2141 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2142 Diag(Old->getLocation(), diag::note_previous_definition);
2143 return New->setInvalidDecl();
2144 }
2145 if (Old->hasExternalStorage() &&
2146 !New->hasLinkage() && New->isLocalVarDecl()) {
2147 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2148 Diag(Old->getLocation(), diag::note_previous_definition);
2149 return New->setInvalidDecl();
2150 }
2151
Douglas Gregoref15bdb2011-09-09 18:32:39 +00002152 // __module_private__ is propagated to later declarations.
2153 if (Old->isModulePrivate())
2154 New->setModulePrivate();
2155
Steve Naroffa5629372008-09-17 14:05:40 +00002156 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00002157
Daniel Dunbar0ca16602009-04-14 02:25:56 +00002158 // FIXME: The test for external storage here seems wrong? We still
2159 // need to check for mismatches.
2160 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00002161 // Don't complain about out-of-line definitions of static members.
2162 !(Old->getLexicalDeclContext()->isRecord() &&
2163 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00002164 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002165 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002166 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00002167 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00002168
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002169 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2170 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2171 Diag(Old->getLocation(), diag::note_previous_definition);
2172 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2173 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2174 Diag(Old->getLocation(), diag::note_previous_definition);
2175 }
2176
Sebastian Redlf1842912010-02-02 18:35:11 +00002177 // C++ doesn't have tentative definitions, so go right ahead and check here.
2178 const VarDecl *Def;
Sebastian Redld85be0c2010-02-03 02:08:48 +00002179 if (getLangOptions().CPlusPlus &&
2180 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00002181 (Def = Old->getDefinition())) {
2182 Diag(New->getLocation(), diag::err_redefinition)
2183 << New->getDeclName();
2184 Diag(Def->getLocation(), diag::note_previous_definition);
2185 New->setInvalidDecl();
2186 return;
2187 }
Fariborz Jahanianad356a12010-06-25 00:05:45 +00002188 // c99 6.2.2 P4.
2189 // For an identifier declared with the storage-class specifier extern in a
2190 // scope in which a prior declaration of that identifier is visible, if
2191 // the prior declaration specifies internal or external linkage, the linkage
2192 // of the identifier at the later declaration is the same as the linkage
2193 // specified at the prior declaration.
2194 // FIXME. revisit this code.
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00002195 if (New->hasExternalStorage() &&
Fariborz Jahanian4f9c9d62010-06-24 18:50:41 +00002196 Old->getLinkage() == InternalLinkage &&
2197 New->getDeclContext() == Old->getDeclContext())
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00002198 New->setStorageClass(Old->getStorageClass());
2199
Douglas Gregor0760fa12009-03-10 23:43:53 +00002200 // Keep a chain of previous declarations.
2201 New->setPreviousDeclaration(Old);
John McCall401982f2010-01-20 21:53:11 +00002202
2203 // Inherit access appropriately.
2204 New->setAccess(Old->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00002205}
2206
Chris Lattnerb6738ec2007-01-28 00:38:24 +00002207/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2208/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00002209Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00002210 DeclSpec &DS) {
Chandler Carruth7c9856d2011-05-03 18:35:10 +00002211 return ParsedFreeStandingDeclSpec(S, AS, DS,
2212 MultiTemplateParamsArg(*this, 0, 0));
2213}
2214
2215/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2216/// no declarator (e.g. "struct foo;") is parsed. It also accopts template
2217/// parameters to cope with template friend declarations.
2218Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2219 DeclSpec &DS,
2220 MultiTemplateParamsArg TemplateParams) {
John McCallc3987482009-10-07 23:34:25 +00002221 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002222 TagDecl *Tag = 0;
2223 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2224 DS.getTypeSpecType() == DeclSpec::TST_struct ||
2225 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002226 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00002227 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00002228
2229 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00002230 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002231
John McCall07e91c02009-08-06 02:15:43 +00002232 // Note that the above type specs guarantee that the
2233 // type rep is a Decl, whereas in many of the others
2234 // it's a Type.
John McCallc3987482009-10-07 23:34:25 +00002235 Tag = dyn_cast<TagDecl>(TagD);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002236 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002237
Nuno Lopese9823fa2009-12-17 11:35:26 +00002238 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
2239 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
2240 // or incomplete types shall not be restrict-qualified."
2241 if (TypeQuals & DeclSpec::TQ_restrict)
2242 Diag(DS.getRestrictSpecLoc(),
2243 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
2244 << DS.getSourceRange();
2245 }
2246
Richard Smitha77a0a62011-08-15 21:04:07 +00002247 if (DS.isConstexprSpecified()) {
2248 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
2249 // and definitions of functions and variables.
2250 if (Tag)
2251 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
2252 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
2253 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
2254 DS.getTypeSpecType() == DeclSpec::TST_union ? 2 : 3);
2255 else
2256 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
2257 // Don't emit warnings after this error.
2258 return TagD;
2259 }
2260
Douglas Gregor3dad8422009-09-26 06:47:28 +00002261 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00002262 // If we're dealing with a decl but not a TagDecl, assume that
2263 // whatever routines created it handled the friendship aspect.
2264 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00002265 return 0;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00002266 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00002267 }
John McCallaa017372011-03-22 23:00:04 +00002268
2269 // Track whether we warned about the fact that there aren't any
2270 // declarators.
2271 bool emittedWarning = false;
Douglas Gregor3dad8422009-09-26 06:47:28 +00002272
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002273 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCall53fa7142010-12-24 02:08:15 +00002274 ProcessDeclAttributeList(S, Record, DS.getAttributes().getList());
Chris Lattnerecf328e2009-10-25 22:21:57 +00002275
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002276 if (!Record->getDeclName() && Record->isDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002277 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
2278 if (getLangOptions().CPlusPlus ||
2279 Record->getDeclContext()->isRecord())
John McCallb54367d2010-05-21 20:45:30 +00002280 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002281
Douglas Gregorf19ac0e2010-04-08 21:33:23 +00002282 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002283 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002284 emittedWarning = true;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002285 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002286 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002287
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002288 // Check for Microsoft C extension: anonymous struct.
2289 if (getLangOptions().Microsoft && !getLangOptions().CPlusPlus &&
2290 CurContext->isRecord() &&
2291 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
2292 // Handle 2 kinds of anonymous struct:
2293 // struct STRUCT;
2294 // and
2295 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
2296 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
2297 if ((Record && Record->getDeclName() && !Record->isDefinition()) ||
2298 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
2299 DS.getRepAsType().get()->isStructureType())) {
2300 Diag(DS.getSourceRange().getBegin(), diag::ext_ms_anonymous_struct)
2301 << DS.getSourceRange();
2302 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
2303 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002304 }
Douglas Gregor3dad8422009-09-26 06:47:28 +00002305
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002306 if (getLangOptions().CPlusPlus &&
2307 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
2308 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
2309 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
John McCallaa017372011-03-22 23:00:04 +00002310 !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002311 Diag(Enum->getLocation(), diag::ext_no_declarators)
2312 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002313 emittedWarning = true;
2314 }
2315
2316 // Skip all the checks below if we have a type error.
2317 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002318
John McCallaa017372011-03-22 23:00:04 +00002319 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregor2d9dde0e2009-01-22 16:23:54 +00002320 // Warn about typedefs of enums without names, since this is an
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00002321 // extension in both Microsoft and GNU.
Douglas Gregor051d8fd2009-01-17 02:55:50 +00002322 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
2323 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00002324 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
2325 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00002326 return Tag;
Douglas Gregor2b136fe2009-01-13 23:10:51 +00002327 }
2328
Douglas Gregorf19ac0e2010-04-08 21:33:23 +00002329 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Sebastian Redla2b5e312008-12-28 15:28:59 +00002330 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002331 emittedWarning = true;
Sebastian Redla2b5e312008-12-28 15:28:59 +00002332 }
Mike Stump11289f42009-09-09 15:08:12 +00002333
John McCallaa017372011-03-22 23:00:04 +00002334 // We're going to complain about a bunch of spurious specifiers;
2335 // only do this if we're declaring a tag, because otherwise we
2336 // should be getting diag::ext_no_declarators.
2337 if (emittedWarning || (TagD && TagD->isInvalidDecl()))
2338 return TagD;
2339
John McCall4d55f5a2011-03-26 02:09:52 +00002340 // Note that a linkage-specification sets a storage class, but
2341 // 'extern "C" struct foo;' is actually valid and not theoretically
2342 // useless.
John McCallaa017372011-03-22 23:00:04 +00002343 if (DeclSpec::SCS scs = DS.getStorageClassSpec())
John McCall4d55f5a2011-03-26 02:09:52 +00002344 if (!DS.isExternInLinkageSpec())
2345 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
2346 << DeclSpec::getSpecifierName(scs);
2347
John McCallaa017372011-03-22 23:00:04 +00002348 if (DS.isThreadSpecified())
2349 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
2350 if (DS.getTypeQualifiers()) {
2351 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2352 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
2353 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2354 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
2355 // Restrict is covered above.
2356 }
2357 if (DS.isInlineSpecified())
2358 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
2359 if (DS.isVirtualSpecified())
2360 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
2361 if (DS.isExplicitSpecified())
2362 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
2363
2364 // FIXME: Warn on useless attributes
2365
John McCall48871652010-08-21 09:40:31 +00002366 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002367}
2368
Fariborz Jahanian1db5c942010-09-28 20:42:35 +00002369/// ActOnVlaStmt - This rouine if finds a vla expression in a decl spec.
2370/// builds a statement for it and returns it so it is evaluated.
2371StmtResult Sema::ActOnVlaStmt(const DeclSpec &DS) {
2372 StmtResult R;
2373 if (DS.getTypeSpecType() == DeclSpec::TST_typeofExpr) {
2374 Expr *Exp = DS.getRepAsExpr();
2375 QualType Ty = Exp->getType();
2376 if (Ty->isPointerType()) {
2377 do
2378 Ty = Ty->getAs<PointerType>()->getPointeeType();
2379 while (Ty->isPointerType());
2380 }
2381 if (Ty->isVariableArrayType()) {
2382 R = ActOnExprStmt(MakeFullExpr(Exp));
2383 }
2384 }
2385 return R;
2386}
2387
John McCallea305ed2009-12-18 10:40:03 +00002388/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00002389/// check if there's an existing declaration that can't be overloaded.
2390///
2391/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00002392static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
2393 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00002394 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00002395 DeclarationName Name,
2396 SourceLocation NameLoc,
2397 unsigned diagnostic) {
2398 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
2399 Sema::ForRedeclaration);
2400 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00002401
John McCallea305ed2009-12-18 10:40:03 +00002402 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00002403 return false;
2404
2405 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00002406 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00002407 assert(PrevDecl && "Expected a non-null Decl");
2408
2409 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
2410 return false;
John McCall1f82f242009-11-18 22:49:29 +00002411
John McCallea305ed2009-12-18 10:40:03 +00002412 SemaRef.Diag(NameLoc, diagnostic) << Name;
2413 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00002414
2415 return true;
2416}
2417
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002418/// InjectAnonymousStructOrUnionMembers - Inject the members of the
2419/// anonymous struct or union AnonRecord into the owning context Owner
2420/// and scope S. This routine will be invoked just after we realize
2421/// that an unnamed union or struct is actually an anonymous union or
2422/// struct, e.g.,
2423///
2424/// @code
2425/// union {
2426/// int i;
2427/// float f;
2428/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
2429/// // f into the surrounding scope.x
2430/// @endcode
2431///
2432/// This routine is recursive, injecting the names of nested anonymous
2433/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00002434static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
2435 DeclContext *Owner,
2436 RecordDecl *AnonRecord,
Francois Pichet783dd6e2010-11-21 06:08:52 +00002437 AccessSpecifier AS,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002438 SmallVector<NamedDecl*, 2> &Chaining,
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002439 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00002440 unsigned diagKind
2441 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
2442 : diag::err_anonymous_struct_member_redecl;
2443
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002444 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002445
2446 // Look every FieldDecl and IndirectFieldDecl with a name.
2447 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
2448 DEnd = AnonRecord->decls_end();
2449 D != DEnd; ++D) {
2450 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
2451 cast<NamedDecl>(*D)->getDeclName()) {
2452 ValueDecl *VD = cast<ValueDecl>(*D);
2453 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
2454 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002455 // C++ [class.union]p2:
2456 // The names of the members of an anonymous union shall be
2457 // distinct from the names of any other entity in the
2458 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002459 Invalid = true;
2460 } else {
2461 // C++ [class.union]p2:
2462 // For the purpose of name lookup, after the anonymous union
2463 // definition, the members of the anonymous union are
2464 // considered to have been defined in the scope in which the
2465 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002466 unsigned OldChainingSize = Chaining.size();
2467 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
2468 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
2469 PE = IF->chain_end(); PI != PE; ++PI)
2470 Chaining.push_back(*PI);
2471 else
2472 Chaining.push_back(VD);
2473
Francois Pichet783dd6e2010-11-21 06:08:52 +00002474 assert(Chaining.size() >= 2);
2475 NamedDecl **NamedChain =
2476 new (SemaRef.Context)NamedDecl*[Chaining.size()];
2477 for (unsigned i = 0; i < Chaining.size(); i++)
2478 NamedChain[i] = Chaining[i];
2479
2480 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002481 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
2482 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00002483 NamedChain, Chaining.size());
2484
2485 IndirectField->setAccess(AS);
2486 IndirectField->setImplicit();
2487 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00002488
2489 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002490 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002491
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002492 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002493 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002494 }
2495 }
2496
2497 return Invalid;
2498}
2499
Douglas Gregorc4df4072010-04-19 22:54:31 +00002500/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
2501/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00002502/// illegal input values are mapped to SC_None.
2503static StorageClass
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002504StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002505 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00002506 case DeclSpec::SCS_unspecified: return SC_None;
2507 case DeclSpec::SCS_extern: return SC_Extern;
2508 case DeclSpec::SCS_static: return SC_Static;
2509 case DeclSpec::SCS_auto: return SC_Auto;
2510 case DeclSpec::SCS_register: return SC_Register;
2511 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002512 // Illegal SCSs map to None: error reporting is up to the caller.
2513 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00002514 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002515 }
2516 llvm_unreachable("unknown storage class specifier");
2517}
2518
2519/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
John McCall8e7d6562010-08-26 03:08:43 +00002520/// a StorageClass. Any error reporting is up to the caller:
2521/// illegal input values are mapped to SC_None.
2522static StorageClass
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002523StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002524 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00002525 case DeclSpec::SCS_unspecified: return SC_None;
2526 case DeclSpec::SCS_extern: return SC_Extern;
2527 case DeclSpec::SCS_static: return SC_Static;
2528 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002529 // Illegal SCSs map to None: error reporting is up to the caller.
2530 case DeclSpec::SCS_auto: // Fall through.
2531 case DeclSpec::SCS_mutable: // Fall through.
2532 case DeclSpec::SCS_register: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00002533 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002534 }
2535 llvm_unreachable("unknown storage class specifier");
2536}
2537
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002538/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002539/// anonymous structure or union. Anonymous unions are a C++ feature
2540/// (C++ [class.union]) and a GNU C extension; anonymous structures
Mike Stump11289f42009-09-09 15:08:12 +00002541/// are a GNU C and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00002542Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2543 AccessSpecifier AS,
2544 RecordDecl *Record) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002545 DeclContext *Owner = Record->getDeclContext();
2546
2547 // Diagnose whether this anonymous struct/union is an extension.
2548 if (Record->isUnion() && !getLangOptions().CPlusPlus)
2549 Diag(Record->getLocation(), diag::ext_anonymous_union);
2550 else if (!Record->isUnion())
2551 Diag(Record->getLocation(), diag::ext_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00002552
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002553 // C and C++ require different kinds of checks for anonymous
2554 // structs/unions.
2555 bool Invalid = false;
2556 if (getLangOptions().CPlusPlus) {
2557 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00002558 unsigned DiagID;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002559 // C++ [class.union]p3:
2560 // Anonymous unions declared in a named namespace or in the
2561 // global namespace shall be declared static.
2562 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
2563 (isa<TranslationUnitDecl>(Owner) ||
Mike Stump11289f42009-09-09 15:08:12 +00002564 (isa<NamespaceDecl>(Owner) &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002565 cast<NamespaceDecl>(Owner)->getDeclName()))) {
2566 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
2567 Invalid = true;
2568
2569 // Recover by adding 'static'.
John McCall49bfce42009-08-03 20:12:06 +00002570 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
Peter Collingbournede32b202011-02-11 19:59:54 +00002571 PrevSpec, DiagID, getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +00002572 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002573 // C++ [class.union]p3:
2574 // A storage class is not allowed in a declaration of an
2575 // anonymous union in a class scope.
2576 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
2577 isa<RecordDecl>(Owner)) {
Mike Stump11289f42009-09-09 15:08:12 +00002578 Diag(DS.getStorageClassSpecLoc(),
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002579 diag::err_anonymous_union_with_storage_spec);
2580 Invalid = true;
2581
2582 // Recover by removing the storage specifier.
2583 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
Peter Collingbournede32b202011-02-11 19:59:54 +00002584 PrevSpec, DiagID, getLangOptions());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002585 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002586
Douglas Gregor0f8bc972011-05-09 23:05:33 +00002587 // Ignore const/volatile/restrict qualifiers.
2588 if (DS.getTypeQualifiers()) {
2589 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2590 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2591 << Record->isUnion() << 0
2592 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
2593 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2594 Diag(DS.getVolatileSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2595 << Record->isUnion() << 1
2596 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
2597 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
2598 Diag(DS.getRestrictSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2599 << Record->isUnion() << 2
2600 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
2601
2602 DS.ClearTypeQualifiers();
2603 }
2604
Mike Stump11289f42009-09-09 15:08:12 +00002605 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00002606 // The member-specification of an anonymous union shall only
2607 // define non-static data members. [Note: nested types and
2608 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002609 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
2610 MemEnd = Record->decls_end();
Douglas Gregorf4d33272009-01-07 19:46:03 +00002611 Mem != MemEnd; ++Mem) {
2612 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
2613 // C++ [class.union]p3:
2614 // An anonymous union shall not have private or protected
2615 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00002616 assert(FD->getAccess() != AS_none);
2617 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00002618 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
2619 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
2620 Invalid = true;
2621 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00002622
Alexis Hunt97ab5542011-05-16 22:41:40 +00002623 // C++ [class.union]p1
2624 // An object of a class with a non-trivial constructor, a non-trivial
2625 // copy constructor, a non-trivial destructor, or a non-trivial copy
2626 // assignment operator cannot be a member of a union, nor can an
2627 // array of such objects.
2628 if (!getLangOptions().CPlusPlus0x && CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00002629 Invalid = true;
Douglas Gregorf4d33272009-01-07 19:46:03 +00002630 } else if ((*Mem)->isImplicit()) {
2631 // Any implicit members are fine.
Douglas Gregor8761da52009-02-03 00:34:39 +00002632 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
2633 // This is a type that showed up in an
2634 // elaborated-type-specifier inside the anonymous struct or
2635 // union, but which actually declares a type outside of the
2636 // anonymous struct or union. It's okay.
Douglas Gregorf4d33272009-01-07 19:46:03 +00002637 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
2638 if (!MemRecord->isAnonymousStructOrUnion() &&
2639 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00002640 // Visual C++ allows type definition in anonymous struct or union.
2641 if (getLangOptions().Microsoft)
2642 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
2643 << (int)Record->isUnion();
2644 else {
2645 // This is a nested type declaration.
2646 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
2647 << (int)Record->isUnion();
2648 Invalid = true;
2649 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002650 }
Abramo Bagnarad7340582010-06-05 05:09:32 +00002651 } else if (isa<AccessSpecDecl>(*Mem)) {
2652 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00002653 } else {
2654 // We have something that isn't a non-static data
2655 // member. Complain about it.
2656 unsigned DK = diag::err_anonymous_record_bad_member;
2657 if (isa<TypeDecl>(*Mem))
2658 DK = diag::err_anonymous_record_with_type;
2659 else if (isa<FunctionDecl>(*Mem))
2660 DK = diag::err_anonymous_record_with_function;
2661 else if (isa<VarDecl>(*Mem))
2662 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00002663
2664 // Visual C++ allows type definition in anonymous struct or union.
2665 if (getLangOptions().Microsoft &&
2666 DK == diag::err_anonymous_record_with_type)
2667 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00002668 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00002669 else {
2670 Diag((*Mem)->getLocation(), DK)
2671 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00002672 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00002673 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002674 }
2675 }
Mike Stump11289f42009-09-09 15:08:12 +00002676 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002677
2678 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002679 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
2680 << (int)getLangOptions().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002681 Invalid = true;
2682 }
2683
John McCallfa2d6922009-10-22 23:31:08 +00002684 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00002685 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00002686 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00002687 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00002688
Mike Stump11289f42009-09-09 15:08:12 +00002689 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002690 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002691 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002692 Anon = FieldDecl::Create(Context, OwningClass,
2693 DS.getSourceRange().getBegin(),
2694 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002695 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00002696 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00002697 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00002698 /*BitWidth=*/0, /*Mutable=*/false,
2699 /*HasInit=*/false);
John McCallb54367d2010-05-21 20:45:30 +00002700 Anon->setAccess(AS);
Douglas Gregor9d5938a2010-09-28 20:38:10 +00002701 if (getLangOptions().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00002702 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002703 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002704 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
2705 assert(SCSpec != DeclSpec::SCS_typedef &&
2706 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002707 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorc4df4072010-04-19 22:54:31 +00002708 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002709 // mutable can only appear on non-static class members, so it's always
2710 // an error here
2711 Diag(Record->getLocation(), diag::err_mutable_nonmember);
2712 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00002713 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002714 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00002715 SCSpec = DS.getStorageClassSpecAsWritten();
2716 VarDecl::StorageClass SCAsWritten
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002717 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002718
Abramo Bagnaradff19302011-03-08 08:55:46 +00002719 Anon = VarDecl::Create(Context, Owner,
2720 DS.getSourceRange().getBegin(),
2721 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00002722 Context.getTypeDeclType(Record),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002723 TInfo, SC, SCAsWritten);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002724 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002725 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002726
2727 // Add the anonymous struct/union object to the current
2728 // context. We'll be referencing this object when we refer to one of
2729 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002730 Owner->addDecl(Anon);
Douglas Gregor456ad1a2010-05-03 15:18:25 +00002731
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002732 // Inject the members of the anonymous struct/union into the owning
2733 // context and into the identifier resolver chain for name lookup
2734 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002735 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet783dd6e2010-11-21 06:08:52 +00002736 Chain.push_back(Anon);
2737
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002738 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
2739 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002740 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002741
2742 // Mark this as an anonymous struct/union type. Note that we do not
2743 // do this until after we have already checked and injected the
2744 // members of this anonymous struct/union type, because otherwise
2745 // the members could be injected twice: once by DeclContext when it
2746 // builds its lookup table, and once by
Mike Stump11289f42009-09-09 15:08:12 +00002747 // InjectAnonymousStructOrUnionMembers.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002748 Record->setAnonymousStructOrUnion(true);
2749
2750 if (Invalid)
2751 Anon->setInvalidDecl();
2752
John McCall48871652010-08-21 09:40:31 +00002753 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00002754}
2755
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002756/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
2757/// Microsoft C anonymous structure.
2758/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
2759/// Example:
2760///
2761/// struct A { int a; };
2762/// struct B { struct A; int b; };
2763///
2764/// void foo() {
2765/// B var;
2766/// var.a = 3;
2767/// }
2768///
2769Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2770 RecordDecl *Record) {
2771
2772 // If there is no Record, get the record via the typedef.
2773 if (!Record)
2774 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
2775
2776 // Mock up a declarator.
2777 Declarator Dc(DS, Declarator::TypeNameContext);
2778 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2779 assert(TInfo && "couldn't build declarator info for anonymous struct");
2780
2781 // Create a declaration for this anonymous struct.
2782 NamedDecl* Anon = FieldDecl::Create(Context,
2783 cast<RecordDecl>(CurContext),
2784 DS.getSourceRange().getBegin(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002785 DS.getSourceRange().getBegin(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002786 /*IdentifierInfo=*/0,
2787 Context.getTypeDeclType(Record),
2788 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00002789 /*BitWidth=*/0, /*Mutable=*/false,
2790 /*HasInit=*/false);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002791 Anon->setImplicit();
2792
2793 // Add the anonymous struct object to the current context.
2794 CurContext->addDecl(Anon);
2795
2796 // Inject the members of the anonymous struct into the current
2797 // context and into the identifier resolver chain for name lookup
2798 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002799 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002800 Chain.push_back(Anon);
2801
2802 if (InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
2803 Record->getDefinition(),
2804 AS_none, Chain, true))
2805 Anon->setInvalidDecl();
2806
2807 return Anon;
2808}
Steve Naroff2fea1392007-09-02 02:04:30 +00002809
Douglas Gregor92751d42008-11-17 22:58:34 +00002810/// GetNameForDeclarator - Determine the full declaration name for the
2811/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002812DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00002813 return GetNameFromUnqualifiedId(D.getName());
2814}
2815
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002816/// \brief Retrieves the declaration name from a parsed unqualified-id.
2817DeclarationNameInfo
2818Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
2819 DeclarationNameInfo NameInfo;
2820 NameInfo.setLoc(Name.StartLocation);
2821
Douglas Gregor7861a802009-11-03 01:35:08 +00002822 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00002823
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002824 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002825 case UnqualifiedId::IK_Identifier:
2826 NameInfo.setName(Name.Identifier);
2827 NameInfo.setLoc(Name.StartLocation);
2828 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00002829
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002830 case UnqualifiedId::IK_OperatorFunctionId:
2831 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
2832 Name.OperatorFunctionId.Operator));
2833 NameInfo.setLoc(Name.StartLocation);
2834 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
2835 = Name.OperatorFunctionId.SymbolLocations[0];
2836 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
2837 = Name.EndLocation.getRawEncoding();
2838 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002839
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002840 case UnqualifiedId::IK_LiteralOperatorId:
2841 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
2842 Name.Identifier));
2843 NameInfo.setLoc(Name.StartLocation);
2844 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
2845 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002846
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002847 case UnqualifiedId::IK_ConversionFunctionId: {
2848 TypeSourceInfo *TInfo;
2849 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
2850 if (Ty.isNull())
2851 return DeclarationNameInfo();
2852 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
2853 Context.getCanonicalType(Ty)));
2854 NameInfo.setLoc(Name.StartLocation);
2855 NameInfo.setNamedTypeInfo(TInfo);
2856 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00002857 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002858
2859 case UnqualifiedId::IK_ConstructorName: {
2860 TypeSourceInfo *TInfo;
2861 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
2862 if (Ty.isNull())
2863 return DeclarationNameInfo();
2864 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
2865 Context.getCanonicalType(Ty)));
2866 NameInfo.setLoc(Name.StartLocation);
2867 NameInfo.setNamedTypeInfo(TInfo);
2868 return NameInfo;
2869 }
2870
2871 case UnqualifiedId::IK_ConstructorTemplateId: {
2872 // In well-formed code, we can only have a constructor
2873 // template-id that refers to the current context, so go there
2874 // to find the actual type being constructed.
2875 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
2876 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
2877 return DeclarationNameInfo();
2878
2879 // Determine the type of the class being constructed.
2880 QualType CurClassType = Context.getTypeDeclType(CurClass);
2881
2882 // FIXME: Check two things: that the template-id names the same type as
2883 // CurClassType, and that the template-id does not occur when the name
2884 // was qualified.
2885
2886 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
2887 Context.getCanonicalType(CurClassType)));
2888 NameInfo.setLoc(Name.StartLocation);
2889 // FIXME: should we retrieve TypeSourceInfo?
2890 NameInfo.setNamedTypeInfo(0);
2891 return NameInfo;
2892 }
2893
2894 case UnqualifiedId::IK_DestructorName: {
2895 TypeSourceInfo *TInfo;
2896 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
2897 if (Ty.isNull())
2898 return DeclarationNameInfo();
2899 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
2900 Context.getCanonicalType(Ty)));
2901 NameInfo.setLoc(Name.StartLocation);
2902 NameInfo.setNamedTypeInfo(TInfo);
2903 return NameInfo;
2904 }
2905
2906 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00002907 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002908 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
2909 return Context.getNameForTemplate(TName, TNameLoc);
2910 }
2911
2912 } // switch (Name.getKind())
2913
Douglas Gregor92751d42008-11-17 22:58:34 +00002914 assert(false && "Unknown name kind");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002915 return DeclarationNameInfo();
Douglas Gregor92751d42008-11-17 22:58:34 +00002916}
2917
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00002918static QualType getCoreType(QualType Ty) {
2919 do {
2920 if (Ty->isPointerType() || Ty->isReferenceType())
2921 Ty = Ty->getPointeeType();
2922 else if (Ty->isArrayType())
2923 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
2924 else
2925 return Ty.withoutLocalFastQualifiers();
2926 } while (true);
2927}
2928
Douglas Gregor8af63e42009-02-06 17:46:57 +00002929/// isNearlyMatchingFunction - Determine whether the C++ functions
2930/// Declaration and Definition are "nearly" matching. This heuristic
2931/// is used to improve diagnostics in the case where an out-of-line
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00002932/// function definition doesn't match any declaration within the class
2933/// or namespace. Also sets Params to the list of indices to the
2934/// parameters that differ between the declaration and the definition.
Douglas Gregor8af63e42009-02-06 17:46:57 +00002935static bool isNearlyMatchingFunction(ASTContext &Context,
2936 FunctionDecl *Declaration,
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00002937 FunctionDecl *Definition,
2938 llvm::SmallVectorImpl<unsigned> &Params) {
2939 Params.clear();
Douglas Gregorad590502008-12-15 23:53:10 +00002940 if (Declaration->param_size() != Definition->param_size())
2941 return false;
2942 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
2943 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
2944 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
2945
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00002946 // The parameter types are identical
Matt Beaumont-Gay56381b82011-08-23 01:35:51 +00002947 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00002948 continue;
2949
2950 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
2951 QualType DefParamBaseTy = getCoreType(DefParamTy);
2952 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
2953 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
2954
2955 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
2956 (DeclTyName && DeclTyName == DefTyName))
2957 Params.push_back(Idx);
2958 else // The two parameters aren't even close
Douglas Gregorad590502008-12-15 23:53:10 +00002959 return false;
2960 }
2961
2962 return true;
2963}
2964
John McCall99b2fe52010-04-29 23:50:39 +00002965/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
2966/// declarator needs to be rebuilt in the current instantiation.
2967/// Any bits of declarator which appear before the name are valid for
2968/// consideration here. That's specifically the type in the decl spec
2969/// and the base type in any member-pointer chunks.
2970static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
2971 DeclarationName Name) {
2972 // The types we specifically need to rebuild are:
2973 // - typenames, typeofs, and decltypes
2974 // - types which will become injected class names
2975 // Of course, we also need to rebuild any type referencing such a
2976 // type. It's safest to just say "dependent", but we call out a
2977 // few cases here.
2978
2979 DeclSpec &DS = D.getMutableDeclSpec();
2980 switch (DS.getTypeSpecType()) {
2981 case DeclSpec::TST_typename:
2982 case DeclSpec::TST_typeofType:
Alexis Hunt4a257072011-05-19 05:37:45 +00002983 case DeclSpec::TST_decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002984 case DeclSpec::TST_underlyingType: {
John McCall99b2fe52010-04-29 23:50:39 +00002985 // Grab the type from the parser.
2986 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00002987 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00002988 if (T.isNull() || !T->isDependentType()) break;
2989
2990 // Make sure there's a type source info. This isn't really much
2991 // of a waste; most dependent types should have type source info
2992 // attached already.
2993 if (!TSI)
2994 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
2995
2996 // Rebuild the type in the current instantiation.
2997 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
2998 if (!TSI) return true;
2999
3000 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00003001 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
3002 DS.UpdateTypeRep(LocType);
3003 break;
3004 }
3005
3006 case DeclSpec::TST_typeofExpr: {
3007 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00003008 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00003009 if (Result.isInvalid()) return true;
3010 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00003011 break;
3012 }
3013
3014 default:
3015 // Nothing to do for these decl specs.
3016 break;
3017 }
3018
3019 // It doesn't matter what order we do this in.
3020 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3021 DeclaratorChunk &Chunk = D.getTypeObject(I);
3022
3023 // The only type information in the declarator which can come
3024 // before the declaration name is the base type of a member
3025 // pointer.
3026 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
3027 continue;
3028
3029 // Rebuild the scope specifier in-place.
3030 CXXScopeSpec &SS = Chunk.Mem.Scope();
3031 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
3032 return true;
3033 }
3034
3035 return false;
3036}
3037
Anders Carlsson1052fd72011-07-04 16:28:17 +00003038Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00003039 return HandleDeclarator(S, D, MultiTemplateParamsArg(*this),
Anders Carlsson1052fd72011-07-04 16:28:17 +00003040 /*IsFunctionDefinition=*/false);
John McCallde6836a2010-08-24 07:21:54 +00003041}
3042
Richard Smithdda56e42011-04-15 14:24:37 +00003043/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3044/// If T is the name of a class, then each of the following shall have a
3045/// name different from T:
3046/// - every static data member of class T;
3047/// - every member function of class T
3048/// - every member of class T that is itself a type;
3049/// \returns true if the declaration name violates these rules.
3050bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
3051 DeclarationNameInfo NameInfo) {
3052 DeclarationName Name = NameInfo.getName();
3053
3054 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
3055 if (Record->getIdentifier() && Record->getDeclName() == Name) {
3056 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
3057 return true;
3058 }
3059
3060 return false;
3061}
3062
John McCall48871652010-08-21 09:40:31 +00003063Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
3064 MultiTemplateParamsArg TemplateParamLists,
Alexis Hunt5a7fa252011-05-12 06:15:49 +00003065 bool IsFunctionDefinition) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003066 // TODO: consider using NameInfo for diagnostic.
3067 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3068 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00003069
Chris Lattner02c04392007-07-25 00:24:17 +00003070 // All of these full declarators require an identifier. If it doesn't have
3071 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00003072 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003073 if (!D.isInvalidType()) // Reject this if we think it is valid.
Chris Lattner8c5dd732008-11-11 06:13:16 +00003074 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003075 diag::err_declarator_need_ident)
3076 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00003077 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00003078 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
3079 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003080
Chris Lattner1a76a3c2007-08-26 06:24:45 +00003081 // The scope passed in may not be a decl scope. Zip up the scope tree until
3082 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00003083 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00003084 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00003085 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003086
John McCall99b2fe52010-04-29 23:50:39 +00003087 DeclContext *DC = CurContext;
3088 if (D.getCXXScopeSpec().isInvalid())
3089 D.setInvalidType();
3090 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00003091 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
3092 UPPC_DeclarationQualifier))
3093 return 0;
3094
John McCall99b2fe52010-04-29 23:50:39 +00003095 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
3096 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
3097 if (!DC) {
3098 // If we could not compute the declaration context, it's because the
3099 // declaration context is dependent but does not refer to a class,
3100 // class template, or class template partial specialization. Complain
3101 // and return early, to avoid the coming semantic disaster.
3102 Diag(D.getIdentifierLoc(),
3103 diag::err_template_qualified_declarator_no_match)
3104 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
3105 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00003106 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00003107 }
John McCall99b2fe52010-04-29 23:50:39 +00003108 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00003109
John McCall99b2fe52010-04-29 23:50:39 +00003110 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00003111 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00003112 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00003113
Douglas Gregora007d362010-10-13 22:19:53 +00003114 if (isa<CXXRecordDecl>(DC)) {
3115 if (!cast<CXXRecordDecl>(DC)->hasDefinition()) {
3116 Diag(D.getIdentifierLoc(),
3117 diag::err_member_def_undefined_record)
3118 << Name << DC << D.getCXXScopeSpec().getRange();
3119 D.setInvalidType();
3120 } else if (isa<CXXRecordDecl>(CurContext) &&
3121 !D.getDeclSpec().isFriendSpecified()) {
3122 // The user provided a superfluous scope specifier inside a class
3123 // definition:
3124 //
3125 // class X {
3126 // void X::f();
3127 // };
3128 if (CurContext->Equals(DC))
3129 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
3130 << Name << FixItHint::CreateRemoval(D.getCXXScopeSpec().getRange());
3131 else
3132 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3133 << Name << D.getCXXScopeSpec().getRange();
3134
3135 // Pretend that this qualifier was not here.
3136 D.getCXXScopeSpec().clear();
3137 }
John McCall99b2fe52010-04-29 23:50:39 +00003138 }
3139
3140 // Check whether we need to rebuild the type of the given
3141 // declaration in the current instantiation.
3142 if (EnteringContext && IsDependentContext &&
3143 TemplateParamLists.size() != 0) {
3144 ContextRAII SavedContext(*this, DC);
3145 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
3146 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00003147 }
3148 }
Richard Smithdda56e42011-04-15 14:24:37 +00003149
3150 if (DiagnoseClassNameShadow(DC, NameInfo))
3151 // If this is a typedef, we'll end up spewing multiple diagnostics.
3152 // Just return early; it's safer.
3153 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3154 return 0;
Douglas Gregor36c22a22010-10-15 13:21:21 +00003155
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003156 NamedDecl *New;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003157
John McCall8cb7bdf2010-06-04 23:28:52 +00003158 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3159 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00003160
Douglas Gregor506bd562010-12-13 22:49:22 +00003161 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
3162 UPPC_DeclarationType))
3163 D.setInvalidType();
3164
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003165 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00003166 ForRedeclaration);
3167
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003168 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00003169 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00003170 bool IsLinkageLookup = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00003171
3172 // If the declaration we're planning to build will be a function
3173 // or object with linkage, then look for another declaration with
3174 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
3175 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3176 /* Do nothing*/;
3177 else if (R->isFunctionType()) {
Douglas Gregor20749772009-07-07 17:00:05 +00003178 if (CurContext->isFunctionOrMethod() ||
3179 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00003180 IsLinkageLookup = true;
Douglas Gregoreddf4332009-02-24 20:03:32 +00003181 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
John McCall1f82f242009-11-18 22:49:29 +00003182 IsLinkageLookup = true;
Sebastian Redl50c68252010-08-31 00:36:30 +00003183 else if (CurContext->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor20749772009-07-07 17:00:05 +00003184 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00003185 IsLinkageLookup = true;
3186
3187 if (IsLinkageLookup)
3188 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00003189
John McCall1f82f242009-11-18 22:49:29 +00003190 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003191 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00003192 LookupQualifiedName(Previous, DC);
3193
3194 // Don't consider using declarations as previous declarations for
3195 // out-of-line members.
3196 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003197
3198 // C++ 7.3.1.2p2:
3199 // Members (including explicit specializations of templates) of a named
3200 // namespace can also be defined outside that namespace by explicit
3201 // qualification of the name being defined, provided that the entity being
3202 // defined was already declared in the namespace and the definition appears
3203 // after the point of declaration in a namespace that encloses the
3204 // declarations namespace.
3205 //
Douglas Gregorad590502008-12-15 23:53:10 +00003206 // Note that we only check the context at this point. We don't yet
3207 // have enough information to make sure that PrevDecl is actually
3208 // the declaration we want to match. For example, given:
3209 //
Douglas Gregor4287b372008-12-12 08:25:50 +00003210 // class X {
3211 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00003212 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00003213 // };
3214 //
Douglas Gregorad590502008-12-15 23:53:10 +00003215 // void X::f(int) { } // ill-formed
3216 //
3217 // In this case, PrevDecl will point to the overload set
3218 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00003219 // matches.
Douglas Gregor8af63e42009-02-06 17:46:57 +00003220
3221 // First check whether we named the global scope.
3222 if (isa<TranslationUnitDecl>(DC)) {
Mike Stump11289f42009-09-09 15:08:12 +00003223 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
Douglas Gregor8af63e42009-02-06 17:46:57 +00003224 << Name << D.getCXXScopeSpec().getRange();
Sebastian Redlafb8be72009-11-08 11:36:54 +00003225 } else {
3226 DeclContext *Cur = CurContext;
3227 while (isa<LinkageSpecDecl>(Cur))
3228 Cur = Cur->getParent();
3229 if (!Cur->Encloses(DC)) {
3230 // The qualifying scope doesn't enclose the original declaration.
3231 // Emit diagnostic based on current scope.
3232 SourceLocation L = D.getIdentifierLoc();
3233 SourceRange R = D.getCXXScopeSpec().getRange();
3234 if (isa<FunctionDecl>(Cur))
3235 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
3236 else
3237 Diag(L, diag::err_invalid_declarator_scope)
3238 << Name << cast<NamedDecl>(DC) << R;
3239 D.setInvalidType();
3240 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003241 }
3242 }
3243
John McCall1f82f242009-11-18 22:49:29 +00003244 if (Previous.isSingleResult() &&
3245 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00003246 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003247 if (!D.isInvalidType())
John McCall1f82f242009-11-18 22:49:29 +00003248 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
3249 Previous.getFoundDecl()))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003250 D.setInvalidType();
Mike Stump11289f42009-09-09 15:08:12 +00003251
Douglas Gregor5101c242008-12-05 18:15:24 +00003252 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00003253 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00003254 }
3255
Douglas Gregor83a586e2008-04-13 21:07:44 +00003256 // In C++, the previous declaration we find might be a tag type
3257 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00003258 // tag type. Note that this does does not apply if we're declaring a
3259 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00003260 if (Previous.isSingleTagDecl() &&
Douglas Gregorfb034662009-01-28 17:15:10 +00003261 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00003262 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00003263
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003264 bool Redeclaration = false;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003265 bool AddToScope = true;
Chris Lattner01a7c532007-01-25 23:09:03 +00003266 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003267 if (TemplateParamLists.size()) {
3268 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00003269 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003270 }
Mike Stump11289f42009-09-09 15:08:12 +00003271
John McCallbcd03502009-12-07 02:54:59 +00003272 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
Douglas Gregoreddf4332009-02-24 20:03:32 +00003273 } else if (R->isFunctionType()) {
John McCallbcd03502009-12-07 02:54:59 +00003274 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003275 move(TemplateParamLists),
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003276 IsFunctionDefinition, Redeclaration,
3277 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00003278 } else {
John McCallbcd03502009-12-07 02:54:59 +00003279 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregorb09f3d82009-07-22 17:18:37 +00003280 move(TemplateParamLists),
3281 Redeclaration);
Chris Lattner01a7c532007-01-25 23:09:03 +00003282 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003283
3284 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00003285 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003286
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003287 // If this has an identifier and is not an invalid redeclaration or
3288 // function template specialization, add it to the scope stack.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003289 if (New->getDeclName() && AddToScope &&
3290 !(Redeclaration && New->isInvalidDecl()))
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00003291 PushOnScopeChains(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00003292
John McCall48871652010-08-21 09:40:31 +00003293 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00003294}
3295
Eli Friedmana3b1d032009-02-21 00:44:51 +00003296/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3297/// types into constant array types in certain situations which would otherwise
3298/// be errors (for GCC compatibility).
3299static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3300 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003301 bool &SizeIsNegative,
3302 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003303 // This method tries to turn a variable array into a constant
3304 // array even when the size isn't an ICE. This is necessary
3305 // for compatibility with code that depends on gcc's buggy
3306 // constant expression folding, like struct {char x[(int)(char*)2];}
3307 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003308 Oversized = 0;
3309
3310 if (T->isDependentType())
3311 return QualType();
3312
John McCall8ccfcb52009-09-24 19:53:00 +00003313 QualifierCollector Qs;
3314 const Type *Ty = Qs.strip(T);
3315
3316 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003317 QualType Pointee = PTy->getPointeeType();
3318 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003319 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
3320 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003321 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00003322 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00003323 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003324 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003325 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
3326 QualType Inner = PTy->getInnerType();
3327 QualType FixedType =
3328 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
3329 Oversized);
3330 if (FixedType.isNull()) return FixedType;
3331 FixedType = Context.getParenType(FixedType);
3332 return Qs.apply(Context, FixedType);
3333 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00003334
3335 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00003336 if (!VLATy)
3337 return QualType();
3338 // FIXME: We should probably handle this case
3339 if (VLATy->getElementType()->isVariablyModifiedType())
3340 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003341
Eli Friedmana3b1d032009-02-21 00:44:51 +00003342 Expr::EvalResult EvalResult;
3343 if (!VLATy->getSizeExpr() ||
Eli Friedmanadf40d42009-02-26 03:58:54 +00003344 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
3345 !EvalResult.Val.isInt())
Eli Friedmana3b1d032009-02-21 00:44:51 +00003346 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00003347
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003348 // Check whether the array size is negative.
Eli Friedmana3b1d032009-02-21 00:44:51 +00003349 llvm::APSInt &Res = EvalResult.Val.getInt();
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003350 if (Res.isSigned() && Res.isNegative()) {
3351 SizeIsNegative = true;
3352 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00003353 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00003354
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003355 // Check whether the array is too large to be addressed.
3356 unsigned ActiveSizeBits
3357 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
3358 Res);
3359 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
3360 Oversized = Res;
3361 return QualType();
3362 }
3363
3364 return Context.getConstantArrayType(VLATy->getElementType(),
3365 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003366}
3367
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003368/// \brief Register the given locally-scoped external C declaration so
3369/// that it can be found later for redeclarations
Mike Stump11289f42009-09-09 15:08:12 +00003370void
John McCall1f82f242009-11-18 22:49:29 +00003371Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
3372 const LookupResult &Previous,
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003373 Scope *S) {
3374 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
3375 "Decl is not a locally-scoped decl!");
3376 // Note that we have a locally-scoped external with this name.
3377 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
3378
John McCall1f82f242009-11-18 22:49:29 +00003379 if (!Previous.isSingleResult())
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003380 return;
3381
John McCall1f82f242009-11-18 22:49:29 +00003382 NamedDecl *PrevDecl = Previous.getFoundDecl();
3383
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003384 // If there was a previous declaration of this variable, it may be
3385 // in our identifier chain. Update the identifier chain with the new
3386 // declaration.
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003387 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003388 // The previous declaration was found on the identifer resolver
3389 // chain, so remove it from its scope.
Douglas Gregor825faf72011-06-29 21:22:02 +00003390
3391 if (S->isDeclScope(PrevDecl)) {
3392 // Special case for redeclarations in the SAME scope.
3393 // Because this declaration is going to be added to the identifier chain
3394 // later, we should temporarily take it OFF the chain.
3395 IdResolver.RemoveDecl(ND);
3396
3397 } else {
3398 // Find the scope for the original declaration.
3399 while (S && !S->isDeclScope(PrevDecl))
3400 S = S->getParent();
3401 }
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003402
3403 if (S)
John McCall48871652010-08-21 09:40:31 +00003404 S->RemoveDecl(PrevDecl);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003405 }
3406}
3407
Douglas Gregordc5c9582011-07-28 14:20:37 +00003408llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3409Sema::findLocallyScopedExternalDecl(DeclarationName Name) {
3410 if (ExternalSource) {
3411 // Load locally-scoped external decls from the external source.
3412 SmallVector<NamedDecl *, 4> Decls;
3413 ExternalSource->ReadLocallyScopedExternalDecls(Decls);
3414 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
3415 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3416 = LocallyScopedExternalDecls.find(Decls[I]->getDeclName());
3417 if (Pos == LocallyScopedExternalDecls.end())
3418 LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I];
3419 }
3420 }
3421
3422 return LocallyScopedExternalDecls.find(Name);
3423}
3424
Eli Friedman574c7452009-04-07 19:37:57 +00003425/// \brief Diagnose function specifiers on a declaration of an identifier that
3426/// does not identify a function.
3427void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
3428 // FIXME: We should probably indicate the identifier in question to avoid
3429 // confusion for constructs like "inline int a(), b;"
3430 if (D.getDeclSpec().isInlineSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003431 Diag(D.getDeclSpec().getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003432 diag::err_inline_non_function);
3433
3434 if (D.getDeclSpec().isVirtualSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003435 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003436 diag::err_virtual_non_function);
3437
3438 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003439 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003440 diag::err_explicit_non_function);
3441}
3442
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003443NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003444Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCallbcd03502009-12-07 02:54:59 +00003445 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00003446 LookupResult &Previous, bool &Redeclaration) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003447 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
3448 if (D.getCXXScopeSpec().isSet()) {
3449 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
3450 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003451 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003452 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00003453 DC = CurContext;
3454 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003455 }
3456
Douglas Gregor0c880302009-03-11 23:00:04 +00003457 if (getLangOptions().CPlusPlus) {
3458 // Check that there are no default arguments (C++ only).
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003459 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00003460 }
3461
Eli Friedman574c7452009-04-07 19:37:57 +00003462 DiagnoseFunctionSpecifiers(D);
3463
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003464 if (D.getDeclSpec().isThreadSpecified())
3465 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Richard Smitha77a0a62011-08-15 21:04:07 +00003466 if (D.getDeclSpec().isConstexprSpecified())
3467 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
3468 << 1;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003469
Douglas Gregord8f446f2010-07-13 06:37:01 +00003470 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
3471 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
3472 << D.getName().getSourceRange();
3473 return 0;
3474 }
3475
John McCallbcd03502009-12-07 02:54:59 +00003476 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003477 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003478
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003479 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00003480 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00003481
Richard Smith3f1b5d02011-05-05 21:57:07 +00003482 CheckTypedefForVariablyModifiedType(S, NewTD);
3483
Richard Smithdda56e42011-04-15 14:24:37 +00003484 return ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
3485}
3486
Richard Smith3f1b5d02011-05-05 21:57:07 +00003487void
3488Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00003489 // C99 6.7.7p2: If a typedef name specifies a variably modified type
3490 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00003491 // Note that variably modified types must be fixed before merging the decl so
3492 // that redeclarations will match.
Chris Lattner9fecd742009-04-19 05:21:20 +00003493 QualType T = NewTD->getUnderlyingType();
3494 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00003495 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00003496
Chris Lattner9fecd742009-04-19 05:21:20 +00003497 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003498 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003499 llvm::APSInt Oversized;
Eli Friedmana3b1d032009-02-21 00:44:51 +00003500 QualType FixedTy =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003501 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3502 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003503 if (!FixedTy.isNull()) {
Richard Smithdda56e42011-04-15 14:24:37 +00003504 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
John McCallbcd03502009-12-07 02:54:59 +00003505 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
Eli Friedmana3b1d032009-02-21 00:44:51 +00003506 } else {
3507 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00003508 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003509 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00003510 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003511 else if (Oversized.getBoolValue())
Richard Smithdda56e42011-04-15 14:24:37 +00003512 Diag(NewTD->getLocation(), diag::err_array_too_large) << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003513 else
Richard Smithdda56e42011-04-15 14:24:37 +00003514 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003515 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00003516 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003517 }
3518 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003519}
Douglas Gregor27821ce2009-07-07 16:35:42 +00003520
Richard Smith3f1b5d02011-05-05 21:57:07 +00003521
3522/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
3523/// declares a typedef-name, either using the 'typedef' type specifier or via
3524/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
3525NamedDecl*
3526Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
3527 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00003528 // Merge the decl with the existing one if appropriate. If the decl is
3529 // in an outer scope, it isn't the same thing.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003530 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
Douglas Gregordb446112011-03-07 16:54:27 +00003531 /*ExplicitInstantiationOrSpecialization=*/false);
Eli Friedman88f4ed92010-08-10 03:13:15 +00003532 if (!Previous.empty()) {
3533 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00003534 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00003535 }
3536
Douglas Gregor27821ce2009-07-07 16:35:42 +00003537 // If this is the C FILE type, notify the AST context.
3538 if (IdentifierInfo *II = NewTD->getIdentifier())
3539 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003540 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00003541 if (II->isStr("FILE"))
3542 Context.setFILEDecl(NewTD);
3543 else if (II->isStr("jmp_buf"))
3544 Context.setjmp_bufDecl(NewTD);
3545 else if (II->isStr("sigjmp_buf"))
3546 Context.setsigjmp_bufDecl(NewTD);
Douglas Gregor2c2c4cd2010-10-05 15:41:24 +00003547 else if (II->isStr("__builtin_va_list"))
3548 Context.setBuiltinVaListType(Context.getTypedefType(NewTD));
Mike Stumpa4de80b2009-07-28 02:25:19 +00003549 }
3550
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003551 return NewTD;
3552}
3553
Douglas Gregor5d68a202009-02-24 19:23:27 +00003554/// \brief Determines whether the given declaration is an out-of-scope
3555/// previous declaration.
3556///
3557/// This routine should be invoked when name lookup has found a
3558/// previous declaration (PrevDecl) that is not in the scope where a
3559/// new declaration by the same name is being introduced. If the new
3560/// declaration occurs in a local scope, previous declarations with
3561/// linkage may still be considered previous declarations (C99
3562/// 6.2.2p4-5, C++ [basic.link]p6).
3563///
3564/// \param PrevDecl the previous declaration found by name
3565/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00003566///
Douglas Gregor5d68a202009-02-24 19:23:27 +00003567/// \param DC the context in which the new declaration is being
3568/// declared.
3569///
3570/// \returns true if PrevDecl is an out-of-scope previous declaration
3571/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00003572static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00003573isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
3574 ASTContext &Context) {
3575 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00003576 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00003577
Douglas Gregoreddf4332009-02-24 20:03:32 +00003578 if (!PrevDecl->hasLinkage())
3579 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00003580
3581 if (Context.getLangOptions().CPlusPlus) {
3582 // C++ [basic.link]p6:
3583 // If there is a visible declaration of an entity with linkage
3584 // having the same name and type, ignoring entities declared
3585 // outside the innermost enclosing namespace scope, the block
3586 // scope declaration declares that same entity and receives the
3587 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00003588 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00003589 if (!OuterContext->isFunctionOrMethod())
3590 // This rule only applies to block-scope declarations.
3591 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00003592
3593 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
3594 if (PrevOuterContext->isRecord())
3595 // We found a member function: ignore it.
3596 return false;
3597
3598 // Find the innermost enclosing namespace for the new and
3599 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00003600 OuterContext = OuterContext->getEnclosingNamespaceContext();
3601 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00003602
Douglas Gregorfcee9462010-08-27 22:55:10 +00003603 // The previous declaration is in a different namespace, so it
3604 // isn't the same function.
3605 if (!OuterContext->Equals(PrevOuterContext))
3606 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00003607 }
3608
Douglas Gregor5d68a202009-02-24 19:23:27 +00003609 return true;
3610}
3611
John McCall3e11ebe2010-03-15 10:12:16 +00003612static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
3613 CXXScopeSpec &SS = D.getCXXScopeSpec();
3614 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00003615 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00003616}
3617
John McCall31168b02011-06-15 23:02:42 +00003618bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
3619 QualType type = decl->getType();
3620 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
3621 if (lifetime == Qualifiers::OCL_Autoreleasing) {
3622 // Various kinds of declaration aren't allowed to be __autoreleasing.
3623 unsigned kind = -1U;
3624 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3625 if (var->hasAttr<BlocksAttr>())
3626 kind = 0; // __block
3627 else if (!var->hasLocalStorage())
3628 kind = 1; // global
3629 } else if (isa<ObjCIvarDecl>(decl)) {
3630 kind = 3; // ivar
3631 } else if (isa<FieldDecl>(decl)) {
3632 kind = 2; // field
3633 }
3634
3635 if (kind != -1U) {
3636 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
3637 << kind;
3638 }
3639 } else if (lifetime == Qualifiers::OCL_None) {
3640 // Try to infer lifetime.
3641 if (!type->isObjCLifetimeType())
3642 return false;
3643
3644 lifetime = type->getObjCARCImplicitLifetime();
3645 type = Context.getLifetimeQualifiedType(type, lifetime);
3646 decl->setType(type);
3647 }
3648
3649 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3650 // Thread-local variables cannot have lifetime.
3651 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
3652 var->isThreadSpecified()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003653 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00003654 << var->getType();
3655 return true;
3656 }
3657 }
3658
3659 return false;
3660}
3661
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003662NamedDecl*
Chris Lattner88fdea82010-10-10 18:16:20 +00003663Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
John McCallbcd03502009-12-07 02:54:59 +00003664 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00003665 LookupResult &Previous,
Douglas Gregorb09f3d82009-07-22 17:18:37 +00003666 MultiTemplateParamsArg TemplateParamLists,
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003667 bool &Redeclaration) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003668 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003669
3670 // Check that there are no default arguments (C++ only).
3671 if (getLangOptions().CPlusPlus)
3672 CheckExtraCXXDefaultArguments(D);
3673
Douglas Gregorc4df4072010-04-19 22:54:31 +00003674 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
3675 assert(SCSpec != DeclSpec::SCS_typedef &&
3676 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00003677 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003678 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003679 // mutable can only appear on non-static class members, so it's always
3680 // an error here
3681 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003682 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003683 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003684 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00003685 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3686 VarDecl::StorageClass SCAsWritten
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00003687 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003688
3689 IdentifierInfo *II = Name.getAsIdentifierInfo();
3690 if (!II) {
3691 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
3692 << Name.getAsString();
3693 return 0;
3694 }
3695
Eli Friedman574c7452009-04-07 19:37:57 +00003696 DiagnoseFunctionSpecifiers(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00003697
Douglas Gregor212cab32009-03-11 20:22:50 +00003698 if (!DC->isRecord() && S->getFnParent() == 0) {
3699 // C99 6.9p2: The storage-class specifiers auto and register shall not
3700 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00003701 if (SC == SC_Auto || SC == SC_Register) {
Mike Stump11289f42009-09-09 15:08:12 +00003702
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00003703 // If this is a register variable with an asm label specified, then this
3704 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00003705 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00003706 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
3707 else
3708 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003709 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003710 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003711 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003712
Ted Kremenek582a0992011-01-23 17:04:59 +00003713 bool isExplicitSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003714 VarDecl *NewVD;
3715 if (!getLangOptions().CPlusPlus) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003716 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
3717 D.getIdentifierLoc(), II,
3718 R, TInfo, SC, SCAsWritten);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003719
3720 if (D.isInvalidType())
3721 NewVD->setInvalidDecl();
3722 } else {
3723 if (DC->isRecord() && !CurContext->isRecord()) {
3724 // This is an out-of-line definition of a static data member.
3725 if (SC == SC_Static) {
3726 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3727 diag::err_static_out_of_line)
3728 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3729 } else if (SC == SC_None)
3730 SC = SC_Static;
Anders Carlssond2e8adf2009-06-24 00:28:53 +00003731 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003732 if (SC == SC_Static) {
3733 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
3734 if (RD->isLocalClass())
3735 Diag(D.getIdentifierLoc(),
3736 diag::err_static_data_member_not_allowed_in_local_class)
3737 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003738
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003739 // C++ [class.union]p1: If a union contains a static data member,
3740 // the program is ill-formed.
3741 //
3742 // We also disallow static data members in anonymous structs.
3743 if (CurContext->isRecord() && (RD->isUnion() || !RD->getDeclName()))
3744 Diag(D.getIdentifierLoc(),
3745 diag::err_static_data_member_not_allowed_in_union_or_anon_struct)
3746 << Name << RD->isUnion();
3747 }
3748 }
3749
3750 // Match up the template parameter lists with the scope specifier, then
3751 // determine whether we have a template or a template specialization.
3752 isExplicitSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003753 bool Invalid = false;
3754 if (TemplateParameterList *TemplateParams
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003755 = MatchTemplateParametersToScopeSpecifier(
Douglas Gregor972fe532011-05-10 18:27:06 +00003756 D.getDeclSpec().getSourceRange().getBegin(),
3757 D.getIdentifierLoc(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003758 D.getCXXScopeSpec(),
John McCallace48cd2010-10-19 01:40:49 +00003759 TemplateParamLists.get(),
3760 TemplateParamLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003761 /*never a friend*/ false,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003762 isExplicitSpecialization,
3763 Invalid)) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003764 if (TemplateParams->size() > 0) {
3765 // There is no such thing as a variable template.
3766 Diag(D.getIdentifierLoc(), diag::err_template_variable)
3767 << II
3768 << SourceRange(TemplateParams->getTemplateLoc(),
3769 TemplateParams->getRAngleLoc());
3770 return 0;
3771 } else {
3772 // There is an extraneous 'template<>' for this variable. Complain
3773 // about it, but allow the declaration of the variable.
3774 Diag(TemplateParams->getTemplateLoc(),
3775 diag::err_template_variable_noparams)
3776 << II
3777 << SourceRange(TemplateParams->getTemplateLoc(),
3778 TemplateParams->getRAngleLoc());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003779 }
Douglas Gregorb09f3d82009-07-22 17:18:37 +00003780 }
Mike Stump11289f42009-09-09 15:08:12 +00003781
Abramo Bagnaradff19302011-03-08 08:55:46 +00003782 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
3783 D.getIdentifierLoc(), II,
3784 R, TInfo, SC, SCAsWritten);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003785
Richard Smithb2bc2e62011-02-21 20:05:19 +00003786 // If this decl has an auto type in need of deduction, make a note of the
3787 // Decl so we can diagnose uses of it in its own initializer.
3788 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
3789 R->getContainedAutoType())
3790 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00003791
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003792 if (D.isInvalidType() || Invalid)
3793 NewVD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003794
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003795 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00003796
Abramo Bagnara60804e12011-03-18 15:16:37 +00003797 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003798 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00003799 TemplateParamLists.size(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003800 TemplateParamLists.release());
3801 }
Richard Smitha77a0a62011-08-15 21:04:07 +00003802
3803 if (D.getDeclSpec().isConstexprSpecified()) {
3804 // FIXME: check this is a valid use of constexpr.
3805 NewVD->setConstexpr(true);
3806 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003807 }
3808
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003809 if (D.getDeclSpec().isThreadSpecified()) {
3810 if (NewVD->hasLocalStorage())
3811 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
Douglas Gregore8bbc122011-09-02 00:18:52 +00003812 else if (!Context.getTargetInfo().isTLSSupported())
Eli Friedmandaea3f62009-04-19 21:48:33 +00003813 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003814 else
3815 NewVD->setThreadSpecified(true);
3816 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003817
Douglas Gregor26701a42011-09-09 02:06:17 +00003818 if (D.getDeclSpec().isModulePrivateSpecified())
3819 NewVD->setModulePrivate();
3820
Douglas Gregor04e9a032009-03-11 23:52:16 +00003821 // Set the lexical context. If the declarator has a C++ scope specifier, the
3822 // lexical context will be different from the semantic context.
3823 NewVD->setLexicalDeclContext(CurContext);
3824
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003825 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00003826 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003827
John McCall31168b02011-06-15 23:02:42 +00003828 // In auto-retain/release, infer strong retension for variables of
3829 // retainable type.
3830 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
3831 NewVD->setInvalidDecl();
3832
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003833 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00003834 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003835 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00003836 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003837 StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00003838 if (S->getFnParent() != 0) {
3839 switch (SC) {
3840 case SC_None:
3841 case SC_Auto:
3842 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
3843 break;
3844 case SC_Register:
Douglas Gregore8bbc122011-09-02 00:18:52 +00003845 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara13392232011-01-11 15:16:52 +00003846 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
3847 break;
3848 case SC_Static:
3849 case SC_Extern:
3850 case SC_PrivateExtern:
3851 break;
3852 }
3853 }
3854
3855 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindola478abca2011-01-01 21:47:03 +00003856 Context, Label));
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003857 }
3858
John McCalla2a3f7d2010-03-16 21:48:18 +00003859 // Diagnose shadowed variables before filtering for scope.
John McCall2d8c7602010-03-20 04:12:52 +00003860 if (!D.getCXXScopeSpec().isSet())
John McCalldf8b37c2010-03-22 09:20:08 +00003861 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00003862
John McCall1f82f242009-11-18 22:49:29 +00003863 // Don't consider existing declarations that are in a different
3864 // scope and are out-of-semantic-context declarations (if the new
3865 // declaration has linkage).
Richard Smith3f1b5d02011-05-05 21:57:07 +00003866 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
Douglas Gregordb446112011-03-07 16:54:27 +00003867 isExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00003868
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003869 if (!getLangOptions().CPlusPlus)
3870 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
3871 else {
3872 // Merge the decl with the existing one if appropriate.
3873 if (!Previous.empty()) {
3874 if (Previous.isSingleResult() &&
3875 isa<FieldDecl>(Previous.getFoundDecl()) &&
3876 D.getCXXScopeSpec().isSet()) {
3877 // The user tried to define a non-static data member
3878 // out-of-line (C++ [dcl.meaning]p1).
3879 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
3880 << D.getCXXScopeSpec().getRange();
3881 Previous.clear();
3882 NewVD->setInvalidDecl();
3883 }
3884 } else if (D.getCXXScopeSpec().isSet()) {
3885 // No previous declaration in the qualifying scope.
3886 Diag(D.getIdentifierLoc(), diag::err_no_member)
3887 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003888 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003889 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003890 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003891
3892 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
3893
3894 // This is an explicit specialization of a static data member. Check it.
3895 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
3896 CheckMemberSpecialization(NewVD, Previous))
3897 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003898 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003899
Ryan Flynne5dc8592009-07-25 22:29:44 +00003900 // attributes declared post-definition are currently ignored
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003901 // FIXME: This should be handled in attribute merging, not
3902 // here.
John McCall1f82f242009-11-18 22:49:29 +00003903 if (Previous.isSingleResult()) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00003904 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
3905 if (Def && (Def = Def->getDefinition()) &&
3906 Def != NewVD && D.hasAttributes()) {
Ryan Flynne5dc8592009-07-25 22:29:44 +00003907 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
3908 Diag(Def->getLocation(), diag::note_previous_definition);
3909 }
3910 }
3911
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003912 // If this is a locally-scoped extern C variable, update the map of
3913 // such variables.
Douglas Gregor16618f22009-09-12 00:17:51 +00003914 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003915 !NewVD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00003916 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003917
Eli Friedman570024a2010-08-05 06:57:20 +00003918 // If there's a #pragma GCC visibility in scope, and this isn't a class
3919 // member, set the visibility of this variable.
3920 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
3921 AddPushedVisibilityAttribute(NewVD);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003922
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00003923 MarkUnusedFileScopedDecl(NewVD);
3924
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003925 return NewVD;
3926}
3927
John McCalldf8b37c2010-03-22 09:20:08 +00003928/// \brief Diagnose variable or built-in function shadowing. Implements
3929/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00003930///
John McCalldf8b37c2010-03-22 09:20:08 +00003931/// This method is called whenever a VarDecl is added to a "useful"
3932/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00003933///
John McCall2d8c7602010-03-20 04:12:52 +00003934/// \param S the scope in which the shadowing name is being declared
3935/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00003936///
John McCalldf8b37c2010-03-22 09:20:08 +00003937void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00003938 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003939 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
3940 Diagnostic::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00003941 return;
3942
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00003943 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00003944 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00003945 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00003946
3947 DeclContext *NewDC = D->getDeclContext();
3948
John McCall2d8c7602010-03-20 04:12:52 +00003949 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00003950 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00003951 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00003952
John McCalla2a3f7d2010-03-16 21:48:18 +00003953 NamedDecl* ShadowedDecl = R.getFoundDecl();
3954 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
3955 return;
3956
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00003957 // Fields are not shadowed by variables in C++ static methods.
3958 if (isa<FieldDecl>(ShadowedDecl))
3959 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
3960 if (MD->isStatic())
3961 return;
3962
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00003963 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
3964 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00003965 // For shadowing external vars, make sure that we point to the global
3966 // declaration, not a locally scoped extern declaration.
3967 for (VarDecl::redecl_iterator
3968 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
3969 I != E; ++I)
3970 if (I->isFileVarDecl()) {
3971 ShadowedDecl = *I;
3972 break;
3973 }
3974 }
3975
3976 DeclContext *OldDC = ShadowedDecl->getDeclContext();
3977
John McCall2d8c7602010-03-20 04:12:52 +00003978 // Only warn about certain kinds of shadowing for class members.
3979 if (NewDC && NewDC->isRecord()) {
3980 // In particular, don't warn about shadowing non-class members.
3981 if (!OldDC->isRecord())
3982 return;
3983
3984 // TODO: should we warn about static data members shadowing
3985 // static data members from base classes?
3986
3987 // TODO: don't diagnose for inaccessible shadowed members.
3988 // This is hard to do perfectly because we might friend the
3989 // shadowing context, but that's just a false negative.
3990 }
3991
3992 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00003993 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00003994 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00003995 if (isa<FieldDecl>(ShadowedDecl))
3996 Kind = 3; // field
3997 else
3998 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00003999 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00004000 Kind = 1; // global
4001 else
4002 Kind = 0; // local
4003
John McCall2d8c7602010-03-20 04:12:52 +00004004 DeclarationName Name = R.getLookupName();
4005
John McCalla2a3f7d2010-03-16 21:48:18 +00004006 // Emit warning and note.
John McCall2d8c7602010-03-20 04:12:52 +00004007 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00004008 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
4009}
4010
John McCalldf8b37c2010-03-22 09:20:08 +00004011/// \brief Check -Wshadow without the advantage of a previous lookup.
4012void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004013 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
4014 Diagnostic::Ignored)
4015 return;
4016
John McCalldf8b37c2010-03-22 09:20:08 +00004017 LookupResult R(*this, D->getDeclName(), D->getLocation(),
4018 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4019 LookupName(R, S);
4020 CheckShadow(S, D, R);
4021}
4022
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004023/// \brief Perform semantic checking on a newly-created variable
4024/// declaration.
4025///
4026/// This routine performs all of the type-checking required for a
Douglas Gregorf16a8a72009-05-01 15:47:09 +00004027/// variable declaration once it has been built. It is used both to
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004028/// check variables after they have been parsed and their declarators
Douglas Gregorf16a8a72009-05-01 15:47:09 +00004029/// have been translated into a declaration, and to check variables
4030/// that have been instantiated from a template.
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004031///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004032/// Sets NewVD->isInvalidDecl() if an error was encountered.
John McCall1f82f242009-11-18 22:49:29 +00004033void Sema::CheckVariableDeclaration(VarDecl *NewVD,
4034 LookupResult &Previous,
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004035 bool &Redeclaration) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004036 // If the decl is already known invalid, don't check it.
4037 if (NewVD->isInvalidDecl())
4038 return;
Mike Stump11289f42009-09-09 15:08:12 +00004039
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004040 QualType T = NewVD->getType();
4041
John McCall8b07ec22010-05-15 11:32:37 +00004042 if (T->isObjCObjectType()) {
Fariborz Jahanian9a14c212011-07-25 21:12:27 +00004043 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
4044 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00004045 T = Context.getObjCObjectPointerType(T);
4046 NewVD->setType(T);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004047 }
Mike Stump11289f42009-09-09 15:08:12 +00004048
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004049 // Emit an error if an address space was applied to decl with local storage.
4050 // This includes arrays of objects with address space qualifiers, but not
4051 // automatic variables that point to other address spaces.
4052 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00004053 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004054 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004055 return NewVD->setInvalidDecl();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004056 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00004057
Mike Stumpca5ae662009-04-14 00:57:29 +00004058 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00004059 && !NewVD->hasAttr<BlocksAttr>()) {
4060 if (getLangOptions().getGCMode() != LangOptions::NonGC)
4061 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
4062 else
4063 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
4064 }
Chris Lattner88fdea82010-10-10 18:16:20 +00004065
Chris Lattner9fecd742009-04-19 05:21:20 +00004066 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00004067 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00004068 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00004069 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004070
Chris Lattner9fecd742009-04-19 05:21:20 +00004071 if ((isVM && NewVD->hasLinkage()) ||
4072 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00004073 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004074 llvm::APSInt Oversized;
Anders Carlsson6c885802009-02-28 21:56:50 +00004075 QualType FixedTy =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004076 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
4077 Oversized);
Mike Stump11289f42009-09-09 15:08:12 +00004078
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004079 if (FixedTy.isNull() && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004080 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00004081 // FIXME: This won't give the correct result for
4082 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00004083 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004084
Anders Carlsson6c885802009-02-28 21:56:50 +00004085 if (NewVD->isFileVarDecl())
4086 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004087 << SizeRange;
John McCall8e7d6562010-08-26 03:08:43 +00004088 else if (NewVD->getStorageClass() == SC_Static)
Anders Carlsson6c885802009-02-28 21:56:50 +00004089 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004090 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00004091 else
4092 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004093 << SizeRange;
4094 return NewVD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004095 }
4096
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004097 if (FixedTy.isNull()) {
Anders Carlsson6c885802009-02-28 21:56:50 +00004098 if (NewVD->isFileVarDecl())
4099 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
4100 else
4101 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004102 return NewVD->setInvalidDecl();
Anders Carlsson6c885802009-02-28 21:56:50 +00004103 }
Mike Stump11289f42009-09-09 15:08:12 +00004104
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004105 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
4106 NewVD->setType(FixedTy);
Anders Carlsson6c885802009-02-28 21:56:50 +00004107 }
4108
John McCall1f82f242009-11-18 22:49:29 +00004109 if (Previous.empty() && NewVD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004110 // Since we did not find anything by this name and we're declaring
4111 // an extern "C" variable, look for a non-visible extern "C"
4112 // declaration with the same name.
4113 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregordc5c9582011-07-28 14:20:37 +00004114 = findLocallyScopedExternalDecl(NewVD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004115 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00004116 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004117 }
4118
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004119 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004120 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
4121 << T;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004122 return NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004123 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004124
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004125 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00004126 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
4127 return NewVD->setInvalidDecl();
4128 }
Mike Stump11289f42009-09-09 15:08:12 +00004129
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004130 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpa7128632009-05-01 23:41:47 +00004131 Diag(NewVD->getLocation(), diag::err_block_on_vm);
4132 return NewVD->setInvalidDecl();
4133 }
4134
Sebastian Redl5467c9f2010-07-12 23:11:43 +00004135 // Function pointers and references cannot have qualified function type, only
4136 // function pointer-to-members can do that.
4137 QualType Pointee;
4138 unsigned PtrOrRef = 0;
4139 if (const PointerType *Ptr = T->getAs<PointerType>())
4140 Pointee = Ptr->getPointeeType();
4141 else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
4142 Pointee = Ref->getPointeeType();
4143 PtrOrRef = 1;
4144 }
4145 if (!Pointee.isNull() && Pointee->isFunctionProtoType() &&
4146 Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) {
4147 Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer)
4148 << PtrOrRef;
4149 return NewVD->setInvalidDecl();
4150 }
4151
John McCall1f82f242009-11-18 22:49:29 +00004152 if (!Previous.empty()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00004153 Redeclaration = true;
John McCall1f82f242009-11-18 22:49:29 +00004154 MergeVarDecl(NewVD, Previous);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004155 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004156}
4157
Douglas Gregor36d1b142009-10-06 17:59:45 +00004158/// \brief Data used with FindOverriddenMethod
4159struct FindOverriddenMethodData {
4160 Sema *S;
4161 CXXMethodDecl *Method;
4162};
4163
4164/// \brief Member lookup function that determines whether a given C++
4165/// method overrides a method in a base class, to be used with
4166/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00004167static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00004168 CXXBasePath &Path,
4169 void *UserData) {
4170 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00004171
Douglas Gregor36d1b142009-10-06 17:59:45 +00004172 FindOverriddenMethodData *Data
4173 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00004174
4175 DeclarationName Name = Data->Method->getDeclName();
4176
4177 // FIXME: Do we care about other names here too?
4178 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00004179 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00004180 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
4181 CanQualType CT = Data->S->Context.getCanonicalType(T);
4182
Anders Carlsson5a4f7722009-11-27 01:26:58 +00004183 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00004184 }
4185
4186 for (Path.Decls = BaseRecord->lookup(Name);
Douglas Gregor36d1b142009-10-06 17:59:45 +00004187 Path.Decls.first != Path.Decls.second;
4188 ++Path.Decls.first) {
John McCall38e5f432010-06-16 09:33:39 +00004189 NamedDecl *D = *Path.Decls.first;
John McCalle9cccd82010-06-16 08:42:20 +00004190 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4191 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00004192 return true;
4193 }
4194 }
4195
4196 return false;
4197}
4198
Sebastian Redld5b24532009-11-18 21:51:29 +00004199/// AddOverriddenMethods - See if a method overrides any in the base classes,
4200/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004201bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00004202 // Look for virtual methods in base classes that this method might override.
4203 CXXBasePaths Paths;
4204 FindOverriddenMethodData Data;
4205 Data.Method = MD;
4206 Data.S = this;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004207 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00004208 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
4209 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
4210 E = Paths.found_decls_end(); I != E; ++I) {
4211 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00004212 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00004213 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Alexis Hunt96d5c762009-11-21 08:43:09 +00004214 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00004215 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004216 AddedAny = true;
4217 }
Sebastian Redld5b24532009-11-18 21:51:29 +00004218 }
4219 }
4220 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004221
4222 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00004223}
4224
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004225static void DiagnoseInvalidRedeclaration(Sema &S, FunctionDecl *NewFD,
4226 bool isFriendDecl) {
4227 DeclarationName Name = NewFD->getDeclName();
4228 DeclContext *DC = NewFD->getDeclContext();
4229 LookupResult Prev(S, Name, NewFD->getLocation(),
John McCallf7cfb222010-10-13 05:45:15 +00004230 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004231 llvm::SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004232 llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
4233 TypoCorrection Correction;
4234 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
4235 : diag::err_member_def_does_not_match;
4236
4237 NewFD->setInvalidDecl();
4238 S.LookupQualifiedName(Prev, DC);
John McCallf7cfb222010-10-13 05:45:15 +00004239 assert(!Prev.isAmbiguous() &&
4240 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004241 if (!Prev.empty()) {
4242 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
4243 Func != FuncEnd; ++Func) {
4244 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
4245 if (FD && isNearlyMatchingFunction(S.Context, FD, NewFD,
4246 MismatchedParams)) {
4247 // Add 1 to the index so that 0 can mean the mismatch didn't
4248 // involve a parameter
4249 unsigned ParamNum =
4250 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
4251 NearMatches.push_back(std::make_pair(FD, ParamNum));
4252 }
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004253 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004254 // If the qualified name lookup yielded nothing, try typo correction
4255 } else if ((Correction = S.CorrectTypo(Prev.getLookupNameInfo(),
Kaelyn Uhrain40aa7c92011-08-18 21:57:36 +00004256 Prev.getLookupKind(), 0, 0, DC)) &&
4257 Correction.getCorrection() != Name) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004258 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
4259 : diag::err_member_def_does_not_match_suggest;
4260 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
4261 CDeclEnd = Correction.end();
4262 CDecl != CDeclEnd; ++CDecl) {
4263 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
4264 if (FD && isNearlyMatchingFunction(S.Context, FD, NewFD,
4265 MismatchedParams)) {
4266 // Add 1 to the index so that 0 can mean the mismatch didn't
4267 // involve a parameter
4268 unsigned ParamNum =
4269 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
4270 NearMatches.push_back(std::make_pair(FD, ParamNum));
4271 }
4272 }
4273 }
4274
4275 if (Correction)
4276 S.Diag(NewFD->getLocation(), DiagMsg)
4277 << Name << DC << Correction.getQuoted(S.getLangOptions())
4278 << FixItHint::CreateReplacement(
4279 NewFD->getLocation(), Correction.getAsString(S.getLangOptions()));
4280 else
4281 S.Diag(NewFD->getLocation(), DiagMsg) << Name << DC << NewFD->getLocation();
4282
4283 for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
4284 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
4285 NearMatch != NearMatchEnd; ++NearMatch) {
4286 FunctionDecl *FD = NearMatch->first;
4287
4288 if (unsigned Idx = NearMatch->second) {
4289 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
4290 S.Diag(FDParam->getTypeSpecStartLoc(),
4291 diag::note_member_def_close_param_match)
4292 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
4293 } else if (Correction) {
4294 S.Diag(FD->getLocation(), diag::note_previous_decl)
4295 << Correction.getQuoted(S.getLangOptions());
4296 } else
4297 S.Diag(FD->getLocation(), diag::note_member_def_close_match);
John McCallf7cfb222010-10-13 05:45:15 +00004298 }
4299}
4300
Mike Stump11289f42009-09-09 15:08:12 +00004301NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00004302Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
John McCallbcd03502009-12-07 02:54:59 +00004303 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00004304 LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004305 MultiTemplateParamsArg TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004306 bool IsFunctionDefinition, bool &Redeclaration,
4307 bool &AddToScope) {
Zhongxing Xubece5d62009-01-16 01:13:29 +00004308 assert(R.getTypePtr()->isFunctionType());
4309
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004310 // TODO: consider using NameInfo for diagnostic.
4311 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4312 DeclarationName Name = NameInfo.getName();
John McCall8e7d6562010-08-26 03:08:43 +00004313 FunctionDecl::StorageClass SC = SC_None;
Zhongxing Xubece5d62009-01-16 01:13:29 +00004314 switch (D.getDeclSpec().getStorageClassSpec()) {
4315 default: assert(0 && "Unknown storage class!");
4316 case DeclSpec::SCS_auto:
4317 case DeclSpec::SCS_register:
4318 case DeclSpec::SCS_mutable:
Mike Stump11289f42009-09-09 15:08:12 +00004319 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregore62c0a42009-02-24 01:23:02 +00004320 diag::err_typecheck_sclass_func);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004321 D.setInvalidType();
Zhongxing Xubece5d62009-01-16 01:13:29 +00004322 break;
John McCall8e7d6562010-08-26 03:08:43 +00004323 case DeclSpec::SCS_unspecified: SC = SC_None; break;
4324 case DeclSpec::SCS_extern: SC = SC_Extern; break;
Douglas Gregore62c0a42009-02-24 01:23:02 +00004325 case DeclSpec::SCS_static: {
Sebastian Redl50c68252010-08-31 00:36:30 +00004326 if (CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00004327 // C99 6.7.1p5:
4328 // The declaration of an identifier for a function that has
4329 // block scope shall have no explicit storage-class specifier
4330 // other than extern
4331 // See also (C++ [dcl.stc]p4).
Mike Stump11289f42009-09-09 15:08:12 +00004332 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregore62c0a42009-02-24 01:23:02 +00004333 diag::err_static_block_func);
John McCall8e7d6562010-08-26 03:08:43 +00004334 SC = SC_None;
Douglas Gregore62c0a42009-02-24 01:23:02 +00004335 } else
John McCall8e7d6562010-08-26 03:08:43 +00004336 SC = SC_Static;
Douglas Gregore62c0a42009-02-24 01:23:02 +00004337 break;
4338 }
Gabor Greif80c21832010-09-08 00:31:13 +00004339 case DeclSpec::SCS_private_extern: SC = SC_PrivateExtern; break;
Zhongxing Xubece5d62009-01-16 01:13:29 +00004340 }
4341
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004342 if (D.getDeclSpec().isThreadSpecified())
4343 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4344
Chris Lattner347eec92009-04-11 19:17:25 +00004345 // Do not allow returning a objc interface by-value.
John McCall8b07ec22010-05-15 11:32:37 +00004346 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
Chris Lattner347eec92009-04-11 19:17:25 +00004347 Diag(D.getIdentifierLoc(),
4348 diag::err_object_cannot_be_passed_returned_by_value) << 0
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00004349 << R->getAs<FunctionType>()->getResultType()
4350 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
4351
4352 QualType T = R->getAs<FunctionType>()->getResultType();
4353 T = Context.getObjCObjectPointerType(T);
4354 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
4355 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4356 R = Context.getFunctionType(T, FPT->arg_type_begin(),
4357 FPT->getNumArgs(), EPI);
4358 }
4359 else if (isa<FunctionNoProtoType>(R))
4360 R = Context.getFunctionNoProtoType(T);
Chris Lattner347eec92009-04-11 19:17:25 +00004361 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004362
Zhongxing Xubece5d62009-01-16 01:13:29 +00004363 FunctionDecl *NewFD;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004364 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00004365 bool isFriend = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004366 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4367 FunctionDecl::StorageClass SCAsWritten
4368 = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
Douglas Gregor513e63c2010-12-10 19:28:19 +00004369 FunctionTemplateDecl *FunctionTemplate = 0;
4370 bool isExplicitSpecialization = false;
4371 bool isFunctionTemplateSpecialization = false;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004372 bool isDependentClassScopeExplicitSpecialization = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00004373
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004374 if (!getLangOptions().CPlusPlus) {
Douglas Gregor2797d322009-03-19 18:33:54 +00004375 // Determine whether the function was written with a
4376 // prototype. This true when:
Douglas Gregor2797d322009-03-19 18:33:54 +00004377 // - there is a prototype in the declarator, or
4378 // - the type R of the function is some kind of typedef or other reference
4379 // to a type name (which eventually refers to a function type).
Mike Stump11289f42009-09-09 15:08:12 +00004380 bool HasPrototype =
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004381 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004382 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
4383
Abramo Bagnaradff19302011-03-08 08:55:46 +00004384 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004385 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
Douglas Gregorc4df4072010-04-19 22:54:31 +00004386 HasPrototype);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004387 if (D.isInvalidType())
4388 NewFD->setInvalidDecl();
4389
4390 // Set the lexical context.
4391 NewFD->setLexicalDeclContext(CurContext);
4392 // Filter out previous declarations that don't match the scope.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004393 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
Douglas Gregordb446112011-03-07 16:54:27 +00004394 /*ExplicitInstantiationOrSpecialization=*/false);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004395 } else {
4396 isFriend = D.getDeclSpec().isFriendSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00004397 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4398 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smitha77a0a62011-08-15 21:04:07 +00004399 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00004400 bool isVirtualOkay = false;
Zhongxing Xubece5d62009-01-16 01:13:29 +00004401
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004402 // Check that the return type is not an abstract class type.
4403 // For record types, this is done by the AbstractClassUsageDiagnoser once
4404 // the class has been completely parsed.
4405 if (!DC->isRecord() &&
4406 RequireNonAbstractType(D.getIdentifierLoc(),
4407 R->getAs<FunctionType>()->getResultType(),
4408 diag::err_abstract_type_in_decl,
4409 AbstractReturnType))
4410 D.setInvalidType();
Mike Stump11289f42009-09-09 15:08:12 +00004411
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004412 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
4413 // This is a C++ constructor declaration.
4414 assert(DC->isRecord() &&
4415 "Constructors can only be declared in a member context");
4416
4417 R = CheckConstructorDeclarator(D, R, SC);
4418
4419 // Create the new declaration
Alexis Hunt5dafebc2011-05-06 01:42:00 +00004420 CXXConstructorDecl *NewCD = CXXConstructorDecl::Create(
4421 Context,
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004422 cast<CXXRecordDecl>(DC),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004423 D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004424 NameInfo, R, TInfo,
4425 isExplicit, isInline,
Richard Smitha77a0a62011-08-15 21:04:07 +00004426 /*isImplicitlyDeclared=*/false,
4427 isConstexpr);
Alexis Hunt5dafebc2011-05-06 01:42:00 +00004428
4429 NewFD = NewCD;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004430 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4431 // This is a C++ destructor declaration.
4432 if (DC->isRecord()) {
4433 R = CheckDestructorDeclarator(D, R, SC);
Sebastian Redl623ea822011-05-19 05:13:44 +00004434 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004435
Sebastian Redl623ea822011-05-19 05:13:44 +00004436 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004437 D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004438 NameInfo, R, TInfo,
4439 isInline,
4440 /*isImplicitlyDeclared=*/false);
Sebastian Redl623ea822011-05-19 05:13:44 +00004441 NewFD = NewDD;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004442 isVirtualOkay = true;
Sebastian Redl623ea822011-05-19 05:13:44 +00004443
4444 // If the class is complete, then we now create the implicit exception
4445 // specification. If the class is incomplete or dependent, we can't do
4446 // it yet.
4447 if (getLangOptions().CPlusPlus0x && !Record->isDependentType() &&
4448 Record->getDefinition() && !Record->isBeingDefined() &&
4449 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
4450 AdjustDestructorExceptionSpec(Record, NewDD);
4451 }
4452
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004453 } else {
4454 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
4455
4456 // Create a FunctionDecl to satisfy the function definition parsing
4457 // code path.
Abramo Bagnaradff19302011-03-08 08:55:46 +00004458 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(),
4459 D.getIdentifierLoc(), Name, R, TInfo,
4460 SC, SCAsWritten, isInline,
Richard Smitha77a0a62011-08-15 21:04:07 +00004461 /*hasPrototype=*/true, isConstexpr);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004462 D.setInvalidType();
4463 }
4464 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4465 if (!DC->isRecord()) {
4466 Diag(D.getIdentifierLoc(),
4467 diag::err_conv_function_not_member);
4468 return 0;
4469 }
4470
4471 CheckConversionDeclarator(D, R, SC);
4472 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004473 D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004474 NameInfo, R, TInfo,
Richard Smitha77a0a62011-08-15 21:04:07 +00004475 isInline, isExplicit, isConstexpr,
Douglas Gregorf2f08062011-03-08 17:10:18 +00004476 SourceLocation());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004477
4478 isVirtualOkay = true;
4479 } else if (DC->isRecord()) {
Richard Smithdef8bdb2011-08-12 18:44:32 +00004480 // If the name of the function is the same as the name of the record,
4481 // then this must be an invalid constructor that has a return type.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004482 // (The parser checks for a return type and makes the declarator a
4483 // constructor if it has no return type).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004484 if (Name.getAsIdentifierInfo() &&
4485 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
4486 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
4487 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4488 << SourceRange(D.getIdentifierLoc());
4489 return 0;
4490 }
4491
4492 bool isStatic = SC == SC_Static;
Sebastian Redl37588092011-03-14 18:08:30 +00004493
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004494 // [class.free]p1:
4495 // Any allocation function for a class T is a static member
4496 // (even if not explicitly declared static).
4497 if (Name.getCXXOverloadedOperator() == OO_New ||
4498 Name.getCXXOverloadedOperator() == OO_Array_New)
4499 isStatic = true;
4500
4501 // [class.free]p6 Any deallocation function for a class X is a static member
4502 // (even if not explicitly declared static).
4503 if (Name.getCXXOverloadedOperator() == OO_Delete ||
4504 Name.getCXXOverloadedOperator() == OO_Array_Delete)
4505 isStatic = true;
Sebastian Redl37588092011-03-14 18:08:30 +00004506
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004507 // This is a C++ method declaration.
Alexis Hunt5dafebc2011-05-06 01:42:00 +00004508 CXXMethodDecl *NewMD = CXXMethodDecl::Create(
4509 Context, cast<CXXRecordDecl>(DC),
4510 D.getSourceRange().getBegin(),
4511 NameInfo, R, TInfo,
4512 isStatic, SCAsWritten, isInline,
Richard Smitha77a0a62011-08-15 21:04:07 +00004513 isConstexpr,
Alexis Hunt5dafebc2011-05-06 01:42:00 +00004514 SourceLocation());
4515 NewFD = NewMD;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004516
4517 isVirtualOkay = !isStatic;
4518 } else {
4519 // Determine whether the function was written with a
4520 // prototype. This true when:
4521 // - we're in C++ (where every function has a prototype),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004522 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004523 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
Richard Smitha77a0a62011-08-15 21:04:07 +00004524 true/*HasPrototype*/, isConstexpr);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004525 }
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00004526
4527 if (isFriend && !isInline && IsFunctionDefinition) {
4528 // C++ [class.friend]p5
4529 // A function can be defined in a friend declaration of a
4530 // class . . . . Such a function is implicitly inline.
4531 NewFD->setImplicitlyInline();
4532 }
4533
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004534 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004535 isExplicitSpecialization = false;
4536 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004537 if (D.isInvalidType())
4538 NewFD->setInvalidDecl();
4539
4540 // Set the lexical context. If the declarator has a C++
4541 // scope specifier, or is the object of a friend declaration, the
4542 // lexical context will be different from the semantic context.
4543 NewFD->setLexicalDeclContext(CurContext);
4544
4545 // Match up the template parameter lists with the scope specifier, then
4546 // determine whether we have a template or a template specialization.
4547 bool Invalid = false;
4548 if (TemplateParameterList *TemplateParams
Douglas Gregor93ded322011-03-04 22:45:55 +00004549 = MatchTemplateParametersToScopeSpecifier(
Douglas Gregord8d297c2009-07-21 23:53:31 +00004550 D.getDeclSpec().getSourceRange().getBegin(),
Douglas Gregor972fe532011-05-10 18:27:06 +00004551 D.getIdentifierLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00004552 D.getCXXScopeSpec(),
John McCall2c2eb122010-10-16 06:59:13 +00004553 TemplateParamLists.get(),
4554 TemplateParamLists.size(),
4555 isFriend,
4556 isExplicitSpecialization,
4557 Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00004558 if (TemplateParams->size() > 0) {
4559 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004560
Abramo Bagnara60804e12011-03-18 15:16:37 +00004561 // Check that we can declare a template here.
4562 if (CheckTemplateDeclScope(S, TemplateParams))
4563 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004564
Abramo Bagnara60804e12011-03-18 15:16:37 +00004565 // A destructor cannot be a template.
4566 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4567 Diag(NewFD->getLocation(), diag::err_destructor_template);
4568 return 0;
John McCall1f0479e2010-03-24 08:27:58 +00004569 }
4570
Abramo Bagnara60804e12011-03-18 15:16:37 +00004571 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
4572 NewFD->getLocation(),
4573 Name, TemplateParams,
4574 NewFD);
4575 FunctionTemplate->setLexicalDeclContext(CurContext);
4576 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
4577
4578 // For source fidelity, store the other template param lists.
4579 if (TemplateParamLists.size() > 1) {
4580 NewFD->setTemplateParameterListsInfo(Context,
4581 TemplateParamLists.size() - 1,
4582 TemplateParamLists.release());
4583 }
4584 } else {
4585 // This is a function template specialization.
4586 isFunctionTemplateSpecialization = true;
4587 // For source fidelity, store all the template param lists.
4588 NewFD->setTemplateParameterListsInfo(Context,
4589 TemplateParamLists.size(),
4590 TemplateParamLists.release());
4591
4592 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
4593 if (isFriend) {
4594 // We want to remove the "template<>", found here.
4595 SourceRange RemoveRange = TemplateParams->getSourceRange();
4596
4597 // If we remove the template<> and the name is not a
4598 // template-id, we're actually silently creating a problem:
4599 // the friend declaration will refer to an untemplated decl,
4600 // and clearly the user wants a template specialization. So
4601 // we need to insert '<>' after the name.
4602 SourceLocation InsertLoc;
4603 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
4604 InsertLoc = D.getName().getSourceRange().getEnd();
4605 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
4606 }
4607
4608 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
4609 << Name << RemoveRange
4610 << FixItHint::CreateRemoval(RemoveRange)
4611 << FixItHint::CreateInsertion(InsertLoc, "<>");
4612 }
4613 }
4614 }
4615 else {
4616 // All template param lists were matched against the scope specifier:
4617 // this is NOT (an explicit specialization of) a template.
4618 if (TemplateParamLists.size() > 0)
4619 // For source fidelity, store all the template param lists.
4620 NewFD->setTemplateParameterListsInfo(Context,
4621 TemplateParamLists.size(),
4622 TemplateParamLists.release());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004623 }
4624
4625 if (Invalid) {
4626 NewFD->setInvalidDecl();
4627 if (FunctionTemplate)
4628 FunctionTemplate->setInvalidDecl();
4629 }
4630
4631 // C++ [dcl.fct.spec]p5:
4632 // The virtual specifier shall only be used in declarations of
4633 // nonstatic class member functions that appear within a
4634 // member-specification of a class declaration; see 10.3.
4635 //
4636 if (isVirtual && !NewFD->isInvalidDecl()) {
4637 if (!isVirtualOkay) {
4638 Diag(D.getDeclSpec().getVirtualSpecLoc(),
4639 diag::err_virtual_non_function);
4640 } else if (!CurContext->isRecord()) {
4641 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00004642 Diag(D.getDeclSpec().getVirtualSpecLoc(),
4643 diag::err_virtual_out_of_class)
4644 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
4645 } else if (NewFD->getDescribedFunctionTemplate()) {
4646 // C++ [temp.mem]p3:
4647 // A member function template shall not be virtual.
4648 Diag(D.getDeclSpec().getVirtualSpecLoc(),
4649 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004650 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
4651 } else {
4652 // Okay: Add virtual to the method.
4653 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00004654 }
Douglas Gregorc1da0f02009-06-24 00:23:40 +00004655 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004656
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004657 // C++ [dcl.fct.spec]p3:
4658 // The inline specifier shall not appear on a block scope function declaration.
4659 if (isInline && !NewFD->isInvalidDecl()) {
4660 if (CurContext->isFunctionOrMethod()) {
4661 // 'inline' is not allowed on block scope function declaration.
4662 Diag(D.getDeclSpec().getInlineSpecLoc(),
4663 diag::err_inline_declaration_block_scope) << Name
4664 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
4665 }
4666 }
4667
4668 // C++ [dcl.fct.spec]p6:
4669 // The explicit specifier shall be used only in the declaration of a
4670 // constructor or conversion function within its class definition; see 12.3.1
4671 // and 12.3.2.
4672 if (isExplicit && !NewFD->isInvalidDecl()) {
4673 if (!CurContext->isRecord()) {
4674 // 'explicit' was specified outside of the class.
4675 Diag(D.getDeclSpec().getExplicitSpecLoc(),
4676 diag::err_explicit_out_of_class)
4677 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
4678 } else if (!isa<CXXConstructorDecl>(NewFD) &&
4679 !isa<CXXConversionDecl>(NewFD)) {
4680 // 'explicit' was specified on a function that wasn't a constructor
4681 // or conversion function.
4682 Diag(D.getDeclSpec().getExplicitSpecLoc(),
4683 diag::err_explicit_non_ctor_or_conv_function)
4684 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
4685 }
4686 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004687
Richard Smitha77a0a62011-08-15 21:04:07 +00004688 if (isConstexpr) {
4689 // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
4690 // are implicitly inline.
4691 NewFD->setImplicitlyInline();
4692
4693 // FIXME: If this is a redeclaration, check the original declaration was
4694 // marked constepr.
4695
4696 // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
4697 // be either constructors or to return a literal type. Therefore,
4698 // destructors cannot be declared constexpr.
4699 if (isa<CXXDestructorDecl>(NewFD))
4700 Diag(D.getDeclSpec().getConstexprSpecLoc(),
4701 diag::err_constexpr_dtor);
4702 }
4703
Douglas Gregor26701a42011-09-09 02:06:17 +00004704 // If __module_private__ was specified, mark the function accordingly.
4705 if (D.getDeclSpec().isModulePrivateSpecified()) {
4706 NewFD->setModulePrivate();
4707 if (FunctionTemplate)
4708 FunctionTemplate->setModulePrivate();
4709 }
Richard Smitha77a0a62011-08-15 21:04:07 +00004710
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004711 // Filter out previous declarations that don't match the scope.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004712 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
Douglas Gregordb446112011-03-07 16:54:27 +00004713 isExplicitSpecialization ||
4714 isFunctionTemplateSpecialization);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004715
4716 if (isFriend) {
4717 // For now, claim that the objects have no previous declaration.
4718 if (FunctionTemplate) {
4719 FunctionTemplate->setObjectOfFriendDecl(false);
4720 FunctionTemplate->setAccess(AS_public);
4721 }
4722 NewFD->setObjectOfFriendDecl(false);
4723 NewFD->setAccess(AS_public);
4724 }
4725
John McCall357d0f32010-12-15 04:00:32 +00004726 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && IsFunctionDefinition) {
4727 // A method is implicitly inline if it's defined in its class
4728 // definition.
4729 NewFD->setImplicitlyInline();
4730 }
4731
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004732 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
4733 !CurContext->isRecord()) {
4734 // C++ [class.static]p1:
4735 // A data or function member of a class may be declared static
4736 // in a class definition, in which case it is a static member of
4737 // the class.
4738
4739 // Complain about the 'static' specifier if it's on an out-of-line
4740 // member function definition.
4741 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4742 diag::err_static_out_of_line)
4743 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4744 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00004745 }
4746
Zhongxing Xubece5d62009-01-16 01:13:29 +00004747 // Handle GNU asm-label extension (encoded as an attribute).
4748 if (Expr *E = (Expr*) D.getAsmLabel()) {
4749 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00004750 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004751 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
4752 SE->getString()));
Zhongxing Xubece5d62009-01-16 01:13:29 +00004753 }
4754
Chris Lattner9af40c12009-04-25 06:12:16 +00004755 // Copy the parameter declarations from the declarator D to the function
4756 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004757 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00004758 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004759 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00004760
Zhongxing Xubece5d62009-01-16 01:13:29 +00004761 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
4762 // function that takes no arguments, not a function that takes a
4763 // single void argument.
4764 // We let through "const void" here because Sema::GetTypeForDeclarator
4765 // already checks for that case.
4766 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4767 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00004768 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00004769 // Empty arg list, don't push any params.
John McCall48871652010-08-21 09:40:31 +00004770 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00004771
4772 // In C++, the empty parameter-type-list must be spelled "void"; a
4773 // typedef of void is not permitted.
4774 if (getLangOptions().CPlusPlus &&
Richard Smithdda56e42011-04-15 14:24:37 +00004775 Param->getType().getUnqualifiedType() != Context.VoidTy) {
4776 bool IsTypeAlias = false;
4777 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
4778 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004779 else if (const TemplateSpecializationType *TST =
4780 Param->getType()->getAs<TemplateSpecializationType>())
4781 IsTypeAlias = TST->isTypeAlias();
Richard Smithdda56e42011-04-15 14:24:37 +00004782 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
4783 << IsTypeAlias;
4784 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004785 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00004786 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00004787 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00004788 assert(Param->getDeclContext() != NewFD && "Was set before ?");
4789 Param->setDeclContext(NewFD);
4790 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00004791
4792 if (Param->isInvalidDecl())
4793 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00004794 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004795 }
Mike Stump11289f42009-09-09 15:08:12 +00004796
John McCall9dd450b2009-09-21 23:43:11 +00004797 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00004798 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00004799 // following example, we'll need to synthesize (unnamed)
4800 // parameters for use in the declaration.
4801 //
4802 // @code
4803 // typedef void fn(int);
4804 // fn f;
4805 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004806
Chris Lattner47c0d002009-04-25 06:03:53 +00004807 // Synthesize a parameter for each argument type.
Chris Lattner47c0d002009-04-25 06:03:53 +00004808 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
4809 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCalla3ccba02010-06-04 11:21:44 +00004810 ParmVarDecl *Param =
4811 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00004812 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00004813 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00004814 }
Chris Lattner49303b22009-04-25 18:38:18 +00004815 } else {
4816 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
4817 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00004818 }
Chris Lattner9af40c12009-04-25 06:12:16 +00004819 // Finally, we know we have the right number of parameters, install them.
Douglas Gregord5058122010-02-11 01:19:42 +00004820 NewFD->setParams(Params.data(), Params.size());
Mike Stump11289f42009-09-09 15:08:12 +00004821
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004822 // Process the non-inheritable attributes on this declaration.
4823 ProcessDeclAttributes(S, NewFD, D,
4824 /*NonInheritable=*/true, /*Inheritable=*/false);
4825
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004826 if (!getLangOptions().CPlusPlus) {
4827 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00004828 bool isExplicitSpecialization=false;
David Blaikied937bf12011-09-08 06:33:04 +00004829 if (!NewFD->isInvalidDecl()) {
4830 if (NewFD->getResultType()->isVariablyModifiedType()) {
4831 // Functions returning a variably modified type violate C99 6.7.5.2p2
4832 // because all functions have linkage.
4833 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
4834 NewFD->setInvalidDecl();
4835 } else {
4836 if (NewFD->isMain())
4837 CheckMain(NewFD, D.getDeclSpec());
4838 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
4839 Redeclaration);
4840 }
4841 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004842 assert((NewFD->isInvalidDecl() || !Redeclaration ||
4843 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
4844 "previous declaration set still overloaded");
4845 } else {
4846 // If the declarator is a template-id, translate the parser's template
4847 // argument list into our AST format.
4848 bool HasExplicitTemplateArgs = false;
4849 TemplateArgumentListInfo TemplateArgs;
4850 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4851 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4852 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4853 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
4854 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4855 TemplateId->getTemplateArgs(),
4856 TemplateId->NumArgs);
4857 translateTemplateArguments(TemplateArgsPtr,
4858 TemplateArgs);
4859 TemplateArgsPtr.release();
Douglas Gregor0e876e02009-09-25 23:53:26 +00004860
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004861 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00004862
Douglas Gregor522d5eb2011-06-06 15:22:55 +00004863 if (NewFD->isInvalidDecl()) {
4864 HasExplicitTemplateArgs = false;
4865 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00004866 // Function template with explicit template arguments.
4867 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
4868 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
4869
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004870 HasExplicitTemplateArgs = false;
4871 } else if (!isFunctionTemplateSpecialization &&
4872 !D.getDeclSpec().isFriendSpecified()) {
4873 // We have encountered something that the user meant to be a
4874 // specialization (because it has explicitly-specified template
4875 // arguments) but that was not introduced with a "template<>" (or had
4876 // too few of them).
4877 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
4878 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
4879 << FixItHint::CreateInsertion(
4880 D.getDeclSpec().getSourceRange().getBegin(),
4881 "template<> ");
4882 isFunctionTemplateSpecialization = true;
John McCallf7cfb222010-10-13 05:45:15 +00004883 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004884 // "friend void foo<>(int);" is an implicit specialization decl.
4885 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00004886 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004887 } else if (isFriend && isFunctionTemplateSpecialization) {
4888 // This combination is only possible in a recovery case; the user
4889 // wrote something like:
4890 // template <> friend void foo(int);
4891 // which we're recovering from as if the user had written:
4892 // friend void foo<>(int);
4893 // Go ahead and fake up a template id.
4894 HasExplicitTemplateArgs = true;
4895 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
4896 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004897 }
John McCallf7cfb222010-10-13 05:45:15 +00004898
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004899 // If it's a friend (and only if it's a friend), it's possible
4900 // that either the specialized function type or the specialized
4901 // template is dependent, and therefore matching will fail. In
4902 // this case, don't check the specialization yet.
4903 if (isFunctionTemplateSpecialization && isFriend &&
4904 (NewFD->getType()->isDependentType() || DC->isDependentContext())) {
4905 assert(HasExplicitTemplateArgs &&
4906 "friend function specialization without template args");
4907 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
4908 Previous))
4909 NewFD->setInvalidDecl();
4910 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00004911 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00004912 && !isFriend) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004913 isDependentClassScopeExplicitSpecialization = true;
4914 Diag(NewFD->getLocation(), getLangOptions().Microsoft ?
4915 diag::ext_function_specialization_in_class :
4916 diag::err_function_specialization_in_class)
Douglas Gregor63fab342011-03-16 19:27:09 +00004917 << NewFD->getDeclName();
Douglas Gregor63fab342011-03-16 19:27:09 +00004918 } else if (CheckFunctionTemplateSpecialization(NewFD,
4919 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
4920 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004921 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00004922
4923 // C++ [dcl.stc]p1:
4924 // A storage-class-specifier shall not be specified in an explicit
4925 // specialization (14.7.3)
4926 if (SC != SC_None) {
Douglas Gregor84265a02011-06-17 05:09:08 +00004927 if (SC != NewFD->getStorageClass())
4928 Diag(NewFD->getLocation(),
4929 diag::err_explicit_specialization_inconsistent_storage_class)
4930 << SC
4931 << FixItHint::CreateRemoval(
4932 D.getDeclSpec().getStorageClassSpecLoc());
4933
4934 else
4935 Diag(NewFD->getLocation(),
4936 diag::ext_explicit_specialization_storage_class)
4937 << FixItHint::CreateRemoval(
4938 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00004939 }
4940
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004941 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
4942 if (CheckMemberSpecialization(NewFD, Previous))
4943 NewFD->setInvalidDecl();
4944 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004945
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004946 // Perform semantic checking on the function declaration.
David Blaikied937bf12011-09-08 06:33:04 +00004947 if (!isDependentClassScopeExplicitSpecialization) {
4948 if (NewFD->isInvalidDecl()) {
4949 // If this is a class member, mark the class invalid immediately.
4950 // This avoids some consistency errors later.
4951 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
4952 methodDecl->getParent()->setInvalidDecl();
4953 } else {
4954 if (NewFD->isMain())
4955 CheckMain(NewFD, D.getDeclSpec());
4956 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
4957 Redeclaration);
4958 }
4959 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004960
4961 assert((NewFD->isInvalidDecl() || !Redeclaration ||
4962 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
4963 "previous declaration set still overloaded");
4964
4965 NamedDecl *PrincipalDecl = (FunctionTemplate
4966 ? cast<NamedDecl>(FunctionTemplate)
4967 : NewFD);
4968
4969 if (isFriend && Redeclaration) {
4970 AccessSpecifier Access = AS_public;
4971 if (!NewFD->isInvalidDecl())
4972 Access = NewFD->getPreviousDeclaration()->getAccess();
4973
4974 NewFD->setAccess(Access);
4975 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
4976
4977 PrincipalDecl->setObjectOfFriendDecl(true);
4978 }
4979
4980 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
4981 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4982 PrincipalDecl->setNonMemberOperator();
4983
4984 // If we have a function template, check the template parameter
4985 // list. This will check and merge default template arguments.
4986 if (FunctionTemplate) {
4987 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
4988 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
4989 PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00004990 D.getDeclSpec().isFriendSpecified()
4991 ? (IsFunctionDefinition
4992 ? TPC_FriendFunctionTemplateDefinition
4993 : TPC_FriendFunctionTemplate)
4994 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00004995 DC && DC->isRecord() &&
4996 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00004997 ? TPC_ClassTemplateMember
4998 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004999 }
5000
5001 if (NewFD->isInvalidDecl()) {
5002 // Ignore all the rest of this.
5003 } else if (!Redeclaration) {
5004 // Fake up an access specifier if it's supposed to be a class member.
5005 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
5006 NewFD->setAccess(AS_public);
5007
5008 // Qualified decls generally require a previous declaration.
5009 if (D.getCXXScopeSpec().isSet()) {
5010 // ...with the major exception of templated-scope or
5011 // dependent-scope friend declarations.
5012
5013 // TODO: we currently also suppress this check in dependent
5014 // contexts because (1) the parameter depth will be off when
5015 // matching friend templates and (2) we might actually be
5016 // selecting a friend based on a dependent factor. But there
5017 // are situations where these conditions don't apply and we
5018 // can actually do this check immediately.
5019 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00005020 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005021 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
5022 CurContext->isDependentContext())) {
Chandler Carruthf8b554f2011-08-19 01:38:33 +00005023 // ignore these
5024 } else {
5025 // The user tried to provide an out-of-line definition for a
5026 // function that is a member of a class or namespace, but there
5027 // was no such member function declared (C++ [class.mfct]p2,
5028 // C++ [namespace.memdef]p2). For example:
5029 //
5030 // class X {
5031 // void f() const;
5032 // };
5033 //
5034 // void X::f() { } // ill-formed
5035 //
5036 // Complain about this problem, and attempt to suggest close
5037 // matches (e.g., those that differ only in cv-qualifiers and
5038 // whether the parameter types are references).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005039
Chandler Carruthf8b554f2011-08-19 01:38:33 +00005040 DiagnoseInvalidRedeclaration(*this, NewFD, false);
5041 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005042
5043 // Unqualified local friend declarations are required to resolve
5044 // to something.
Chandler Carruthe92e42f2011-08-19 01:40:11 +00005045 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
5046 DiagnoseInvalidRedeclaration(*this, NewFD, true);
5047 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005048
5049 } else if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
5050 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00005051 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005052 // An out-of-line member function declaration must also be a
5053 // definition (C++ [dcl.meaning]p1).
5054 // Note that this is not the case for explicit specializations of
5055 // function templates or member functions of class templates, per
5056 // C++ [temp.expl.spec]p2. We also allow these declarations as an extension
5057 // for compatibility with old SWIG code which likes to generate them.
5058 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
5059 << D.getCXXScopeSpec().getRange();
5060 }
5061 }
Alexis Hunt5a7fa252011-05-12 06:15:49 +00005062
5063
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005064 // Handle attributes. We need to have merged decls when handling attributes
5065 // (for example to check for conflicts, etc).
5066 // FIXME: This needs to happen before we merge declarations. Then,
5067 // let attribute merging cope with attribute conflicts.
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00005068 ProcessDeclAttributes(S, NewFD, D,
5069 /*NonInheritable=*/false, /*Inheritable=*/true);
Ryan Flynne5dc8592009-07-25 22:29:44 +00005070
5071 // attributes declared post-definition are currently ignored
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005072 // FIXME: This should happen during attribute merging
John McCall1f82f242009-11-18 22:49:29 +00005073 if (Redeclaration && Previous.isSingleResult()) {
5074 const FunctionDecl *Def;
5075 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
Alexis Hunt4a8ea102011-05-06 20:44:56 +00005076 if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) {
Ryan Flynne5dc8592009-07-25 22:29:44 +00005077 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
5078 Diag(Def->getLocation(), diag::note_previous_definition);
5079 }
5080 }
5081
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005082 AddKnownFunctionAttributes(NewFD);
5083
Douglas Gregor72609052010-08-06 13:50:58 +00005084 if (NewFD->hasAttr<OverloadableAttr>() &&
5085 !NewFD->getType()->getAs<FunctionProtoType>()) {
5086 Diag(NewFD->getLocation(),
5087 diag::err_attribute_overloadable_no_prototype)
5088 << NewFD;
5089
5090 // Turn this into a variadic function with no parameters.
5091 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005092 FunctionProtoType::ExtProtoInfo EPI;
5093 EPI.Variadic = true;
5094 EPI.ExtInfo = FT->getExtInfo();
5095
5096 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00005097 NewFD->setType(R);
5098 }
5099
Eli Friedman570024a2010-08-05 06:57:20 +00005100 // If there's a #pragma GCC visibility in scope, and this isn't a class
5101 // member, set the visibility of this function.
5102 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
5103 AddPushedVisibilityAttribute(NewFD);
5104
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005105 // If this is a locally-scoped extern C function, update the
5106 // map of such names.
Douglas Gregor16618f22009-09-12 00:17:51 +00005107 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005108 && !NewFD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00005109 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005110
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00005111 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00005112 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00005113
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005114 if (getLangOptions().CPlusPlus) {
5115 if (FunctionTemplate) {
5116 if (NewFD->isInvalidDecl())
5117 FunctionTemplate->setInvalidDecl();
5118 return FunctionTemplate;
5119 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005120 }
Mike Stump11289f42009-09-09 15:08:12 +00005121
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00005122 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00005123
5124 if (getLangOptions().CUDA)
5125 if (IdentifierInfo *II = NewFD->getIdentifier())
5126 if (!NewFD->isInvalidDecl() &&
5127 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5128 if (II->isStr("cudaConfigureCall")) {
5129 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
5130 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
5131
5132 Context.setcudaConfigureCallDecl(NewFD);
5133 }
5134 }
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005135
5136 // Here we have an function template explicit specialization at class scope.
5137 // The actually specialization will be postponed to template instatiation
5138 // time via the ClassScopeFunctionSpecializationDecl node.
5139 if (isDependentClassScopeExplicitSpecialization) {
5140 ClassScopeFunctionSpecializationDecl *NewSpec =
5141 ClassScopeFunctionSpecializationDecl::Create(
5142 Context, CurContext, SourceLocation(),
5143 cast<CXXMethodDecl>(NewFD));
5144 CurContext->addDecl(NewSpec);
5145 AddToScope = false;
5146 }
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00005147
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005148 return NewFD;
5149}
5150
5151/// \brief Perform semantic checking of a new function declaration.
5152///
5153/// Performs semantic analysis of the new function declaration
5154/// NewFD. This routine performs all semantic checking that does not
5155/// require the actual declarator involved in the declaration, and is
5156/// used both for the declaration of functions as they are parsed
5157/// (called via ActOnDeclarator) and for the declaration of functions
5158/// that have been instantiated via C++ template instantiation (called
5159/// via InstantiateDecl).
5160///
Douglas Gregorcf915552009-10-13 16:30:37 +00005161/// \param IsExplicitSpecialiation whether this new function declaration is
5162/// an explicit specialization of the previous declaration.
5163///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005164/// This sets NewFD->isInvalidDecl() to true if there was an error.
John McCall84d87672009-12-10 09:41:52 +00005165void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00005166 LookupResult &Previous,
Douglas Gregorcf915552009-10-13 16:30:37 +00005167 bool IsExplicitSpecialization,
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00005168 bool &Redeclaration) {
David Blaikied937bf12011-09-08 06:33:04 +00005169 assert(!NewFD->getResultType()->isVariablyModifiedType()
5170 && "Variably modified return types are not handled here");
John McCalld9baf6a2009-07-24 03:03:21 +00005171
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005172 // Check for a previous declaration of this name.
John McCall1f82f242009-11-18 22:49:29 +00005173 if (Previous.empty() && NewFD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005174 // Since we did not find anything by this name and we're declaring
5175 // an extern "C" function, look for a non-visible extern "C"
5176 // declaration with the same name.
5177 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregordc5c9582011-07-28 14:20:37 +00005178 = findLocallyScopedExternalDecl(NewFD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005179 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00005180 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005181 }
5182
Douglas Gregore62c0a42009-02-24 01:23:02 +00005183 // Merge or overload the declaration with an existing declaration of
5184 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00005185 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00005186 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00005187 // a declaration that requires merging. If it's an overload,
5188 // there's no more work to do here; we'll just add the new
5189 // function to the scope.
Douglas Gregor633b7372009-02-13 00:26:38 +00005190
John McCall1f82f242009-11-18 22:49:29 +00005191 NamedDecl *OldDecl = 0;
John McCalldaa3d6b2009-12-09 03:35:25 +00005192 if (!AllowOverloadingOfFunction(Previous, Context)) {
5193 Redeclaration = true;
5194 OldDecl = Previous.getFoundDecl();
5195 } else {
John McCalle9cccd82010-06-16 08:42:20 +00005196 switch (CheckOverload(S, NewFD, Previous, OldDecl,
5197 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00005198 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00005199 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00005200 break;
5201
5202 case Ovl_NonFunction:
5203 Redeclaration = true;
5204 break;
5205
5206 case Ovl_Overload:
5207 Redeclaration = false;
5208 break;
John McCall1f82f242009-11-18 22:49:29 +00005209 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00005210
5211 if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
5212 // If a function name is overloadable in C, then every function
5213 // with that name must be marked "overloadable".
5214 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
5215 << Redeclaration << NewFD;
5216 NamedDecl *OverloadedDecl = 0;
5217 if (Redeclaration)
5218 OverloadedDecl = OldDecl;
5219 else if (!Previous.empty())
5220 OverloadedDecl = Previous.getRepresentativeDecl();
5221 if (OverloadedDecl)
5222 Diag(OverloadedDecl->getLocation(),
5223 diag::note_attribute_overloadable_prev_overload);
5224 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
5225 Context));
5226 }
John McCall1f82f242009-11-18 22:49:29 +00005227 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005228
John McCall1f82f242009-11-18 22:49:29 +00005229 if (Redeclaration) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005230 // NewFD and OldDecl represent declarations that need to be
Mike Stump11289f42009-09-09 15:08:12 +00005231 // merged.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00005232 if (MergeFunctionDecl(NewFD, OldDecl))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005233 return NewFD->setInvalidDecl();
Zhongxing Xubece5d62009-01-16 01:13:29 +00005234
John McCall1f82f242009-11-18 22:49:29 +00005235 Previous.clear();
5236 Previous.addDecl(OldDecl);
5237
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005238 if (FunctionTemplateDecl *OldTemplateDecl
Douglas Gregorca027af2009-10-12 22:27:17 +00005239 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
Douglas Gregorcf915552009-10-13 16:30:37 +00005240 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
Douglas Gregorca027af2009-10-12 22:27:17 +00005241 FunctionTemplateDecl *NewTemplateDecl
5242 = NewFD->getDescribedFunctionTemplate();
5243 assert(NewTemplateDecl && "Template/non-template mismatch");
5244 if (CXXMethodDecl *Method
5245 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
5246 Method->setAccess(OldTemplateDecl->getAccess());
5247 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
5248 }
Douglas Gregorcf915552009-10-13 16:30:37 +00005249
5250 // If this is an explicit specialization of a member that is a function
5251 // template, mark it as a member specialization.
5252 if (IsExplicitSpecialization &&
5253 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
5254 NewTemplateDecl->setMemberSpecialization();
5255 assert(OldTemplateDecl->isMemberSpecialization());
5256 }
Douglas Gregoref15bdb2011-09-09 18:32:39 +00005257
5258 if (OldTemplateDecl->isModulePrivate())
5259 NewTemplateDecl->setModulePrivate();
5260
Douglas Gregorca027af2009-10-12 22:27:17 +00005261 } else {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005262 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
5263 NewFD->setAccess(OldDecl->getAccess());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005264 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005265 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005266 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00005267 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005268
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005269 // Semantic checking for this function declaration (in isolation).
5270 if (getLangOptions().CPlusPlus) {
5271 // C++-specific checks.
5272 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
5273 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005274 } else if (CXXDestructorDecl *Destructor =
5275 dyn_cast<CXXDestructorDecl>(NewFD)) {
5276 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005277 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005278
Douglas Gregor7454c562010-07-02 20:37:36 +00005279 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00005280 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005281 if (!ClassType->isDependentType()) {
5282 DeclarationName Name
5283 = Context.DeclarationNames.getCXXDestructorName(
5284 Context.getCanonicalType(ClassType));
5285 if (NewFD->getDeclName() != Name) {
5286 Diag(NewFD->getLocation(), diag::err_destructor_name);
5287 return NewFD->setInvalidDecl();
5288 }
5289 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005290 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00005291 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005292 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00005293 }
5294
5295 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00005296 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
5297 if (!Method->isFunctionTemplateSpecialization() &&
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005298 !Method->getDescribedFunctionTemplate()) {
5299 if (AddOverriddenMethods(Method->getParent(), Method)) {
5300 // If the function was marked as "static", we have a problem.
5301 if (NewFD->getStorageClass() == SC_Static) {
5302 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
5303 << NewFD->getDeclName();
5304 for (CXXMethodDecl::method_iterator
5305 Overridden = Method->begin_overridden_methods(),
5306 OverriddenEnd = Method->end_overridden_methods();
5307 Overridden != OverriddenEnd;
5308 ++Overridden) {
5309 Diag((*Overridden)->getLocation(),
5310 diag::note_overridden_virtual_function);
5311 }
5312 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005313 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005314 }
Douglas Gregor6be3de32009-12-01 17:35:23 +00005315 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005316
5317 // Extra checking for C++ overloaded operators (C++ [over.oper]).
5318 if (NewFD->isOverloadedOperator() &&
5319 CheckOverloadedOperatorDeclaration(NewFD))
5320 return NewFD->setInvalidDecl();
Alexis Huntc88db062010-01-13 09:01:02 +00005321
5322 // Extra checking for C++0x literal operators (C++0x [over.literal]).
5323 if (NewFD->getLiteralIdentifier() &&
5324 CheckLiteralOperatorDeclaration(NewFD))
5325 return NewFD->setInvalidDecl();
5326
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005327 // In C++, check default arguments now that we have merged decls. Unless
5328 // the lexical context is the class, because in this case this is done
5329 // during delayed parsing anyway.
5330 if (!CurContext->isRecord())
5331 CheckCXXDefaultArguments(NewFD);
Douglas Gregor9246b682010-12-21 19:47:46 +00005332
5333 // If this function declares a builtin function, check the type of this
5334 // declaration against the expected type for the builtin.
5335 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
5336 ASTContext::GetBuiltinTypeError Error;
5337 QualType T = Context.GetBuiltinType(BuiltinID, Error);
5338 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
5339 // The type of this function differs from the type of the builtin,
5340 // so forget about the builtin entirely.
5341 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
5342 }
5343 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005344 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005345}
5346
David Blaikied937bf12011-09-08 06:33:04 +00005347void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
John McCall02dee0a2009-07-25 04:36:53 +00005348 // C++ [basic.start.main]p3: A program that declares main to be inline
5349 // or static is ill-formed.
5350 // C99 6.7.4p4: In a hosted environment, the inline function specifier
5351 // shall not appear in a declaration of main.
5352 // static main is not an error under C99, but we should warn about it.
David Blaikied937bf12011-09-08 06:33:04 +00005353 if (FD->getStorageClass() == SC_Static)
5354 Diag(DS.getStorageClassSpecLoc(), getLangOptions().CPlusPlus
5355 ? diag::err_static_main : diag::warn_static_main)
5356 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5357 if (FD->isInlineSpecified())
5358 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
5359 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
John McCall02dee0a2009-07-25 04:36:53 +00005360
5361 QualType T = FD->getType();
5362 assert(T->isFunctionType() && "function decl is not of function type");
John McCall9dd450b2009-09-21 23:43:11 +00005363 const FunctionType* FT = T->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00005364
John McCall02dee0a2009-07-25 04:36:53 +00005365 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
Douglas Gregorf05c0952011-02-19 19:04:23 +00005366 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
John McCall02dee0a2009-07-25 04:36:53 +00005367 FD->setInvalidDecl(true);
5368 }
5369
5370 // Treat protoless main() as nullary.
5371 if (isa<FunctionNoProtoType>(FT)) return;
5372
5373 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
5374 unsigned nparams = FTP->getNumArgs();
5375 assert(FD->getNumParams() == nparams);
5376
John McCall0e21fcc2009-12-24 09:58:38 +00005377 bool HasExtraParameters = (nparams > 3);
5378
5379 // Darwin passes an undocumented fourth argument of type char**. If
5380 // other platforms start sprouting these, the logic below will start
5381 // getting shifty.
Douglas Gregore8bbc122011-09-02 00:18:52 +00005382 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00005383 HasExtraParameters = false;
5384
5385 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00005386 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
5387 FD->setInvalidDecl(true);
5388 nparams = 3;
5389 }
5390
5391 // FIXME: a lot of the following diagnostics would be improved
5392 // if we had some location information about types.
5393
5394 QualType CharPP =
5395 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00005396 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00005397
5398 for (unsigned i = 0; i < nparams; ++i) {
5399 QualType AT = FTP->getArgType(i);
5400
5401 bool mismatch = true;
5402
5403 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
5404 mismatch = false;
5405 else if (Expected[i] == CharPP) {
5406 // As an extension, the following forms are okay:
5407 // char const **
5408 // char const * const *
5409 // char * const *
5410
John McCall8ccfcb52009-09-24 19:53:00 +00005411 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00005412 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005413 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
5414 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
John McCall02dee0a2009-07-25 04:36:53 +00005415 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
5416 qs.removeConst();
5417 mismatch = !qs.empty();
5418 }
5419 }
5420
5421 if (mismatch) {
5422 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
5423 // TODO: suggest replacing given type with expected type
5424 FD->setInvalidDecl(true);
5425 }
5426 }
5427
5428 if (nparams == 1 && !FD->isInvalidDecl()) {
5429 Diag(FD->getLocation(), diag::warn_main_one_arg);
5430 }
Douglas Gregorbff62032010-10-21 16:57:46 +00005431
5432 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
5433 Diag(FD->getLocation(), diag::err_main_template_decl);
5434 FD->setInvalidDecl();
5435 }
John McCalld9baf6a2009-07-24 03:03:21 +00005436}
5437
Eli Friedmand5a55bd2008-05-20 13:48:25 +00005438bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00005439 // FIXME: Need strict checking. In C89, we need to check for
5440 // any assignment, increment, decrement, function-calls, or
5441 // commas outside of a sizeof. In C99, it's the same list,
5442 // except that the aforementioned are allowed in unevaluated
5443 // expressions. Everything else falls under the
5444 // "may accept other forms of constant expressions" exception.
5445 // (We never end up here for C++, so the constant expression
5446 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00005447 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00005448 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00005449 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
5450 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00005451 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00005452}
5453
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005454namespace {
5455 // Visits an initialization expression to see if OrigDecl is evaluated in
5456 // its own initialization and throws a warning if it does.
5457 class SelfReferenceChecker
5458 : public EvaluatedExprVisitor<SelfReferenceChecker> {
5459 Sema &S;
5460 Decl *OrigDecl;
Richard Trieua04ad1a2011-09-01 21:44:13 +00005461 bool isRecordType;
5462 bool isPODType;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005463
5464 public:
5465 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
5466
5467 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieua04ad1a2011-09-01 21:44:13 +00005468 S(S), OrigDecl(OrigDecl) {
5469 isPODType = false;
5470 isRecordType = false;
5471 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
5472 isPODType = VD->getType().isPODType(S.Context);
5473 isRecordType = VD->getType()->isRecordType();
5474 }
5475 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005476
5477 void VisitExpr(Expr *E) {
5478 if (isa<ObjCMessageExpr>(*E)) return;
Richard Trieua04ad1a2011-09-01 21:44:13 +00005479 if (isRecordType) {
5480 Expr *expr = E;
5481 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5482 ValueDecl *VD = ME->getMemberDecl();
5483 if (isa<EnumConstantDecl>(VD) || isa<VarDecl>(VD)) return;
5484 expr = ME->getBase();
5485 }
5486 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(expr)) {
5487 HandleDeclRefExpr(DRE);
5488 return;
5489 }
5490 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005491 Inherited::VisitExpr(E);
5492 }
5493
Richard Trieua04ad1a2011-09-01 21:44:13 +00005494 void VisitMemberExpr(MemberExpr *E) {
Richard Trieuaa5e2562011-09-07 00:58:53 +00005495 if (E->getType()->canDecayToPointerType()) return;
Richard Trieua04ad1a2011-09-01 21:44:13 +00005496 if (isa<FieldDecl>(E->getMemberDecl()))
5497 if (DeclRefExpr *DRE
5498 = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) {
5499 HandleDeclRefExpr(DRE);
5500 return;
5501 }
5502 Inherited::VisitMemberExpr(E);
5503 }
5504
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005505 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieua04ad1a2011-09-01 21:44:13 +00005506 if ((!isRecordType &&E->getCastKind() == CK_LValueToRValue) ||
5507 (isRecordType && E->getCastKind() == CK_NoOp)) {
5508 Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts();
5509 if (MemberExpr *ME = dyn_cast<MemberExpr>(SubExpr))
5510 SubExpr = ME->getBase()->IgnoreParenImpCasts();
5511 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
5512 HandleDeclRefExpr(DRE);
5513 return;
5514 }
5515 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005516 Inherited::VisitImplicitCastExpr(E);
5517 }
5518
Richard Trieua04ad1a2011-09-01 21:44:13 +00005519 void VisitUnaryOperator(UnaryOperator *E) {
5520 // For POD record types, addresses of its own members are well-defined.
5521 if (isRecordType && isPODType) return;
5522 Inherited::VisitUnaryOperator(E);
5523 }
5524
5525 void HandleDeclRefExpr(DeclRefExpr *DRE) {
5526 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005527 if (OrigDecl != ReferenceDecl) return;
5528 LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName,
5529 Sema::NotForRedeclaration);
Richard Trieua04ad1a2011-09-01 21:44:13 +00005530 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005531 S.PDiag(diag::warn_uninit_self_reference_in_init)
Richard Trieua04ad1a2011-09-01 21:44:13 +00005532 << Result.getLookupName()
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005533 << OrigDecl->getLocation()
Richard Trieua04ad1a2011-09-01 21:44:13 +00005534 << DRE->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005535 }
5536 };
5537}
5538
Richard Trieua04ad1a2011-09-01 21:44:13 +00005539/// CheckSelfReference - Warns if OrigDecl is used in expression E.
5540void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) {
5541 SelfReferenceChecker(*this, OrigDecl).VisitExpr(E);
5542}
5543
Douglas Gregor5fb53972009-01-14 15:45:31 +00005544/// AddInitializerToDecl - Adds the initializer Init to the
5545/// declaration dcl. If DirectInit is true, this is C++ direct
5546/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00005547void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
5548 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00005549 // If there is no declaration, there was an error parsing it. Just ignore
5550 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00005551 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00005552 return;
Mike Stump11289f42009-09-09 15:08:12 +00005553
Ted Kremenek37881932011-04-04 23:29:12 +00005554 // Check for self-references within variable initializers.
5555 if (VarDecl *vd = dyn_cast<VarDecl>(RealDecl)) {
5556 // Variables declared within a function/method body are handled
5557 // by a dataflow analysis.
5558 if (!vd->hasLocalStorage() && !vd->isStaticLocal())
Richard Trieua04ad1a2011-09-01 21:44:13 +00005559 CheckSelfReference(RealDecl, Init);
Ted Kremenek37881932011-04-04 23:29:12 +00005560 }
5561 else {
Richard Trieua04ad1a2011-09-01 21:44:13 +00005562 CheckSelfReference(RealDecl, Init);
Ted Kremenek37881932011-04-04 23:29:12 +00005563 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005564
Douglas Gregor0c880302009-03-11 23:00:04 +00005565 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
5566 // With declarators parsed the way they are, the parser cannot
5567 // distinguish between a normal initializer and a pure-specifier.
5568 // Thus this grotesque test.
5569 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00005570 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00005571 Context.getCanonicalType(IL->getType()) == Context.IntTy)
5572 CheckPureMethod(Method, Init->getSourceRange());
5573 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00005574 Diag(Method->getLocation(), diag::err_member_function_initialization)
5575 << Method->getDeclName() << Init->getSourceRange();
5576 Method->setInvalidDecl();
5577 }
5578 return;
5579 }
5580
Steve Naroff437b4d82007-09-12 20:13:48 +00005581 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5582 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00005583 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
5584 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00005585 RealDecl->setInvalidDecl();
5586 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00005587 }
5588
Richard Smith30482bc2011-02-20 03:19:35 +00005589 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
5590 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith9647d3c2011-03-17 16:11:59 +00005591 TypeSourceInfo *DeducedType = 0;
5592 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00005593 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
5594 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5595 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00005596 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00005597 RealDecl->setInvalidDecl();
5598 return;
5599 }
Richard Smith9647d3c2011-03-17 16:11:59 +00005600 VDecl->setTypeSourceInfo(DeducedType);
5601 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00005602
John McCall31168b02011-06-15 23:02:42 +00005603 // In ARC, infer lifetime.
5604 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
5605 VDecl->setInvalidDecl();
5606
Richard Smith30482bc2011-02-20 03:19:35 +00005607 // If this is a redeclaration, check that the type we just deduced matches
5608 // the previously declared type.
5609 if (VarDecl *Old = VDecl->getPreviousDeclaration())
5610 MergeVarDeclTypes(VDecl, Old);
5611 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00005612
5613
Eli Friedmanc9827d12009-11-14 03:40:14 +00005614 // A definition must end up with a complete type, which means it must be
5615 // complete with the restriction that an array type might be completed by the
5616 // initializer; note that later code assumes this restriction.
5617 QualType BaseDeclType = VDecl->getType();
5618 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
5619 BaseDeclType = Array->getElementType();
5620 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
Eli Friedman337cd3a2009-04-13 21:28:54 +00005621 diag::err_typecheck_decl_incomplete_type)) {
5622 RealDecl->setInvalidDecl();
5623 return;
5624 }
5625
Douglas Gregorc99f1552009-12-03 18:33:45 +00005626 // The variable can not have an abstract class type.
5627 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5628 diag::err_abstract_type_in_decl,
5629 AbstractVariableType))
5630 VDecl->setInvalidDecl();
5631
Sebastian Redl5ca79842010-02-01 20:16:42 +00005632 const VarDecl *Def;
5633 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00005634 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00005635 << VDecl->getDeclName();
5636 Diag(Def->getLocation(), diag::note_previous_definition);
5637 VDecl->setInvalidDecl();
5638 return;
5639 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00005640
Douglas Gregorf0f83692010-08-24 05:27:49 +00005641 const VarDecl* PrevInit = 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00005642 if (getLangOptions().CPlusPlus) {
5643 // C++ [class.static.data]p4
5644 // If a static data member is of const integral or const
5645 // enumeration type, its declaration in the class definition can
5646 // specify a constant-initializer which shall be an integral
5647 // constant expression (5.19). In that case, the member can appear
5648 // in integral constant expressions. The member shall still be
5649 // defined in a namespace scope if it is used in the program and the
5650 // namespace scope definition shall not contain an initializer.
5651 //
5652 // We already performed a redefinition check above, but for static
5653 // data members we also need to check whether there was an in-class
5654 // declaration with an initializer.
5655 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5656 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5657 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5658 return;
5659 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00005660
Douglas Gregor71f39c92010-12-16 01:31:22 +00005661 if (VDecl->hasLocalStorage())
5662 getCurFunction()->setHasBranchProtectedScope();
5663
5664 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
5665 VDecl->setInvalidDecl();
5666 return;
5667 }
5668 }
John McCalld4e1b762010-08-01 01:24:59 +00005669
Douglas Gregor85dabae2009-12-16 01:38:02 +00005670 // Capture the variable that is being initialized and the style of
5671 // initialization.
5672 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5673
5674 // FIXME: Poor source location information.
5675 InitializationKind Kind
5676 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
5677 Init->getLocStart(),
5678 Init->getLocEnd())
5679 : InitializationKind::CreateCopy(VDecl->getLocation(),
5680 Init->getLocStart());
5681
Steve Naroff61091402007-09-12 14:07:44 +00005682 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00005683 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00005684 QualType DclT = VDecl->getType(), SavT = DclT;
John McCall1c9c3fd2010-10-15 04:57:14 +00005685 if (VDecl->isLocalVarDecl()) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00005686 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
Steve Naroff437b4d82007-09-12 20:13:48 +00005687 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff08899ff2008-04-15 22:42:06 +00005688 VDecl->setInvalidDecl();
5689 } else if (!VDecl->isInvalidDecl()) {
Eli Friedman78275202009-12-19 08:11:05 +00005690 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
John McCalldadc5752010-08-24 06:29:42 +00005691 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00005692 MultiExprArg(*this, &Init, 1),
Eli Friedman463e5232009-12-22 02:10:53 +00005693 &DclT);
5694 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00005695 VDecl->setInvalidDecl();
Eli Friedman78275202009-12-19 08:11:05 +00005696 return;
5697 }
Mike Stump11289f42009-09-09 15:08:12 +00005698
Eli Friedman463e5232009-12-22 02:10:53 +00005699 Init = Result.takeAs<Expr>();
5700
Anders Carlsson41e08812008-08-22 05:00:02 +00005701 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmance982572009-02-20 01:34:21 +00005702 // Don't check invalid declarations to avoid emitting useless diagnostics.
5703 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
John McCall8e7d6562010-08-26 03:08:43 +00005704 if (VDecl->getStorageClass() == SC_Static) // C99 6.7.8p4.
Anders Carlsson41e08812008-08-22 05:00:02 +00005705 CheckForConstantInitializer(Init, DclT);
5706 }
Steve Naroff61091402007-09-12 14:07:44 +00005707 }
Mike Stump11289f42009-09-09 15:08:12 +00005708 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00005709 VDecl->getLexicalDeclContext()->isRecord()) {
5710 // This is an in-class initialization for a static data member, e.g.,
5711 //
5712 // struct S {
5713 // static const int value = 17;
5714 // };
5715
John McCalldb768922010-09-10 23:21:22 +00005716 // Try to perform the initialization regardless.
5717 if (!VDecl->isInvalidDecl()) {
5718 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
5719 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5720 MultiExprArg(*this, &Init, 1),
5721 &DclT);
5722 if (Result.isInvalid()) {
5723 VDecl->setInvalidDecl();
5724 return;
5725 }
5726
5727 Init = Result.takeAs<Expr>();
5728 }
Douglas Gregor0c880302009-03-11 23:00:04 +00005729
5730 // C++ [class.mem]p4:
5731 // A member-declarator can contain a constant-initializer only
5732 // if it declares a static member (9.4) of const integral or
5733 // const enumeration type, see 9.4.2.
5734 QualType T = VDecl->getType();
John McCalldb768922010-09-10 23:21:22 +00005735
5736 // Do nothing on dependent types.
5737 if (T->isDependentType()) {
5738
5739 // Require constness.
5740 } else if (!T.isConstQualified()) {
5741 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
5742 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00005743 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00005744
5745 // We allow integer constant expressions in all cases.
5746 } else if (T->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00005747 // Check whether the expression is a constant expression.
5748 SourceLocation Loc;
5749 if (Init->isValueDependent())
5750 ; // Nothing to check.
5751 else if (Init->isIntegerConstantExpr(Context, &Loc))
5752 ; // Ok, it's an ICE!
5753 else if (Init->isEvaluatable(Context)) {
5754 // If we can constant fold the initializer through heroics, accept it,
5755 // but report this as a use of an extension for -pedantic.
5756 Diag(Loc, diag::ext_in_class_initializer_non_constant)
5757 << Init->getSourceRange();
5758 } else {
5759 // Otherwise, this is some crazy unknown case. Report the issue at the
5760 // location provided by the isIntegerConstantExpr failed check.
5761 Diag(Loc, diag::err_in_class_initializer_non_constant)
5762 << Init->getSourceRange();
5763 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00005764 }
5765
5766 // We allow floating-point constants as an extension in C++03, and
5767 // C++0x has far more complicated rules that we don't really
5768 // implement fully.
5769 } else {
5770 bool Allowed = false;
5771 if (getLangOptions().CPlusPlus0x) {
5772 Allowed = T->isLiteralType();
5773 } else if (T->isFloatingType()) { // also permits complex, which is ok
5774 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
5775 << T << Init->getSourceRange();
5776 Allowed = true;
5777 }
5778
5779 if (!Allowed) {
5780 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
5781 << T << Init->getSourceRange();
5782 VDecl->setInvalidDecl();
5783
5784 // TODO: there are probably expressions that pass here that shouldn't.
5785 } else if (!Init->isValueDependent() &&
5786 !Init->isConstantInitializer(Context, false)) {
5787 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
5788 << Init->getSourceRange();
5789 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00005790 }
5791 }
Steve Naroff08899ff2008-04-15 22:42:06 +00005792 } else if (VDecl->isFileVarDecl()) {
Douglas Gregord4e1fb52010-10-15 01:21:46 +00005793 if (VDecl->getStorageClassAsWritten() == SC_Extern &&
Douglas Gregorfceea362010-04-22 14:36:26 +00005794 (!getLangOptions().CPlusPlus ||
5795 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
Steve Naroff437b4d82007-09-12 20:13:48 +00005796 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00005797 if (!VDecl->isInvalidDecl()) {
5798 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
John McCalldadc5752010-08-24 06:29:42 +00005799 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00005800 MultiExprArg(*this, &Init, 1),
Eli Friedman463e5232009-12-22 02:10:53 +00005801 &DclT);
5802 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00005803 VDecl->setInvalidDecl();
Eli Friedman463e5232009-12-22 02:10:53 +00005804 return;
5805 }
5806
5807 Init = Result.takeAs<Expr>();
5808 }
Mike Stump11289f42009-09-09 15:08:12 +00005809
Anders Carlsson41e08812008-08-22 05:00:02 +00005810 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmance982572009-02-20 01:34:21 +00005811 // Don't check invalid declarations to avoid emitting useless diagnostics.
5812 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Anders Carlsson41e08812008-08-22 05:00:02 +00005813 // C99 6.7.8p4. All file scoped initializers need to be constant.
5814 CheckForConstantInitializer(Init, DclT);
5815 }
Steve Naroff61091402007-09-12 14:07:44 +00005816 }
5817 // If the type changed, it means we had an incomplete type that was
Mike Stump11289f42009-09-09 15:08:12 +00005818 // completed by the initializer. For example:
Steve Naroff61091402007-09-12 14:07:44 +00005819 // int ary[] = { 1, 3, 5 };
5820 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00005821 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff437b4d82007-09-12 20:13:48 +00005822 VDecl->setType(DclT);
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00005823 Init->setType(DclT);
5824 }
Chris Lattner88fdea82010-10-10 18:16:20 +00005825
John McCallacf0ee52010-10-08 02:01:28 +00005826 // Check any implicit conversions within the expression.
5827 CheckImplicitConversions(Init, VDecl->getLocation());
John McCall31168b02011-06-15 23:02:42 +00005828
5829 if (!VDecl->isInvalidDecl())
5830 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
5831
John McCall5d413782010-12-06 08:20:24 +00005832 Init = MaybeCreateExprWithCleanups(Init);
Steve Naroff61091402007-09-12 14:07:44 +00005833 // Attach the initializer to the decl.
Douglas Gregord5058122010-02-11 01:19:42 +00005834 VDecl->setInit(Init);
Douglas Gregorbeecd582009-04-21 17:11:58 +00005835
John McCall8b7fd8f12011-01-19 11:48:09 +00005836 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00005837}
5838
John McCalleae5acb2010-03-31 02:13:20 +00005839/// ActOnInitializerError - Given that there was an error parsing an
5840/// initializer for the given declaration, try to return to some form
5841/// of sanity.
John McCall48871652010-08-21 09:40:31 +00005842void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00005843 // Our main concern here is re-establishing invariants like "a
5844 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00005845 if (!D || D->isInvalidDecl()) return;
5846
5847 VarDecl *VD = dyn_cast<VarDecl>(D);
5848 if (!VD) return;
5849
Richard Smith30482bc2011-02-20 03:19:35 +00005850 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00005851 if (ParsingInitForAutoVars.count(D)) {
5852 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00005853 return;
5854 }
5855
John McCalleae5acb2010-03-31 02:13:20 +00005856 QualType Ty = VD->getType();
5857 if (Ty->isDependentType()) return;
5858
5859 // Require a complete type.
5860 if (RequireCompleteType(VD->getLocation(),
5861 Context.getBaseElementType(Ty),
5862 diag::err_typecheck_decl_incomplete_type)) {
5863 VD->setInvalidDecl();
5864 return;
5865 }
5866
5867 // Require an abstract type.
5868 if (RequireNonAbstractType(VD->getLocation(), Ty,
5869 diag::err_abstract_type_in_decl,
5870 AbstractVariableType)) {
5871 VD->setInvalidDecl();
5872 return;
5873 }
5874
5875 // Don't bother complaining about constructors or destructors,
5876 // though.
5877}
5878
John McCall48871652010-08-21 09:40:31 +00005879void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00005880 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00005881 // If there is no declaration, there was an error parsing it. Just ignore it.
5882 if (RealDecl == 0)
5883 return;
5884
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005885 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
5886 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00005887
Anders Carlssonae019932009-07-11 00:34:39 +00005888 // C++0x [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00005889 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00005890 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
5891 << Var->getDeclName() << Type;
5892 Var->setInvalidDecl();
5893 return;
5894 }
Mike Stump11289f42009-09-09 15:08:12 +00005895
Douglas Gregore6565622010-02-09 07:26:29 +00005896 switch (Var->isThisDeclarationADefinition()) {
5897 case VarDecl::Definition:
5898 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
5899 break;
5900
5901 // We have an out-of-line definition of a static data member
5902 // that has an in-class initializer, so we type-check this like
5903 // a declaration.
5904 //
5905 // Fall through
5906
5907 case VarDecl::DeclarationOnly:
5908 // It's only a declaration.
5909
5910 // Block scope. C99 6.7p7: If an identifier for an object is
5911 // declared with no linkage (C99 6.2.2p6), the type for the
5912 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00005913 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00005914 !Var->getLinkage() && !Var->isInvalidDecl() &&
5915 RequireCompleteType(Var->getLocation(), Type,
5916 diag::err_typecheck_decl_incomplete_type))
5917 Var->setInvalidDecl();
5918
5919 // Make sure that the type is not abstract.
5920 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
5921 RequireNonAbstractType(Var->getLocation(), Type,
5922 diag::err_abstract_type_in_decl,
5923 AbstractVariableType))
5924 Var->setInvalidDecl();
5925 return;
5926
5927 case VarDecl::TentativeDefinition:
5928 // File scope. C99 6.9.2p2: A declaration of an identifier for an
5929 // object that has file scope without an initializer, and without a
5930 // storage-class specifier or with the storage-class specifier "static",
5931 // constitutes a tentative definition. Note: A tentative definition with
5932 // external linkage is valid (C99 6.2.2p5).
5933 if (!Var->isInvalidDecl()) {
5934 if (const IncompleteArrayType *ArrayT
5935 = Context.getAsIncompleteArrayType(Type)) {
5936 if (RequireCompleteType(Var->getLocation(),
5937 ArrayT->getElementType(),
5938 diag::err_illegal_decl_array_incomplete_type))
5939 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00005940 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00005941 // C99 6.9.2p3: If the declaration of an identifier for an object is
5942 // a tentative definition and has internal linkage (C99 6.2.2p3), the
5943 // declared type shall not be an incomplete type.
5944 // NOTE: code such as the following
5945 // static struct s;
5946 // struct s { int a; };
5947 // is accepted by gcc. Hence here we issue a warning instead of
5948 // an error and we do not invalidate the static declaration.
5949 // NOTE: to avoid multiple warnings, only check the first declaration.
5950 if (Var->getPreviousDeclaration() == 0)
5951 RequireCompleteType(Var->getLocation(), Type,
5952 diag::ext_typecheck_decl_incomplete_type);
5953 }
5954 }
5955
5956 // Record the tentative definition; we're done.
5957 if (!Var->isInvalidDecl())
5958 TentativeDefinitions.push_back(Var);
5959 return;
5960 }
5961
5962 // Provide a specific diagnostic for uninitialized variable
5963 // definitions with incomplete array type.
5964 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00005965 Diag(Var->getLocation(),
5966 diag::err_typecheck_incomplete_array_needs_initializer);
5967 Var->setInvalidDecl();
5968 return;
5969 }
5970
John McCalla755f0f2010-08-01 01:25:24 +00005971 // Provide a specific diagnostic for uninitialized variable
5972 // definitions with reference type.
5973 if (Type->isReferenceType()) {
5974 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
5975 << Var->getDeclName()
5976 << SourceRange(Var->getLocation(), Var->getLocation());
5977 Var->setInvalidDecl();
5978 return;
5979 }
Douglas Gregore6565622010-02-09 07:26:29 +00005980
5981 // Do not attempt to type-check the default initializer for a
5982 // variable with dependent type.
5983 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00005984 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005985
Douglas Gregore6565622010-02-09 07:26:29 +00005986 if (Var->isInvalidDecl())
5987 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00005988
Douglas Gregore6565622010-02-09 07:26:29 +00005989 if (RequireCompleteType(Var->getLocation(),
5990 Context.getBaseElementType(Type),
5991 diag::err_typecheck_decl_incomplete_type)) {
5992 Var->setInvalidDecl();
5993 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005994 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005995
Douglas Gregore6565622010-02-09 07:26:29 +00005996 // The variable can not have an abstract class type.
5997 if (RequireNonAbstractType(Var->getLocation(), Type,
5998 diag::err_abstract_type_in_decl,
5999 AbstractVariableType)) {
6000 Var->setInvalidDecl();
6001 return;
6002 }
6003
Douglas Gregor9574af62011-05-21 17:52:48 +00006004 // Check for jumps past the implicit initializer. C++0x
6005 // clarifies that this applies to a "variable with automatic
6006 // storage duration", not a "local variable".
6007 // C++0x [stmt.dcl]p3
6008 // A program that jumps from a point where a variable with automatic
6009 // storage duration is not in scope to a point where it is in scope is
6010 // ill-formed unless the variable has scalar type, class type with a
6011 // trivial default constructor and a trivial destructor, a cv-qualified
6012 // version of one of these types, or an array of one of the preceding
6013 // types and is declared without an initializer.
6014 if (getLangOptions().CPlusPlus && Var->hasLocalStorage()) {
6015 if (const RecordType *Record
6016 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00006017 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor9574af62011-05-21 17:52:48 +00006018 if ((!getLangOptions().CPlusPlus0x && !CXXRecord->isPOD()) ||
6019 (getLangOptions().CPlusPlus0x &&
6020 (!CXXRecord->hasTrivialDefaultConstructor() ||
Douglas Gregor22ae6962011-05-27 21:28:00 +00006021 !CXXRecord->hasTrivialDestructor())))
Alexis Hunt466627c2011-05-11 22:50:12 +00006022 getCurFunction()->setHasBranchProtectedScope();
6023 }
Douglas Gregore6565622010-02-09 07:26:29 +00006024 }
Douglas Gregor9574af62011-05-21 17:52:48 +00006025
6026 // C++03 [dcl.init]p9:
6027 // If no initializer is specified for an object, and the
6028 // object is of (possibly cv-qualified) non-POD class type (or
6029 // array thereof), the object shall be default-initialized; if
6030 // the object is of const-qualified type, the underlying class
6031 // type shall have a user-declared default
6032 // constructor. Otherwise, if no initializer is specified for
6033 // a non- static object, the object and its subobjects, if
6034 // any, have an indeterminate initial value); if the object
6035 // or any of its subobjects are of const-qualified type, the
6036 // program is ill-formed.
6037 // C++0x [dcl.init]p11:
6038 // If no initializer is specified for an object, the object is
6039 // default-initialized; [...].
6040 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
6041 InitializationKind Kind
6042 = InitializationKind::CreateDefault(Var->getLocation());
6043
6044 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
6045 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
6046 MultiExprArg(*this, 0, 0));
6047 if (Init.isInvalid())
6048 Var->setInvalidDecl();
6049 else if (Init.get())
6050 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Douglas Gregor589973b2010-03-08 02:45:10 +00006051
John McCall8b7fd8f12011-01-19 11:48:09 +00006052 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00006053 }
6054}
6055
Richard Smith02e85f32011-04-14 22:09:26 +00006056void Sema::ActOnCXXForRangeDecl(Decl *D) {
6057 VarDecl *VD = dyn_cast<VarDecl>(D);
6058 if (!VD) {
6059 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
6060 D->setInvalidDecl();
6061 return;
6062 }
6063
6064 VD->setCXXForRangeDecl(true);
6065
6066 // for-range-declaration cannot be given a storage class specifier.
6067 int Error = -1;
6068 switch (VD->getStorageClassAsWritten()) {
6069 case SC_None:
6070 break;
6071 case SC_Extern:
6072 Error = 0;
6073 break;
6074 case SC_Static:
6075 Error = 1;
6076 break;
6077 case SC_PrivateExtern:
6078 Error = 2;
6079 break;
6080 case SC_Auto:
6081 Error = 3;
6082 break;
6083 case SC_Register:
6084 Error = 4;
6085 break;
6086 }
6087 // FIXME: constexpr isn't allowed here.
6088 //if (DS.isConstexprSpecified())
6089 // Error = 5;
6090 if (Error != -1) {
6091 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
6092 << VD->getDeclName() << Error;
6093 D->setInvalidDecl();
6094 }
6095}
6096
John McCall8b7fd8f12011-01-19 11:48:09 +00006097void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
6098 if (var->isInvalidDecl()) return;
6099
John McCall31168b02011-06-15 23:02:42 +00006100 // In ARC, don't allow jumps past the implicit initialization of a
6101 // local retaining variable.
6102 if (getLangOptions().ObjCAutoRefCount &&
6103 var->hasLocalStorage()) {
6104 switch (var->getType().getObjCLifetime()) {
6105 case Qualifiers::OCL_None:
6106 case Qualifiers::OCL_ExplicitNone:
6107 case Qualifiers::OCL_Autoreleasing:
6108 break;
6109
6110 case Qualifiers::OCL_Weak:
6111 case Qualifiers::OCL_Strong:
6112 getCurFunction()->setHasBranchProtectedScope();
6113 break;
6114 }
6115 }
6116
John McCall8b7fd8f12011-01-19 11:48:09 +00006117 // All the following checks are C++ only.
6118 if (!getLangOptions().CPlusPlus) return;
6119
6120 QualType baseType = Context.getBaseElementType(var->getType());
6121 if (baseType->isDependentType()) return;
6122
6123 // __block variables might require us to capture a copy-initializer.
6124 if (var->hasAttr<BlocksAttr>()) {
6125 // It's currently invalid to ever have a __block variable with an
6126 // array type; should we diagnose that here?
6127
6128 // Regardless, we don't want to ignore array nesting when
6129 // constructing this copy.
6130 QualType type = var->getType();
6131
6132 if (type->isStructureOrClassType()) {
6133 SourceLocation poi = var->getLocation();
6134 Expr *varRef = new (Context) DeclRefExpr(var, type, VK_LValue, poi);
6135 ExprResult result =
6136 PerformCopyInitialization(
6137 InitializedEntity::InitializeBlock(poi, type, false),
6138 poi, Owned(varRef));
6139 if (!result.isInvalid()) {
6140 result = MaybeCreateExprWithCleanups(result);
6141 Expr *init = result.takeAs<Expr>();
6142 Context.setBlockVarCopyInits(var, init);
6143 }
6144 }
6145 }
6146
6147 // Check for global constructors.
6148 if (!var->getDeclContext()->isDependentContext() &&
6149 var->hasGlobalStorage() &&
6150 !var->isStaticLocal() &&
6151 var->getInit() &&
6152 !var->getInit()->isConstantInitializer(Context,
6153 baseType->isReferenceType()))
6154 Diag(var->getLocation(), diag::warn_global_constructor)
6155 << var->getInit()->getSourceRange();
6156
6157 // Require the destructor.
6158 if (const RecordType *recordType = baseType->getAs<RecordType>())
6159 FinalizeVarWithDestructor(var, recordType);
6160}
6161
Richard Smithb2bc2e62011-02-21 20:05:19 +00006162/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
6163/// any semantic actions necessary after any initializer has been attached.
6164void
6165Sema::FinalizeDeclaration(Decl *ThisDecl) {
6166 // Note that we are no longer parsing the initializer for this declaration.
6167 ParsingInitForAutoVars.erase(ThisDecl);
6168}
6169
John McCallba7bf592010-08-24 05:47:05 +00006170Sema::DeclGroupPtrTy
6171Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
6172 Decl **Group, unsigned NumDecls) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006173 SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00006174
6175 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00006176 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00006177
Richard Smith2abf6762011-02-23 00:37:57 +00006178 for (unsigned i = 0; i != NumDecls; ++i)
6179 if (Decl *D = Group[i])
6180 Decls.push_back(D);
6181
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006182 return BuildDeclaratorGroup(Decls.data(), Decls.size(),
Richard Smith2abf6762011-02-23 00:37:57 +00006183 DS.getTypeSpecType() == DeclSpec::TST_auto);
6184}
6185
6186/// BuildDeclaratorGroup - convert a list of declarations into a declaration
6187/// group, performing any necessary semantic checking.
6188Sema::DeclGroupPtrTy
6189Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
6190 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00006191 // C++0x [dcl.spec.auto]p7:
6192 // If the type deduced for the template parameter U is not the same in each
6193 // deduction, the program is ill-formed.
6194 // FIXME: When initializer-list support is added, a distinction is needed
6195 // between the deduced type U and the deduced type which 'auto' stands for.
6196 // auto a = 0, b = { 1, 2, 3 };
6197 // is legal because the deduced type U is 'int' in both cases.
Richard Smith2abf6762011-02-23 00:37:57 +00006198 if (TypeMayContainAuto && NumDecls > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00006199 QualType Deduced;
6200 CanQualType DeducedCanon;
6201 VarDecl *DeducedDecl = 0;
6202 for (unsigned i = 0; i != NumDecls; ++i) {
6203 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
6204 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00006205 // Don't reissue diagnostics when instantiating a template.
6206 if (AT && D->isInvalidDecl())
6207 break;
Richard Smith30482bc2011-02-20 03:19:35 +00006208 if (AT && AT->isDeduced()) {
6209 QualType U = AT->getDeducedType();
6210 CanQualType UCanon = Context.getCanonicalType(U);
6211 if (Deduced.isNull()) {
6212 Deduced = U;
6213 DeducedCanon = UCanon;
6214 DeducedDecl = D;
6215 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00006216 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
6217 diag::err_auto_different_deductions)
Richard Smith30482bc2011-02-20 03:19:35 +00006218 << Deduced << DeducedDecl->getDeclName()
6219 << U << D->getDeclName()
6220 << DeducedDecl->getInit()->getSourceRange()
6221 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00006222 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00006223 break;
6224 }
6225 }
6226 }
6227 }
6228 }
6229
Richard Smith2abf6762011-02-23 00:37:57 +00006230 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
Chris Lattner776fac82007-06-09 00:53:06 +00006231}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00006232
Chris Lattner5bbb3c82009-03-29 16:50:03 +00006233
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006234/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
6235/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00006236Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00006237 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00006238
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006239 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
John McCall8e7d6562010-08-26 03:08:43 +00006240 VarDecl::StorageClass StorageClass = SC_None;
6241 VarDecl::StorageClass StorageClassAsWritten = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00006242 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00006243 StorageClass = SC_Register;
6244 StorageClassAsWritten = SC_Register;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00006245 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006246 Diag(DS.getStorageClassSpecLoc(),
6247 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00006248 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006249 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006250
6251 if (D.getDeclSpec().isThreadSpecified())
6252 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Richard Smitha77a0a62011-08-15 21:04:07 +00006253 if (D.getDeclSpec().isConstexprSpecified())
6254 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6255 << 0;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006256
Eli Friedman574c7452009-04-07 19:37:57 +00006257 DiagnoseFunctionSpecifiers(D);
6258
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00006259 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00006260 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00006261
Douglas Gregor27b4c162010-12-23 22:44:42 +00006262 if (getLangOptions().CPlusPlus) {
6263 // Check that there are no default arguments inside the type of this
6264 // parameter.
6265 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00006266
6267 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
6268 if (D.getCXXScopeSpec().isSet()) {
6269 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
6270 << D.getCXXScopeSpec().getRange();
6271 D.getCXXScopeSpec().clear();
6272 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00006273 }
6274
Alexis Hunta56cbcc2010-11-03 01:07:06 +00006275 // Ensure we have a valid name
6276 IdentifierInfo *II = 0;
6277 if (D.hasName()) {
6278 II = D.getIdentifier();
6279 if (!II) {
6280 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
6281 << GetNameForDeclarator(D).getName().getAsString();
6282 D.setInvalidType(true);
6283 }
6284 }
6285
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00006286 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00006287 if (II) {
John McCall84f02672010-03-18 06:42:38 +00006288 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
6289 ForRedeclaration);
6290 LookupName(R, S);
6291 if (R.isSingleResult()) {
6292 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00006293 if (PrevDecl->isTemplateParameter()) {
6294 // Maybe we will complain about the shadowed template parameter.
6295 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
6296 // Just pretend that we didn't see the previous declaration.
6297 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00006298 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00006299 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00006300 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006301
Chris Lattnerd9773512009-01-21 02:38:50 +00006302 // Recover by removing the name
6303 II = 0;
6304 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00006305 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00006306 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006307 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00006308 }
Steve Naroff773df5c2007-08-07 22:44:21 +00006309
John McCallf7b2fb52010-01-22 00:28:27 +00006310 // Temporarily put parameter variables in the translation unit, not
6311 // the enclosing context. This prevents them from accidentally
6312 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00006313 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00006314 D.getSourceRange().getBegin(),
6315 D.getIdentifierLoc(), II,
6316 parmDeclType, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00006317 StorageClass, StorageClassAsWritten);
Mike Stump11289f42009-09-09 15:08:12 +00006318
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006319 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00006320 New->setInvalidDecl();
6321
6322 assert(S->isFunctionPrototypeScope());
6323 assert(S->getFunctionPrototypeDepth() >= 1);
6324 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
6325 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00006326
Douglas Gregor91f84212008-12-11 16:49:14 +00006327 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00006328 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00006329 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00006330 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00006331
Douglas Gregor758a8692009-06-17 21:51:59 +00006332 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00006333
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006334 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00006335 Diag(New->getLocation(), diag::err_block_on_nonlocal);
6336 }
John McCall48871652010-08-21 09:40:31 +00006337 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00006338}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00006339
John McCalla3ccba02010-06-04 11:21:44 +00006340/// \brief Synthesizes a variable for a parameter arising from a
6341/// typedef.
6342ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
6343 SourceLocation Loc,
6344 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00006345 /* FIXME: setting StartLoc == Loc.
6346 Would it be worth to modify callers so as to provide proper source
6347 location for the unnamed parameters, embedding the parameter's type? */
6348 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00006349 T, Context.getTrivialTypeSourceInfo(T, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00006350 SC_None, SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00006351 Param->setImplicit();
6352 return Param;
6353}
6354
John McCallc5990642010-08-24 09:05:15 +00006355void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
6356 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00006357 // Don't diagnose unused-parameter errors in template instantiations; we
6358 // will already have done so in the template itself.
6359 if (!ActiveTemplateInstantiations.empty())
6360 return;
6361
6362 for (; Param != ParamEnd; ++Param) {
6363 if (!(*Param)->isUsed() && (*Param)->getDeclName() &&
6364 !(*Param)->hasAttr<UnusedAttr>()) {
6365 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
6366 << (*Param)->getDeclName();
6367 }
6368 }
6369}
6370
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006371void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
6372 ParmVarDecl * const *ParamEnd,
6373 QualType ReturnTy,
6374 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006375 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006376 return;
6377
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006378 // Warn if the return value is pass-by-value and larger than the specified
6379 // threshold.
John McCall31168b02011-06-15 23:02:42 +00006380 if (ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006381 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006382 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006383 Diag(D->getLocation(), diag::warn_return_value_size)
6384 << D->getDeclName() << Size;
6385 }
6386
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006387 // Warn if any parameter is pass-by-value and larger than the specified
6388 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006389 for (; Param != ParamEnd; ++Param) {
6390 QualType T = (*Param)->getType();
John McCall31168b02011-06-15 23:02:42 +00006391 if (!T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006392 continue;
6393 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006394 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006395 Diag((*Param)->getLocation(), diag::warn_parameter_size)
6396 << (*Param)->getDeclName() << Size;
6397 }
6398}
6399
Abramo Bagnaradff19302011-03-08 08:55:46 +00006400ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
6401 SourceLocation NameLoc, IdentifierInfo *Name,
6402 QualType T, TypeSourceInfo *TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00006403 VarDecl::StorageClass StorageClass,
6404 VarDecl::StorageClass StorageClassAsWritten) {
John McCall31168b02011-06-15 23:02:42 +00006405 // In ARC, infer a lifetime qualifier for appropriate parameter types.
6406 if (getLangOptions().ObjCAutoRefCount &&
6407 T.getObjCLifetime() == Qualifiers::OCL_None &&
6408 T->isObjCLifetimeType()) {
6409
6410 Qualifiers::ObjCLifetime lifetime;
6411
6412 // Special cases for arrays:
6413 // - if it's const, use __unsafe_unretained
6414 // - otherwise, it's an error
6415 if (T->isArrayType()) {
6416 if (!T.isConstQualified()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00006417 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
John McCall31168b02011-06-15 23:02:42 +00006418 << TSInfo->getTypeLoc().getSourceRange();
6419 }
6420 lifetime = Qualifiers::OCL_ExplicitNone;
6421 } else {
6422 lifetime = T->getObjCARCImplicitLifetime();
6423 }
6424 T = Context.getLifetimeQualifiedType(T, lifetime);
6425 }
6426
Abramo Bagnaradff19302011-03-08 08:55:46 +00006427 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00006428 Context.getAdjustedParameterType(T),
6429 TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00006430 StorageClass, StorageClassAsWritten,
6431 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00006432
6433 // Parameters can not be abstract class types.
6434 // For record types, this is done by the AbstractClassUsageDiagnoser once
6435 // the class has been completely parsed.
6436 if (!CurContext->isRecord() &&
6437 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
6438 AbstractParamType))
6439 New->setInvalidDecl();
6440
6441 // Parameter declarators cannot be interface types. All ObjC objects are
6442 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00006443 if (T->isObjCObjectType()) {
Douglas Gregor940bca72010-04-12 07:48:19 +00006444 Diag(NameLoc,
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00006445 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
6446 << FixItHint::CreateInsertion(NameLoc, "*");
6447 T = Context.getObjCObjectPointerType(T);
6448 New->setType(T);
Douglas Gregor940bca72010-04-12 07:48:19 +00006449 }
6450
6451 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
6452 // duration shall not be qualified by an address-space qualifier."
6453 // Since all parameters have automatic store duration, they can not have
6454 // an address space.
6455 if (T.getAddressSpace() != 0) {
6456 Diag(NameLoc, diag::err_arg_with_address_space);
6457 New->setInvalidDecl();
6458 }
6459
6460 return New;
6461}
6462
Douglas Gregor170512f2009-04-01 23:51:29 +00006463void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
6464 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006465 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006466
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00006467 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
6468 // for a K&R function.
6469 if (!FTI.hasPrototype) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00006470 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
6471 --i;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006472 if (FTI.ArgInfo[i].Param == 0) {
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00006473 llvm::SmallString<256> Code;
6474 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar07d07852009-10-18 21:17:35 +00006475 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00006476 << ";\n";
Chris Lattner4bd8dd82008-11-19 08:23:25 +00006477 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregor170512f2009-04-01 23:51:29 +00006478 << FTI.ArgInfo[i].Ident
Douglas Gregora771f462010-03-31 17:46:05 +00006479 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00006480
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00006481 // Implicitly declare the argument as type 'int' for lack of a better
6482 // type.
John McCall084e83d2011-03-24 11:26:52 +00006483 AttributeFactory attrs;
6484 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006485 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00006486 unsigned DiagID; // unused
Mike Stump11289f42009-09-09 15:08:12 +00006487 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCall49bfce42009-08-03 20:12:06 +00006488 PrevSpec, DiagID);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006489 Declarator ParamD(DS, Declarator::KNRTypeListContext);
6490 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor9aa89042009-01-23 16:23:13 +00006491 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00006492 }
6493 }
Mike Stump11289f42009-09-09 15:08:12 +00006494 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00006495}
6496
John McCall48871652010-08-21 09:40:31 +00006497Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
6498 Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00006499 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006500 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00006501 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00006502
John McCall48871652010-08-21 09:40:31 +00006503 Decl *DP = HandleDeclarator(ParentScope, D,
6504 MultiTemplateParamsArg(*this),
6505 /*IsFunctionDefinition=*/true);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00006506 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006507}
6508
Anders Carlsson31c7e882009-12-09 03:30:09 +00006509static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
6510 // Don't warn about invalid declarations.
6511 if (FD->isInvalidDecl())
6512 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006513
Anders Carlsson31c7e882009-12-09 03:30:09 +00006514 // Or declarations that aren't global.
6515 if (!FD->isGlobal())
6516 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006517
Anders Carlsson31c7e882009-12-09 03:30:09 +00006518 // Don't warn about C++ member functions.
6519 if (isa<CXXMethodDecl>(FD))
6520 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006521
Anders Carlsson31c7e882009-12-09 03:30:09 +00006522 // Don't warn about 'main'.
6523 if (FD->isMain())
6524 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006525
Anders Carlsson31c7e882009-12-09 03:30:09 +00006526 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00006527 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00006528 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006529
6530 // Don't warn about function templates.
6531 if (FD->getDescribedFunctionTemplate())
6532 return false;
6533
6534 // Don't warn about function template specializations.
6535 if (FD->isFunctionTemplateSpecialization())
6536 return false;
6537
Anders Carlsson31c7e882009-12-09 03:30:09 +00006538 bool MissingPrototype = true;
6539 for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
6540 Prev; Prev = Prev->getPreviousDeclaration()) {
6541 // Ignore any declarations that occur in function or method
6542 // scope, because they aren't visible from the header.
6543 if (Prev->getDeclContext()->isFunctionOrMethod())
6544 continue;
6545
6546 MissingPrototype = !Prev->getType()->isFunctionProtoType();
6547 break;
6548 }
6549
6550 return MissingPrototype;
6551}
6552
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00006553void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
6554 // Don't complain if we're in GNU89 mode and the previous definition
6555 // was an extern inline function.
6556 const FunctionDecl *Definition;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006557 if (FD->isDefined(Definition) &&
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00006558 !canRedefineFunction(Definition, getLangOptions())) {
6559 if (getLangOptions().GNUMode && Definition->isInlineSpecified() &&
6560 Definition->getStorageClass() == SC_Extern)
6561 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
6562 << FD->getDeclName() << getLangOptions().CPlusPlus;
6563 else
6564 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
6565 Diag(Definition->getLocation(), diag::note_previous_definition);
6566 }
6567}
6568
John McCall48871652010-08-21 09:40:31 +00006569Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00006570 // Clear the last template instantiation error context.
6571 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
6572
Douglas Gregor17a7c122009-06-24 00:54:41 +00006573 if (!D)
6574 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00006575 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00006576
John McCall48871652010-08-21 09:40:31 +00006577 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00006578 FD = FunTmpl->getTemplatedDecl();
6579 else
John McCall48871652010-08-21 09:40:31 +00006580 FD = cast<FunctionDecl>(D);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00006581
Douglas Gregor9a28e842010-03-01 23:15:13 +00006582 // Enter a new function scope
6583 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00006584
Douglas Gregorcad304ba2008-10-29 15:10:40 +00006585 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00006586 if (!FD->isLateTemplateParsed())
6587 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00006588
Douglas Gregor75a45ba2009-02-16 17:45:42 +00006589 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00006590 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor7a0febe2009-02-17 16:03:01 +00006591 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00006592 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00006593 FD->setInvalidDecl();
6594 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00006595 }
6596
Eli Friedman9ad72442009-03-04 07:30:59 +00006597 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00006598 // (C99 6.9.1p3, C++ [dcl.fct]p6).
6599 QualType ResultType = FD->getResultType();
6600 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00006601 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00006602 RequireCompleteType(FD->getLocation(), ResultType,
6603 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00006604 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00006605
Douglas Gregorf1b876d2009-03-31 16:35:03 +00006606 // GNU warning -Wmissing-prototypes:
6607 // Warn if a global function is defined without a previous
6608 // prototype declaration. This warning is issued even if the
6609 // definition itself provides a prototype. The aim is to detect
6610 // global functions that fail to be declared in header files.
Anders Carlsson31c7e882009-12-09 03:30:09 +00006611 if (ShouldWarnAboutMissingPrototype(FD))
6612 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Douglas Gregorf1b876d2009-03-31 16:35:03 +00006613
Douglas Gregor67da0d92009-05-15 17:59:04 +00006614 if (FnBodyScope)
6615 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006616
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006617 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00006618 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
6619 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006620
6621 // Introduce our parameters into the function scope
6622 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
6623 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc72e6452009-01-09 18:51:29 +00006624 Param->setOwningFunction(FD);
6625
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006626 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00006627 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006628 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00006629
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00006630 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00006631 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00006632 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006633
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006634 // Checking attributes of current function definition
6635 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006636 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
6637 if (DA && (!FD->getAttr<DLLExportAttr>())) {
6638 // dllimport attribute cannot be directly applied to definition.
Francois Pichet3096d202011-03-29 10:39:17 +00006639 // Microsoft accepts dllimport for functions defined within class scope.
6640 if (!DA->isInherited() &&
6641 !(LangOpts.Microsoft && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006642 Diag(FD->getLocation(),
6643 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
6644 << "dllimport";
6645 FD->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00006646 return FD;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00006647 }
6648
6649 // Visual C++ appears to not think this is an issue, so only issue
6650 // a warning when Microsoft extensions are disabled.
6651 if (!LangOpts.Microsoft) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006652 // If a symbol previously declared dllimport is later defined, the
6653 // attribute is ignored in subsequent references, and a warning is
6654 // emitted.
6655 Diag(FD->getLocation(),
6656 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar56df9772010-08-17 22:39:59 +00006657 << FD->getName() << "dllimport";
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006658 }
6659 }
John McCall48871652010-08-21 09:40:31 +00006660 return FD;
Chris Lattnere168f762006-11-10 05:29:30 +00006661}
6662
Douglas Gregor6fd1b182010-05-15 06:01:05 +00006663/// \brief Given the set of return statements within a function body,
6664/// compute the variables that are subject to the named return value
6665/// optimization.
6666///
6667/// Each of the variables that is subject to the named return value
6668/// optimization will be marked as NRVO variables in the AST, and any
6669/// return statement that has a marked NRVO variable as its NRVO candidate can
6670/// use the named return value optimization.
6671///
6672/// This function applies a very simplistic algorithm for NRVO: if every return
6673/// statement in the function has the same NRVO candidate, that candidate is
6674/// the NRVO variable.
6675///
6676/// FIXME: Employ a smarter algorithm that accounts for multiple return
6677/// statements and the lifetimes of the NRVO candidates. We should be able to
6678/// find a maximal set of NRVO variables.
Douglas Gregor49695f02011-09-06 20:46:03 +00006679void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCallaab3e412010-08-25 08:40:02 +00006680 ReturnStmt **Returns = Scope->Returns.data();
6681
Douglas Gregor6fd1b182010-05-15 06:01:05 +00006682 const VarDecl *NRVOCandidate = 0;
John McCallaab3e412010-08-25 08:40:02 +00006683 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00006684 if (!Returns[I]->getNRVOCandidate())
6685 return;
6686
6687 if (!NRVOCandidate)
6688 NRVOCandidate = Returns[I]->getNRVOCandidate();
6689 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
6690 return;
6691 }
6692
6693 if (NRVOCandidate)
6694 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
6695}
6696
John McCallfaf5fb42010-08-26 23:41:50 +00006697Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Douglas Gregor67da0d92009-05-15 17:59:04 +00006698 return ActOnFinishFunctionBody(D, move(BodyArg), false);
6699}
6700
John McCallb268a282010-08-23 23:25:46 +00006701Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
6702 bool IsInstantiation) {
Douglas Gregorc45a40a2009-08-22 00:34:47 +00006703 FunctionDecl *FD = 0;
6704 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
6705 if (FunTmpl)
6706 FD = FunTmpl->getTemplatedDecl();
6707 else
6708 FD = dyn_cast_or_null<FunctionDecl>(dcl);
6709
Ted Kremenek0b405322010-03-23 00:13:23 +00006710 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00006711 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00006712
Douglas Gregorc45a40a2009-08-22 00:34:47 +00006713 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00006714 FD->setBody(Body);
Ted Kremenek918fe842010-03-20 21:06:02 +00006715 if (FD->isMain()) {
Mike Stump8e79f992009-07-24 02:49:01 +00006716 // C and C++ allow for main to automagically return 0.
John McCallcaa19452009-07-28 01:00:58 +00006717 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
6718 FD->setHasImplicitReturnZero(true);
Ted Kremenek0b405322010-03-23 00:13:23 +00006719 WP.disableCheckFallThrough();
Douglas Gregor9824aec2011-07-11 15:24:01 +00006720 } else if (FD->hasAttr<NakedAttr>()) {
6721 // If the function is marked 'naked', don't complain about missing return
6722 // statements.
6723 WP.disableCheckFallThrough();
Ted Kremenek918fe842010-03-20 21:06:02 +00006724 }
Mike Stump11289f42009-09-09 15:08:12 +00006725
Francois Pichet3abc9b82011-05-11 02:14:46 +00006726 // MSVC permits the use of pure specifier (=0) on function definition,
6727 // defined at class scope, warn about this non standard construct.
6728 if (getLangOptions().Microsoft && FD->isPure())
6729 Diag(FD->getLocation(), diag::warn_pure_function_definition);
6730
Douglas Gregor88d292c2010-05-13 16:44:06 +00006731 if (!FD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006732 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006733 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
6734 FD->getResultType(), FD);
Douglas Gregor88d292c2010-05-13 16:44:06 +00006735
6736 // If this is a constructor, we need a vtable.
6737 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
6738 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00006739
Douglas Gregor49695f02011-09-06 20:46:03 +00006740 computeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00006741 }
6742
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00006743 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00006744 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00006745 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00006746 MD->setBody(Body);
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00006747 if (Body)
6748 MD->setEndLoc(Body->getLocEnd());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006749 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006750 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006751 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
6752 MD->getResultType(), MD);
Douglas Gregore3f3ea02011-09-06 20:33:37 +00006753
6754 if (Body)
Douglas Gregor49695f02011-09-06 20:46:03 +00006755 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006756 }
Nico Weber715abaf2011-08-22 17:25:57 +00006757 if (ObjCShouldCallSuperDealloc) {
6758 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc);
6759 ObjCShouldCallSuperDealloc = false;
6760 }
Nico Weber1fb82662011-08-28 22:35:17 +00006761 if (ObjCShouldCallSuperFinalize) {
6762 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize);
6763 ObjCShouldCallSuperFinalize = false;
6764 }
Ted Kremenek5a201952009-02-07 01:47:29 +00006765 } else {
John McCall48871652010-08-21 09:40:31 +00006766 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00006767 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00006768
Nico Weber715abaf2011-08-22 17:25:57 +00006769 assert(!ObjCShouldCallSuperDealloc && "This should only be set for "
6770 "ObjC methods, which should have been handled in the block above.");
Nico Weber1fb82662011-08-28 22:35:17 +00006771 assert(!ObjCShouldCallSuperFinalize && "This should only be set for "
6772 "ObjC methods, which should have been handled in the block above.");
Nico Weber715abaf2011-08-22 17:25:57 +00006773
Chris Lattnere2473062007-05-28 06:28:18 +00006774 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00006775 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00006776 // C++ constructors that have function-try-blocks can't have return
6777 // statements in the handlers of that block. (C++ [except.handle]p14)
6778 // Verify this.
6779 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
6780 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
6781
Richard Smithdef8bdb2011-08-12 18:44:32 +00006782 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00006783 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +00006784 !dcl->isInvalidDecl() &&
John McCall31168b02011-06-15 23:02:42 +00006785 !hasAnyUnrecoverableErrorsInThisFunction())
Douglas Gregor9a28e842010-03-01 23:15:13 +00006786 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00006787
John McCalldeb646e2010-08-04 01:04:25 +00006788 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
6789 if (!Destructor->getParent()->isDependentType())
6790 CheckDestructor(Destructor);
6791
John McCalla6309952010-03-16 21:39:52 +00006792 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6793 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +00006794 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00006795
6796 // If any errors have occurred, clear out any temporaries that may have
6797 // been leftover. This ensures that these temporaries won't be picked up for
6798 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +00006799 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCall31168b02011-06-15 23:02:42 +00006800 PP.getDiagnostics().getSuppressAllDiagnostics()) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00006801 ExprTemporaries.clear();
John McCall31168b02011-06-15 23:02:42 +00006802 ExprNeedsCleanups = false;
6803 } else if (!isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +00006804 // Since the body is valid, issue any analysis-based warnings that are
6805 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +00006806 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +00006807 }
6808
Douglas Gregor9a28e842010-03-01 23:15:13 +00006809 assert(ExprTemporaries.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +00006810 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Douglas Gregor9a28e842010-03-01 23:15:13 +00006811 }
6812
John McCalle99d5f32010-03-25 22:08:03 +00006813 if (!IsInstantiation)
6814 PopDeclContext();
6815
Ted Kremenek1767a272011-02-23 01:51:48 +00006816 PopFunctionOrBlockScope(ActivePolicy, dcl);
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00006817
Douglas Gregora7e3ea32009-11-15 07:07:58 +00006818 // If any errors have occurred, clear out any temporaries that may have
6819 // been leftover. This ensures that these temporaries won't be picked up for
6820 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +00006821 if (getDiagnostics().hasErrorOccurred()) {
Douglas Gregora7e3ea32009-11-15 07:07:58 +00006822 ExprTemporaries.clear();
John McCall31168b02011-06-15 23:02:42 +00006823 ExprNeedsCleanups = false;
6824 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00006825
John McCall48871652010-08-21 09:40:31 +00006826 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00006827}
6828
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00006829
6830/// When we finish delayed parsing of an attribute, we must attach it to the
6831/// relevant Decl.
6832void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
6833 ParsedAttributes &Attrs) {
6834 ProcessDeclAttributeList(S, D, Attrs.getList());
6835}
6836
6837
Chris Lattnerac18be92006-11-20 06:49:47 +00006838/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
6839/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00006840NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00006841 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00006842 // Before we produce a declaration for an implicitly defined
6843 // function, see whether there was a locally-scoped declaration of
6844 // this name as a function or variable. If so, use that
6845 // (non-visible) declaration, and complain about it.
6846 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregordc5c9582011-07-28 14:20:37 +00006847 = findLocallyScopedExternalDecl(&II);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00006848 if (Pos != LocallyScopedExternalDecls.end()) {
6849 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
6850 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
6851 return Pos->second;
6852 }
6853
Chris Lattner00e26072008-05-05 21:18:06 +00006854 // Extension in C99. Legal in C90, but warn about it.
Daniel Dunbar07d07852009-10-18 21:17:35 +00006855 if (II.getName().startswith("__builtin_"))
Douglas Gregor56fbc372009-09-28 21:14:19 +00006856 Diag(Loc, diag::warn_builtin_unknown) << &II;
6857 else if (getLangOptions().C99)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00006858 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner00e26072008-05-05 21:18:06 +00006859 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00006860 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00006861
Chris Lattnerac18be92006-11-20 06:49:47 +00006862 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00006863 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +00006864 AttributeFactory attrFactory;
6865 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +00006866 unsigned DiagID;
6867 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00006868 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00006869 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +00006870 Declarator D(DS, Declarator::BlockContext);
John McCall084e83d2011-03-24 11:26:52 +00006871 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
Douglas Gregor54992352011-01-26 03:43:54 +00006872 0, 0, true, SourceLocation(),
Douglas Gregorad69e652011-07-13 21:47:47 +00006873 SourceLocation(),
Sebastian Redl802a4532011-03-05 22:42:13 +00006874 EST_None, SourceLocation(),
6875 0, 0, 0, 0, Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +00006876 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006877 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00006878 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006879
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00006880 // Insert this function into translation-unit scope.
6881
6882 DeclContext *PrevDC = CurContext;
6883 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006884
John McCall48871652010-08-21 09:40:31 +00006885 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +00006886 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00006887
6888 CurContext = PrevDC;
6889
Douglas Gregore711f702009-02-14 18:57:46 +00006890 AddKnownFunctionAttributes(FD);
6891
Steve Naroff3913ea42008-04-04 14:32:09 +00006892 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +00006893}
6894
Douglas Gregore711f702009-02-14 18:57:46 +00006895/// \brief Adds any function attributes that we know a priori based on
6896/// the declaration of this function.
6897///
6898/// These attributes can apply both to implicitly-declared builtins
6899/// (like __builtin___printf_chk) or to library-declared functions
6900/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +00006901///
6902/// We need to check for duplicate attributes both here and where user-written
6903/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +00006904void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
6905 if (FD->isInvalidDecl())
6906 return;
6907
6908 // If this is a built-in function, map its builtin attributes to
6909 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +00006910 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +00006911 // Handle printf-formatting attributes.
6912 unsigned FormatIdx;
6913 bool HasVAListArg;
6914 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006915 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006916 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
6917 "printf", FormatIdx+1,
Ted Kremenek7f4945a2010-02-11 05:28:37 +00006918 HasVAListArg ? 0 : FormatIdx+2));
Douglas Gregore711f702009-02-14 18:57:46 +00006919 }
Ted Kremenek5932c352010-07-16 02:11:15 +00006920 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
6921 HasVAListArg)) {
6922 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006923 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
6924 "scanf", FormatIdx+1,
Ted Kremenek5932c352010-07-16 02:11:15 +00006925 HasVAListArg ? 0 : FormatIdx+2));
6926 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00006927
6928 // Mark const if we don't care about errno and that is the only
6929 // thing preventing the function from being const. This allows
6930 // IRgen to use LLVM intrinsics for such functions.
6931 if (!getLangOptions().MathErrno &&
6932 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006933 if (!FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006934 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00006935 }
Mike Stumpca6c8752009-07-27 19:14:18 +00006936
Douglas Gregor88336832011-06-15 05:45:11 +00006937 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006938 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregor88336832011-06-15 05:45:11 +00006939 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006940 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregore711f702009-02-14 18:57:46 +00006941 }
6942
6943 IdentifierInfo *Name = FD->getIdentifier();
6944 if (!Name)
6945 return;
Mike Stump11289f42009-09-09 15:08:12 +00006946 if ((!getLangOptions().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00006947 FD->getDeclContext()->isTranslationUnit()) ||
6948 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00006949 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +00006950 LinkageSpecDecl::lang_c)) {
6951 // Okay: this could be a libc/libm/Objective-C function we know
6952 // about.
6953 } else
6954 return;
6955
Douglas Gregorfedd4282009-04-22 20:56:09 +00006956 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
Mike Stump82a9e442009-07-28 00:07:08 +00006957 // FIXME: NSLog and NSLogv should be target specific
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006958 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
Douglas Gregore711f702009-02-14 18:57:46 +00006959 // FIXME: We known better than our headers.
Ted Kremenek7f4945a2010-02-11 05:28:37 +00006960 const_cast<FormatAttr *>(Format)->setType(Context, "printf");
Mike Stump11289f42009-09-09 15:08:12 +00006961 } else
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006962 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
6963 "printf", 1,
Eli Friedmanf4799842009-06-10 04:01:38 +00006964 Name->isStr("NSLogv") ? 0 : 2));
Douglas Gregorfedd4282009-04-22 20:56:09 +00006965 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +00006966 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +00006967 // target-specific builtins, perhaps?
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006968 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006969 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
6970 "printf", 2,
Eli Friedmanf4799842009-06-10 04:01:38 +00006971 Name->isStr("vasprintf") ? 0 : 3));
Mike Stumpa4de80b2009-07-28 02:25:19 +00006972 }
Douglas Gregore711f702009-02-14 18:57:46 +00006973}
Chris Lattner302b4be2006-11-19 02:31:38 +00006974
John McCall703a3f82009-10-24 08:00:42 +00006975TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00006976 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +00006977 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00006978 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +00006979
John McCallbcd03502009-12-07 02:54:59 +00006980 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +00006981 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +00006982 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +00006983 }
6984
Chris Lattner18b19622007-01-22 07:39:13 +00006985 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +00006986 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00006987 D.getSourceRange().getBegin(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +00006988 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +00006989 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +00006990 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +00006991
John McCall04fcd0d2011-02-01 08:20:08 +00006992 // Bail out immediately if we have an invalid declaration.
6993 if (D.isInvalidType()) {
6994 NewTD->setInvalidDecl();
6995 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +00006996 }
6997
Douglas Gregor26701a42011-09-09 02:06:17 +00006998 if (D.getDeclSpec().isModulePrivateSpecified())
6999 NewTD->setModulePrivate();
7000
John McCall04fcd0d2011-02-01 08:20:08 +00007001 // C++ [dcl.typedef]p8:
7002 // If the typedef declaration defines an unnamed class (or
7003 // enum), the first typedef-name declared by the declaration
7004 // to be that class type (or enum type) is used to denote the
7005 // class type (or enum type) for linkage purposes only.
7006 // We need to check whether the type was declared in the declaration.
7007 switch (D.getDeclSpec().getTypeSpecType()) {
7008 case TST_enum:
7009 case TST_struct:
7010 case TST_union:
7011 case TST_class: {
7012 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
7013
7014 // Do nothing if the tag is not anonymous or already has an
7015 // associated typedef (from an earlier typedef in this decl group).
7016 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +00007017 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +00007018
7019 // A well-formed anonymous tag must always be a TUK_Definition.
7020 assert(tagFromDeclSpec->isThisDeclarationADefinition());
7021
7022 // The type must match the tag exactly; no qualifiers allowed.
7023 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
7024 break;
7025
7026 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +00007027 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +00007028 break;
7029 }
7030
7031 default:
7032 break;
7033 }
7034
Steve Narofff93b6722007-08-28 20:14:24 +00007035 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00007036}
7037
Douglas Gregord9034f02009-05-14 16:41:31 +00007038
7039/// \brief Determine whether a tag with a given kind is acceptable
7040/// as a redeclaration of the given tag declaration.
7041///
7042/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00007043bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +00007044 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +00007045 SourceLocation NewTagLoc,
7046 const IdentifierInfo &Name) {
7047 // C++ [dcl.type.elab]p3:
7048 // The class-key or enum keyword present in the
7049 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +00007050 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +00007051 // refers. This rule also applies to the form of
7052 // elaborated-type-specifier that declares a class-name or
7053 // friend class since it can be construed as referring to the
7054 // definition of the class. Thus, in any
7055 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +00007056 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +00007057 // used to refer to a union (clause 9), and either the class or
7058 // struct class-key shall be used to refer to a class (clause 9)
7059 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007060 TagTypeKind OldTag = Previous->getTagKind();
Richard Trieucaa33d32011-06-10 03:11:26 +00007061 if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct))
7062 if (OldTag == NewTag)
7063 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007064
Abramo Bagnara6150c882010-05-11 21:36:43 +00007065 if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
7066 (NewTag == TTK_Struct || NewTag == TTK_Class)) {
Douglas Gregord9034f02009-05-14 16:41:31 +00007067 // Warn about the struct/class tag mismatch.
7068 bool isTemplate = false;
7069 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
7070 isTemplate = Record->getDescribedClassTemplate();
7071
Richard Trieucaa33d32011-06-10 03:11:26 +00007072 if (!ActiveTemplateInstantiations.empty()) {
7073 // In a template instantiation, do not offer fix-its for tag mismatches
7074 // since they usually mess up the template instead of fixing the problem.
7075 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
7076 << (NewTag == TTK_Class) << isTemplate << &Name;
7077 return true;
7078 }
7079
7080 if (isDefinition) {
7081 // On definitions, check previous tags and issue a fix-it for each
7082 // one that doesn't match the current tag.
7083 if (Previous->getDefinition()) {
7084 // Don't suggest fix-its for redefinitions.
7085 return true;
7086 }
7087
7088 bool previousMismatch = false;
7089 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
7090 E(Previous->redecls_end()); I != E; ++I) {
7091 if (I->getTagKind() != NewTag) {
7092 if (!previousMismatch) {
7093 previousMismatch = true;
7094 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
7095 << (NewTag == TTK_Class) << isTemplate << &Name;
7096 }
7097 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
7098 << (NewTag == TTK_Class)
7099 << FixItHint::CreateReplacement(I->getInnerLocStart(),
7100 NewTag == TTK_Class?
7101 "class" : "struct");
7102 }
7103 }
7104 return true;
7105 }
7106
7107 // Check for a previous definition. If current tag and definition
7108 // are same type, do nothing. If no definition, but disagree with
7109 // with previous tag type, give a warning, but no fix-it.
7110 const TagDecl *Redecl = Previous->getDefinition() ?
7111 Previous->getDefinition() : Previous;
7112 if (Redecl->getTagKind() == NewTag) {
7113 return true;
7114 }
7115
Douglas Gregord9034f02009-05-14 16:41:31 +00007116 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Abramo Bagnara6150c882010-05-11 21:36:43 +00007117 << (NewTag == TTK_Class)
Richard Trieucaa33d32011-06-10 03:11:26 +00007118 << isTemplate << &Name;
7119 Diag(Redecl->getLocation(), diag::note_previous_use);
7120
7121 // If there is a previous defintion, suggest a fix-it.
7122 if (Previous->getDefinition()) {
7123 Diag(NewTagLoc, diag::note_struct_class_suggestion)
7124 << (Redecl->getTagKind() == TTK_Class)
7125 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
7126 Redecl->getTagKind() == TTK_Class? "class" : "struct");
7127 }
7128
Douglas Gregord9034f02009-05-14 16:41:31 +00007129 return true;
7130 }
7131 return false;
7132}
7133
Steve Naroff30d242c2007-09-15 18:49:24 +00007134/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00007135/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +00007136/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +00007137/// reference/declaration/definition of a tag.
John McCall48871652010-08-21 09:40:31 +00007138Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +00007139 SourceLocation KWLoc, CXXScopeSpec &SS,
7140 IdentifierInfo *Name, SourceLocation NameLoc,
7141 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor26701a42011-09-09 02:06:17 +00007142 bool IsModulePrivate,
Douglas Gregor009f6992010-09-16 23:58:57 +00007143 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00007144 bool &OwnedDecl, bool &IsDependent,
7145 bool ScopedEnum, bool ScopedEnumUsesClassTag,
Douglas Gregor0bf31402010-10-08 23:50:27 +00007146 TypeResult UnderlyingType) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007147 // If this is not a definition, it must have a name.
John McCall9bb74a52009-07-31 02:45:11 +00007148 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +00007149 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +00007150 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00007151
Douglas Gregord6ab8742009-05-28 23:31:59 +00007152 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00007153 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00007154
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007155 // FIXME: Check explicit specializations more carefully.
7156 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007157 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +00007158
7159 // We only need to do this matching if we have template parameters
7160 // or a scope specifier, which also conveniently avoids this work
7161 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +00007162 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +00007163 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00007164 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00007165 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
John McCallc9739e32010-10-16 07:23:36 +00007166 TemplateParameterLists.get(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00007167 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00007168 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007169 isExplicitSpecialization,
7170 Invalid)) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00007171 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00007172 // This is a declaration or definition of a class template (which may
7173 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +00007174
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007175 if (Invalid)
John McCall48871652010-08-21 09:40:31 +00007176 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00007177
Douglas Gregore93e46c2009-07-22 23:48:44 +00007178 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +00007179 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +00007180 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00007181 TemplateParams, AS,
Douglas Gregor26701a42011-09-09 02:06:17 +00007182 IsModulePrivate,
Abramo Bagnara60804e12011-03-18 15:16:37 +00007183 TemplateParameterLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00007184 (TemplateParameterList**) TemplateParameterLists.release());
Douglas Gregore93e46c2009-07-22 23:48:44 +00007185 return Result.get();
7186 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007187 // The "template<>" header is extraneous.
7188 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +00007189 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007190 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +00007191 }
Mike Stump11289f42009-09-09 15:08:12 +00007192 }
7193 }
7194
Douglas Gregor0bf31402010-10-08 23:50:27 +00007195 // Figure out the underlying type if this a enum declaration. We need to do
7196 // this early, because it's needed to detect if this is an incompatible
7197 // redeclaration.
7198 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
7199
7200 if (Kind == TTK_Enum) {
7201 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
7202 // No underlying type explicitly specified, or we failed to parse the
7203 // type, default to int.
7204 EnumUnderlying = Context.IntTy.getTypePtr();
7205 else if (UnderlyingType.get()) {
7206 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
7207 // integral type; any cv-qualification is ignored.
7208 TypeSourceInfo *TI = 0;
7209 QualType T = GetTypeFromParser(UnderlyingType.get(), &TI);
7210 EnumUnderlying = TI;
7211
7212 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
7213
7214 if (!T->isDependentType() && !T->isIntegralType(Context)) {
7215 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
7216 << T;
7217 // Recover by falling back to int.
7218 EnumUnderlying = Context.IntTy.getTypePtr();
7219 }
Douglas Gregor2b988fd2010-12-16 00:24:44 +00007220
7221 if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI,
7222 UPPC_FixedUnderlyingType))
7223 EnumUnderlying = Context.IntTy.getTypePtr();
7224
Francois Picheta3108062010-10-18 15:01:13 +00007225 } else if (getLangOptions().Microsoft)
7226 // Microsoft enums are always of int type.
7227 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007228 }
7229
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00007230 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00007231 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +00007232 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +00007233
Chandler Carrutha419dbb2010-03-01 21:17:36 +00007234 RedeclarationKind Redecl = ForRedeclaration;
7235 if (TUK == TUK_Friend || TUK == TUK_Reference)
7236 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +00007237
7238 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
John McCall6538c932009-10-10 05:48:19 +00007239
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00007240 if (Name && SS.isNotEmpty()) {
7241 // We have a nested-name tag ('struct foo::bar').
7242
7243 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00007244 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00007245 Name = 0;
7246 goto CreateNewDecl;
7247 }
7248
John McCall7f41d982009-09-11 04:59:25 +00007249 // If this is a friend or a reference to a class in a dependent
7250 // context, don't try to make a decl for it.
7251 if (TUK == TUK_Friend || TUK == TUK_Reference) {
7252 DC = computeDeclContext(SS, false);
7253 if (!DC) {
7254 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00007255 return 0;
John McCall7f41d982009-09-11 04:59:25 +00007256 }
John McCall0b66eb32010-05-01 00:40:08 +00007257 } else {
7258 DC = computeDeclContext(SS, true);
7259 if (!DC) {
7260 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
7261 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007262 return 0;
John McCall0b66eb32010-05-01 00:40:08 +00007263 }
John McCall7f41d982009-09-11 04:59:25 +00007264 }
7265
John McCall0b66eb32010-05-01 00:40:08 +00007266 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +00007267 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007268
Douglas Gregor8761da52009-02-03 00:34:39 +00007269 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00007270 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +00007271 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +00007272
John McCall1f82f242009-11-18 22:49:29 +00007273 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00007274 return 0;
John McCall6538c932009-10-10 05:48:19 +00007275
John McCall1f82f242009-11-18 22:49:29 +00007276 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00007277 // Name lookup did not find anything. However, if the
7278 // nested-name-specifier refers to the current instantiation,
7279 // and that current instantiation has any dependent base
7280 // classes, we might find something at instantiation time: treat
7281 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +00007282 // But this only makes any sense for reference-like lookups.
7283 if (Previous.wasNotFoundInCurrentInstantiation() &&
7284 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00007285 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00007286 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +00007287 }
7288
7289 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +00007290 Diag(NameLoc, diag::err_not_tag_in_scope)
7291 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00007292 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007293 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00007294 goto CreateNewDecl;
7295 }
Chris Lattnerd9773512009-01-21 02:38:50 +00007296 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00007297 // If this is a named struct, check to see if there was a previous forward
7298 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +00007299 // FIXME: We're looking into outer scopes here, even when we
7300 // shouldn't be. Doing so can result in ambiguities that we
7301 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +00007302 LookupName(Previous, S);
7303
Douglas Gregor5d1d9e32011-05-09 21:46:33 +00007304 if (Previous.isAmbiguous() &&
7305 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +00007306 LookupResult::Filter F = Previous.makeFilter();
7307 while (F.hasNext()) {
7308 NamedDecl *ND = F.next();
7309 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
7310 F.erase();
7311 }
7312 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +00007313 }
7314
John McCall1f82f242009-11-18 22:49:29 +00007315 // Note: there used to be some attempt at recovery here.
7316 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00007317 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007318
John McCall9bb74a52009-07-31 02:45:11 +00007319 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007320 // FIXME: This makes sure that we ignore the contexts associated
7321 // with C structs, unions, and enums when looking for a matching
7322 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +00007323 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00007324 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
7325 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007326 }
Douglas Gregor009f6992010-09-16 23:58:57 +00007327 } else if (S->isFunctionPrototypeScope()) {
7328 // If this is an enum declaration in function prototype scope, set its
7329 // initial context to the translation unit.
7330 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00007331 }
7332
John McCall1f82f242009-11-18 22:49:29 +00007333 if (Previous.isSingleResult() &&
7334 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00007335 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +00007336 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +00007337 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00007338 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00007339 }
7340
Douglas Gregor87f54062009-09-15 22:30:29 +00007341 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007342 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007343 // This is a declaration of or a reference to "std::bad_alloc".
7344 isStdBadAlloc = true;
7345
John McCall1f82f242009-11-18 22:49:29 +00007346 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007347 // std::bad_alloc has been implicitly declared (but made invisible to
7348 // name lookup). Fill in this implicit declaration as the previous
7349 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007350 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00007351 }
7352 }
John McCall1f82f242009-11-18 22:49:29 +00007353
John McCalle9eaf8e2010-03-25 21:28:06 +00007354 // If we didn't find a previous declaration, and this is a reference
7355 // (or friend reference), move to the correct scope. In C++, we
7356 // also need to do a redeclaration lookup there, just in case
7357 // there's a shadow friend decl.
7358 if (Name && Previous.empty() &&
7359 (TUK == TUK_Reference || TUK == TUK_Friend)) {
7360 if (Invalid) goto CreateNewDecl;
7361 assert(SS.isEmpty());
7362
7363 if (TUK == TUK_Reference) {
7364 // C++ [basic.scope.pdecl]p5:
7365 // -- for an elaborated-type-specifier of the form
7366 //
7367 // class-key identifier
7368 //
7369 // if the elaborated-type-specifier is used in the
7370 // decl-specifier-seq or parameter-declaration-clause of a
7371 // function defined in namespace scope, the identifier is
7372 // declared as a class-name in the namespace that contains
7373 // the declaration; otherwise, except as a friend
7374 // declaration, the identifier is declared in the smallest
7375 // non-class, non-function-prototype scope that contains the
7376 // declaration.
7377 //
7378 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
7379 // C structs and unions.
7380 //
7381 // It is an error in C++ to declare (rather than define) an enum
7382 // type, including via an elaborated type specifier. We'll
7383 // diagnose that later; for now, declare the enum in the same
7384 // scope as we would have picked for any other tag type.
7385 //
7386 // GNU C also supports this behavior as part of its incomplete
7387 // enum types extension, while GNU C++ does not.
7388 //
7389 // Find the context where we'll be declaring the tag.
7390 // FIXME: We would like to maintain the current DeclContext as the
7391 // lexical context,
Rafael Espindola9e976dc2011-01-20 02:26:24 +00007392 while (SearchDC->isRecord() || SearchDC->isTransparentContext())
John McCalle9eaf8e2010-03-25 21:28:06 +00007393 SearchDC = SearchDC->getParent();
7394
7395 // Find the scope where we'll be declaring the tag.
7396 while (S->isClassScope() ||
7397 (getLangOptions().CPlusPlus &&
7398 S->isFunctionPrototypeScope()) ||
7399 ((S->getFlags() & Scope::DeclScope) == 0) ||
7400 (S->getEntity() &&
7401 ((DeclContext *)S->getEntity())->isTransparentContext()))
7402 S = S->getParent();
7403 } else {
7404 assert(TUK == TUK_Friend);
7405 // C++ [namespace.memdef]p3:
7406 // If a friend declaration in a non-local class first declares a
7407 // class or function, the friend class or function is a member of
7408 // the innermost enclosing namespace.
7409 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +00007410 }
7411
John McCalle87beb22010-04-23 18:46:30 +00007412 // In C++, we need to do a redeclaration lookup to properly
7413 // diagnose some problems.
John McCalle9eaf8e2010-03-25 21:28:06 +00007414 if (getLangOptions().CPlusPlus) {
7415 Previous.setRedeclarationKind(ForRedeclaration);
7416 LookupQualifiedName(Previous, SearchDC);
7417 }
7418 }
7419
John McCall1f82f242009-11-18 22:49:29 +00007420 if (!Previous.empty()) {
Douglas Gregorce40e2e2010-04-12 16:00:01 +00007421 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCalle87beb22010-04-23 18:46:30 +00007422
7423 // It's okay to have a tag decl in the same scope as a typedef
7424 // which hides a tag decl in the same scope. Finding this
7425 // insanity with a redeclaration lookup can only actually happen
7426 // in C++.
7427 //
7428 // This is also okay for elaborated-type-specifiers, which is
7429 // technically forbidden by the current standard but which is
7430 // okay according to the likely resolution of an open issue;
7431 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
7432 if (getLangOptions().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +00007433 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +00007434 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
7435 TagDecl *Tag = TT->getDecl();
7436 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007437 Tag->getDeclContext()->getRedeclContext()
7438 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +00007439 PrevDecl = Tag;
7440 Previous.clear();
7441 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +00007442 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +00007443 }
7444 }
7445 }
7446 }
7447
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007448 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00007449 // If this is a use of a previous tag, or if the tag is already declared
7450 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007451 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +00007452 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregordb446112011-03-07 16:54:27 +00007453 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00007454 // Make sure that this wasn't declared as an enum and now used as a
7455 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +00007456 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
7457 TUK == TUK_Definition, KWLoc,
7458 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00007459 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +00007460 = (PrevTagDecl->getTagKind() != TTK_Enum &&
7461 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +00007462 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +00007463 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007464 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00007465 << FixItHint::CreateReplacement(SourceRange(KWLoc),
7466 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +00007467 else
7468 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +00007469 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00007470
Mike Stump11289f42009-09-09 15:08:12 +00007471 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +00007472 Kind = PrevTagDecl->getTagKind();
7473 else {
7474 // Recover by making this an anonymous redefinition.
7475 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00007476 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +00007477 Invalid = true;
7478 }
7479 }
7480
Douglas Gregor0bf31402010-10-08 23:50:27 +00007481 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
7482 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
7483
7484 // All conflicts with previous declarations are recovered by
7485 // returning the previous declaration.
7486 if (ScopedEnum != PrevEnum->isScoped()) {
7487 Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch)
7488 << PrevEnum->isScoped();
7489 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7490 return PrevTagDecl;
7491 }
7492 else if (EnumUnderlying && PrevEnum->isFixed()) {
7493 QualType T;
7494 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
7495 T = TI->getType();
7496 else
7497 T = QualType(EnumUnderlying.get<const Type*>(), 0);
7498
7499 if (!Context.hasSameUnqualifiedType(T, PrevEnum->getIntegerType())) {
Douglas Gregor1a099ba2010-12-01 16:10:38 +00007500 Diag(NameLoc.isValid() ? NameLoc : KWLoc,
7501 diag::err_enum_redeclare_type_mismatch)
7502 << T
7503 << PrevEnum->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007504 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7505 return PrevTagDecl;
7506 }
7507 }
7508 else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) {
7509 Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch)
7510 << PrevEnum->isFixed();
7511 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7512 return PrevTagDecl;
7513 }
7514 }
7515
Douglas Gregor170512f2009-04-01 23:51:29 +00007516 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007517 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +00007518
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007519 // FIXME: In the future, return a variant or some other clue
7520 // for the consumer of this Decl to know it doesn't own it.
7521 // For our current ASTs this shouldn't be a problem, but will
7522 // need to be changed with DeclGroups.
Francois Pichete37eeba2011-06-01 04:14:20 +00007523 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
7524 getLangOptions().Microsoft)) || TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +00007525 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +00007526
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007527 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +00007528 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007529 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00007530 // If we're defining a specialization and the previous definition
7531 // is from an implicit instantiation, don't emit an error
7532 // here; we'll catch this in the general case below.
7533 if (!isExplicitSpecialization ||
7534 !isa<CXXRecordDecl>(Def) ||
7535 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
7536 == TSK_ExplicitSpecialization) {
7537 Diag(NameLoc, diag::err_redefinition) << Name;
7538 Diag(Def->getLocation(), diag::note_previous_definition);
7539 // If this is a redefinition, recover by making this
7540 // struct be anonymous, which will make any later
7541 // references get the previous definition.
7542 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00007543 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007544 Invalid = true;
7545 }
Douglas Gregordee1be82009-01-17 00:42:38 +00007546 } else {
7547 // If the type is currently being defined, complain
7548 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +00007549 const TagType *Tag
7550 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +00007551 if (Tag->isBeingDefined()) {
7552 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +00007553 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +00007554 diag::note_previous_definition);
7555 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00007556 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +00007557 Invalid = true;
7558 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007559 }
Douglas Gregordee1be82009-01-17 00:42:38 +00007560
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007561 // Okay, this is definition of a previously declared or referenced
7562 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +00007563 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007564 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007565 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +00007566 // have a definition. Just create a new decl.
7567
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007568 } else {
7569 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +00007570 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007571 // new decl/type. We set PrevDecl to NULL so that the entities
7572 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +00007573 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +00007574 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007575 // If we get here, we're going to create a new Decl. If PrevDecl
7576 // is non-NULL, it's a definition of the tag declared by
7577 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +00007578
7579
7580 // Otherwise, PrevDecl is not a tag, but was found with tag
7581 // lookup. This is only actually possible in C++, where a few
7582 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007583 } else {
John McCalle87beb22010-04-23 18:46:30 +00007584 assert(getLangOptions().CPlusPlus);
7585
7586 // Use a better diagnostic if an elaborated-type-specifier
7587 // found the wrong kind of type on the first
7588 // (non-redeclaration) lookup.
7589 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
7590 !Previous.isForRedeclaration()) {
7591 unsigned Kind = 0;
7592 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +00007593 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
7594 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +00007595 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
7596 Diag(PrevDecl->getLocation(), diag::note_declared_at);
7597 Invalid = true;
7598
7599 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregordb446112011-03-07 16:54:27 +00007600 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
7601 isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +00007602 // do nothing
7603
7604 // Diagnose implicit declarations introduced by elaborated types.
7605 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
7606 unsigned Kind = 0;
7607 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +00007608 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
7609 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +00007610 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
7611 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
7612 Invalid = true;
7613
7614 // Otherwise it's a declaration. Call out a particularly common
7615 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +00007616 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
7617 unsigned Kind = 0;
7618 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +00007619 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +00007620 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +00007621 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
7622 Invalid = true;
7623
7624 // Otherwise, diagnose.
7625 } else {
7626 // The tag name clashes with something else in the target scope,
7627 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00007628 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +00007629 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00007630 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +00007631 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00007632 }
John McCalle87beb22010-04-23 18:46:30 +00007633
7634 // The existing declaration isn't relevant to us; we're in a
7635 // new scope, so clear out the previous declaration.
7636 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +00007637 }
Chris Lattner18b19622007-01-22 07:39:13 +00007638 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00007639
Chris Lattner438e5012008-12-17 07:13:27 +00007640CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +00007641
John McCall1f82f242009-11-18 22:49:29 +00007642 TagDecl *PrevDecl = 0;
7643 if (Previous.isSingleResult())
7644 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
7645
Chris Lattnerbf0b7982007-01-23 04:27:41 +00007646 // If there is an identifier, use the location of the identifier as the
7647 // location of the decl, otherwise use the location of the struct/union
7648 // keyword.
7649 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +00007650
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007651 // Otherwise, create a new declaration. If there is a previous
7652 // declaration of the same entity, the two will be linked via
7653 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00007654 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00007655
Douglas Gregor0bf31402010-10-08 23:50:27 +00007656 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00007657 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +00007658 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
7659 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007660 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +00007661 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00007662 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +00007663 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00007664 if (TUK != TUK_Definition && !Invalid) {
7665 TagDecl *Def;
Douglas Gregor0bf31402010-10-08 23:50:27 +00007666 if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
7667 // C++0x: 7.2p2: opaque-enum-declaration.
7668 // Conflicts are diagnosed above. Do nothing.
7669 }
7670 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00007671 Diag(Loc, diag::ext_forward_ref_enum_def)
7672 << New;
7673 Diag(Def->getLocation(), diag::note_previous_definition);
7674 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +00007675 unsigned DiagID = diag::ext_forward_ref_enum;
7676 if (getLangOptions().Microsoft)
7677 DiagID = diag::ext_ms_forward_ref_enum;
7678 else if (getLangOptions().CPlusPlus)
7679 DiagID = diag::err_forward_ref_enum;
7680 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +00007681
7682 // If this is a forward-declared reference to an enumeration, make a
7683 // note of it; we won't actually be introducing the declaration into
7684 // the declaration context.
7685 if (TUK == TUK_Reference)
7686 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00007687 }
Douglas Gregord45b93b2009-03-06 18:34:03 +00007688 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00007689
7690 if (EnumUnderlying) {
7691 EnumDecl *ED = cast<EnumDecl>(New);
7692 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
7693 ED->setIntegerTypeSourceInfo(TI);
7694 else
7695 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
7696 ED->setPromotionType(ED->getIntegerType());
7697 }
7698
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00007699 } else {
7700 // struct/union/class
7701
Chris Lattner776fac82007-06-09 00:53:06 +00007702 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
7703 // struct X { int A; } D; D should chain to X.
Douglas Gregor87f54062009-09-15 22:30:29 +00007704 if (getLangOptions().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +00007705 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007706 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007707 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007708
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007709 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +00007710 StdBadAlloc = cast<CXXRecordDecl>(New);
7711 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007712 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007713 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007714 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007715
John McCall3e11ebe2010-03-15 10:12:16 +00007716 // Maybe add qualifier info.
7717 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +00007718 if (SS.isSet()) {
Douglas Gregor14454802011-02-25 02:25:35 +00007719 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +00007720 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007721 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00007722 TemplateParameterLists.size(),
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007723 (TemplateParameterList**) TemplateParameterLists.release());
7724 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +00007725 }
7726 else
7727 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +00007728 }
7729
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00007730 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
7731 // Add alignment attributes if necessary; these attributes are checked when
7732 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007733 //
7734 // It is important for implementing the correct semantics that this
7735 // happen here (in act on tag decl). The #pragma pack stack is
7736 // maintained as a result of parser callbacks which can occur at
7737 // many points during the parsing of a struct declaration (because
7738 // the #pragma tokens are effectively skipped over during the
7739 // parsing of the struct).
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00007740 AddAlignmentAttributesForRecord(RD);
Fariborz Jahanian6b4e26b2011-04-26 17:54:40 +00007741
7742 AddMsStructLayoutForRecord(RD);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007743 }
7744
Douglas Gregoref15bdb2011-09-09 18:32:39 +00007745 if (PrevDecl && PrevDecl->isModulePrivate())
7746 New->setModulePrivate();
7747 else if (IsModulePrivate)
Douglas Gregor26701a42011-09-09 02:06:17 +00007748 New->setModulePrivate();
7749
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007750 // If this is a specialization of a member class (of a class template),
7751 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +00007752 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007753 Invalid = true;
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00007754
Douglas Gregordee1be82009-01-17 00:42:38 +00007755 if (Invalid)
7756 New->setInvalidDecl();
7757
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007758 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00007759 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007760
Douglas Gregordee1be82009-01-17 00:42:38 +00007761 // If we're declaring or defining a tag in function prototype scope
7762 // in C, note that this type can only be used within the function.
Douglas Gregor658b9552009-01-09 22:42:13 +00007763 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
7764 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
7765
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007766 // Set the lexical context. If the tag has a C++ scope specifier, the
7767 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +00007768 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +00007769
John McCallaa74a0c2009-08-28 07:59:38 +00007770 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +00007771 // In Microsoft mode, a friend declaration also acts as a forward
7772 // declaration so we always pass true to setObjectOfFriendDecl to make
7773 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +00007774 if (TUK == TUK_Friend)
Francois Pichete37eeba2011-06-01 04:14:20 +00007775 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
7776 getLangOptions().Microsoft);
John McCallaa74a0c2009-08-28 07:59:38 +00007777
Anders Carlsson5558ca12009-03-26 01:19:02 +00007778 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +00007779 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007780 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +00007781
John McCall9bb74a52009-07-31 02:45:11 +00007782 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +00007783 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00007784
Chris Lattner18b19622007-01-22 07:39:13 +00007785 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +00007786 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +00007787 // We might be replacing an existing declaration in the lookup tables;
7788 // if so, borrow its access specifier.
7789 if (PrevDecl)
7790 New->setAccess(PrevDecl->getAccess());
7791
Sebastian Redl50c68252010-08-31 00:36:30 +00007792 DeclContext *DC = New->getDeclContext()->getRedeclContext();
John McCalle9eaf8e2010-03-25 21:28:06 +00007793 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
7794 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +00007795 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
7796 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +00007797 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +00007798 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +00007799 PushOnScopeChains(New, S, !IsForwardReference);
7800 if (IsForwardReference)
7801 SearchDC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
7802
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00007803 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007804 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +00007805 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00007806
Douglas Gregor27821ce2009-07-07 16:35:42 +00007807 // If this is the C FILE type, notify the AST context.
7808 if (IdentifierInfo *II = New->getIdentifier())
7809 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007810 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +00007811 II->isStr("FILE"))
7812 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +00007813
Douglas Gregord6ab8742009-05-28 23:31:59 +00007814 OwnedDecl = true;
John McCall48871652010-08-21 09:40:31 +00007815 return New;
Chris Lattner18b19622007-01-22 07:39:13 +00007816}
Chris Lattner1300fb92007-01-23 23:42:53 +00007817
John McCall48871652010-08-21 09:40:31 +00007818void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00007819 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00007820 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +00007821
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007822 // Enter the tag context.
7823 PushDeclContext(S, Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +00007824}
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007825
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007826void Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
7827 assert(isa<ObjCContainerDecl>(IDecl) &&
7828 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
7829 DeclContext *OCD = cast<DeclContext>(IDecl);
7830 assert(getContainingDC(OCD) == CurContext &&
7831 "The next DeclContext should be lexically contained in the current one.");
7832 CurContext = OCD;
7833}
7834
John McCall48871652010-08-21 09:40:31 +00007835void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +00007836 SourceLocation FinalLoc,
John McCall1c7e6ec2009-12-20 07:58:13 +00007837 SourceLocation LBraceLoc) {
7838 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00007839 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007840
John McCall1c7e6ec2009-12-20 07:58:13 +00007841 FieldCollector->StartClass();
7842
7843 if (!Record->getIdentifier())
7844 return;
7845
Anders Carlsson30f29442011-03-25 14:31:08 +00007846 if (FinalLoc.isValid())
7847 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
Anders Carlssonfc1eef42011-01-22 17:51:53 +00007848
John McCall1c7e6ec2009-12-20 07:58:13 +00007849 // C++ [class]p2:
7850 // [...] The class-name is also inserted into the scope of the
7851 // class itself; this is known as the injected-class-name. For
7852 // purposes of access checking, the injected-class-name is treated
7853 // as if it were a public member name.
7854 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007855 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
7856 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +00007857 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +00007858 /*PrevDecl=*/0,
7859 /*DelayTypeCreation=*/true);
7860 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +00007861 InjectedClassName->setImplicit();
7862 InjectedClassName->setAccess(AS_public);
7863 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
7864 InjectedClassName->setDescribedClassTemplate(Template);
7865 PushOnScopeChains(InjectedClassName, S);
7866 assert(InjectedClassName->isInjectedClassName() &&
7867 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007868}
7869
John McCall48871652010-08-21 09:40:31 +00007870void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00007871 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00007872 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00007873 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00007874 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007875
7876 if (isa<CXXRecordDecl>(Tag))
7877 FieldCollector->FinishClass();
7878
7879 // Exit this scope of this tag's definition.
7880 PopDeclContext();
Douglas Gregor859f0ae2010-01-06 17:00:51 +00007881
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007882 // Notify the consumer that we've defined a tag.
7883 Consumer.HandleTagDeclDefinition(Tag);
7884}
Chris Lattner535b8302008-06-21 19:39:06 +00007885
Fariborz Jahanian4327b322011-08-29 17:33:12 +00007886void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007887 // Exit this scope of this interface definition.
7888 PopDeclContext();
7889}
7890
John McCall48871652010-08-21 09:40:31 +00007891void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +00007892 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00007893 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +00007894 Tag->setInvalidDecl();
7895
John McCall71ba5f22010-03-17 19:25:57 +00007896 // We're undoing ActOnTagStartDefinition here, not
7897 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
7898 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +00007899
7900 PopDeclContext();
7901}
7902
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007903// Note that FieldName may be null for anonymous bitfields.
Mike Stump11289f42009-09-09 15:08:12 +00007904bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Eli Friedmanc96d4962009-08-15 21:55:26 +00007905 QualType FieldTy, const Expr *BitWidth,
7906 bool *ZeroWidth) {
7907 // Default to true; that shouldn't confuse checks for emptiness
7908 if (ZeroWidth)
7909 *ZeroWidth = true;
7910
Chris Lattner73bf7b42009-03-05 22:45:59 +00007911 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +00007912 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +00007913 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +00007914 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +00007915 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
7916 return true;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007917 if (FieldName)
7918 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
7919 << FieldName << FieldTy << BitWidth->getSourceRange();
7920 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
7921 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +00007922 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
7923 UPPC_BitFieldWidth))
7924 return true;
Douglas Gregor1efa4372009-03-11 18:59:21 +00007925
7926 // If the bit-width is type- or value-dependent, don't try to check
7927 // it now.
7928 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
7929 return false;
7930
Anders Carlsson5df391e2008-12-06 20:33:04 +00007931 llvm::APSInt Value;
7932 if (VerifyIntegerConstantExpression(BitWidth, &Value))
7933 return true;
7934
Eli Friedmanc96d4962009-08-15 21:55:26 +00007935 if (Value != 0 && ZeroWidth)
7936 *ZeroWidth = false;
7937
Chris Lattner81ed6802008-12-12 04:56:04 +00007938 // Zero-width bitfield is ok for anonymous field.
7939 if (Value == 0 && FieldName)
7940 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00007941
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007942 if (Value.isSigned() && Value.isNegative()) {
7943 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +00007944 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007945 << FieldName << Value.toString(10);
7946 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
7947 << Value.toString(10);
7948 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00007949
Douglas Gregor1efa4372009-03-11 18:59:21 +00007950 if (!FieldTy->isDependentType()) {
7951 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007952 if (Value.getZExtValue() > TypeSize) {
Anders Carlssond5635fe2010-04-16 15:16:32 +00007953 if (!getLangOptions().CPlusPlus) {
7954 if (FieldName)
7955 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
7956 << FieldName << (unsigned)Value.getZExtValue()
7957 << (unsigned)TypeSize;
7958
7959 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
7960 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
7961 }
7962
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007963 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +00007964 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
7965 << FieldName << (unsigned)Value.getZExtValue()
7966 << (unsigned)TypeSize;
7967 else
7968 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
7969 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007970 }
Douglas Gregor1efa4372009-03-11 18:59:21 +00007971 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00007972
7973 return false;
7974}
7975
Richard Smith938f40b2011-06-11 17:19:42 +00007976/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00007977/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +00007978Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +00007979 Declarator &D, Expr *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +00007980 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +00007981 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith938f40b2011-06-11 17:19:42 +00007982 /*HasInit=*/false, AS_public);
John McCall48871652010-08-21 09:40:31 +00007983 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +00007984}
7985
7986/// HandleField - Analyze a field of a C struct or a C++ data member.
7987///
7988FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
7989 SourceLocation DeclStart,
Richard Smith938f40b2011-06-11 17:19:42 +00007990 Declarator &D, Expr *BitWidth, bool HasInit,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00007991 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +00007992 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +00007993 SourceLocation Loc = DeclStart;
7994 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00007995
John McCall8cb7bdf2010-06-04 23:28:52 +00007996 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7997 QualType T = TInfo->getType();
Douglas Gregora02a72a2010-12-15 23:18:36 +00007998 if (getLangOptions().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +00007999 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00008000
Douglas Gregora02a72a2010-12-15 23:18:36 +00008001 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8002 UPPC_DataMemberType)) {
8003 D.setInvalidType();
8004 T = Context.IntTy;
8005 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
8006 }
8007 }
8008
Eli Friedman574c7452009-04-07 19:37:57 +00008009 DiagnoseFunctionSpecifiers(D);
8010
Eli Friedmand5c0eed2009-04-19 20:27:55 +00008011 if (D.getDeclSpec().isThreadSpecified())
8012 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Richard Smitha77a0a62011-08-15 21:04:07 +00008013 if (D.getDeclSpec().isConstexprSpecified())
8014 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
8015 << 2;
Douglas Gregor2c7d9292010-08-30 14:32:14 +00008016
8017 // Check to see if this name was declared as a member previously
8018 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
8019 LookupName(Previous, S);
8020 assert((Previous.empty() || Previous.isOverloadedResult() ||
8021 Previous.isSingleResult())
8022 && "Lookup of member name should be either overloaded, single or null");
Eli Friedmand5c0eed2009-04-19 20:27:55 +00008023
Douglas Gregor2c7d9292010-08-30 14:32:14 +00008024 // If the name is overloaded then get any declaration else get the single result
8025 NamedDecl *PrevDecl = Previous.isOverloadedResult() ?
8026 Previous.getRepresentativeDecl() : Previous.getAsSingle<NamedDecl>();
Douglas Gregorf187420f2009-06-17 23:37:01 +00008027
8028 if (PrevDecl && PrevDecl->isTemplateParameter()) {
8029 // Maybe we will complain about the shadowed template parameter.
8030 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
8031 // Just pretend that we didn't see the previous declaration.
8032 PrevDecl = 0;
8033 }
8034
Douglas Gregor1efa4372009-03-11 18:59:21 +00008035 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
8036 PrevDecl = 0;
8037
Steve Naroff5ec6ff72009-07-14 14:58:18 +00008038 bool Mutable
8039 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
8040 SourceLocation TSSL = D.getSourceRange().getBegin();
8041 FieldDecl *NewFD
Richard Smith938f40b2011-06-11 17:19:42 +00008042 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit,
8043 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +00008044
8045 if (NewFD->isInvalidDecl())
8046 Record->setInvalidDecl();
8047
Douglas Gregor1efa4372009-03-11 18:59:21 +00008048 if (NewFD->isInvalidDecl() && PrevDecl) {
8049 // Don't introduce NewFD into scope; there's already something
8050 // with the same name in the same scope.
8051 } else if (II) {
8052 PushOnScopeChains(NewFD, S);
8053 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008054 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +00008055
8056 return NewFD;
8057}
8058
8059/// \brief Build a new FieldDecl and check its well-formedness.
8060///
8061/// This routine builds a new FieldDecl given the fields name, type,
8062/// record, etc. \p PrevDecl should refer to any previous declaration
8063/// with the same name and in the same scope as the field to be
8064/// created.
8065///
8066/// \returns a new FieldDecl.
8067///
Mike Stump11289f42009-09-09 15:08:12 +00008068/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00008069FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00008070 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +00008071 RecordDecl *Record, SourceLocation Loc,
Richard Smith938f40b2011-06-11 17:19:42 +00008072 bool Mutable, Expr *BitWidth, bool HasInit,
Steve Naroff5ec6ff72009-07-14 14:58:18 +00008073 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00008074 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +00008075 Declarator *D) {
8076 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +00008077 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008078 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00008079
Douglas Gregor1efa4372009-03-11 18:59:21 +00008080 // If we receive a broken type, recover by assuming 'int' and
8081 // marking this declaration as invalid.
8082 if (T.isNull()) {
8083 InvalidDecl = true;
8084 T = Context.IntTy;
8085 }
8086
Eli Friedmand0e8de22009-12-07 00:22:08 +00008087 QualType EltTy = Context.getBaseElementType(T);
8088 if (!EltTy->isDependentType() &&
John McCall2677e102010-08-16 23:42:35 +00008089 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
8090 // Fields of incomplete type force their record to be invalid.
8091 Record->setInvalidDecl();
Eli Friedmand0e8de22009-12-07 00:22:08 +00008092 InvalidDecl = true;
John McCall2677e102010-08-16 23:42:35 +00008093 }
Eli Friedmand0e8de22009-12-07 00:22:08 +00008094
Steve Naroff8eeeb132007-05-08 21:09:37 +00008095 // C99 6.7.2.1p8: A member of a structure or union may have any type other
8096 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +00008097 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00008098 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00008099 llvm::APSInt Oversized;
Eli Friedmana3b1d032009-02-21 00:44:51 +00008100 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00008101 SizeIsNegative,
8102 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00008103 if (!FixedTy.isNull()) {
8104 Diag(Loc, diag::warn_illegal_constant_array_size);
8105 T = FixedTy;
8106 } else {
8107 if (SizeIsNegative)
8108 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00008109 else if (Oversized.getBoolValue())
8110 Diag(Loc, diag::err_array_too_large)
8111 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00008112 else
8113 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00008114 InvalidDecl = true;
8115 }
Steve Naroff8eeeb132007-05-08 21:09:37 +00008116 }
Mike Stump11289f42009-09-09 15:08:12 +00008117
Anders Carlsson576cc6f2009-03-22 20:18:17 +00008118 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +00008119 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
8120 diag::err_abstract_type_in_decl,
8121 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00008122 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +00008123
Eli Friedmanc96d4962009-08-15 21:55:26 +00008124 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +00008125 // If this is declared as a bit-field, check the bit-field.
Eli Friedmand0e8de22009-12-07 00:22:08 +00008126 if (!InvalidDecl && BitWidth &&
8127 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
Douglas Gregor1efa4372009-03-11 18:59:21 +00008128 InvalidDecl = true;
Douglas Gregor1efa4372009-03-11 18:59:21 +00008129 BitWidth = 0;
Eli Friedmanc96d4962009-08-15 21:55:26 +00008130 ZeroWidth = false;
Anders Carlsson5df391e2008-12-06 20:33:04 +00008131 }
Mike Stump11289f42009-09-09 15:08:12 +00008132
John McCallb1cd7da2010-06-04 08:34:12 +00008133 // Check that 'mutable' is consistent with the type of the declaration.
8134 if (!InvalidDecl && Mutable) {
8135 unsigned DiagID = 0;
8136 if (T->isReferenceType())
8137 DiagID = diag::err_mutable_reference;
8138 else if (T.isConstQualified())
8139 DiagID = diag::err_mutable_const;
8140
8141 if (DiagID) {
8142 SourceLocation ErrLoc = Loc;
8143 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
8144 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
8145 Diag(ErrLoc, DiagID);
8146 Mutable = false;
8147 InvalidDecl = true;
8148 }
8149 }
8150
Abramo Bagnaradff19302011-03-08 08:55:46 +00008151 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00008152 BitWidth, Mutable, HasInit);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008153 if (InvalidDecl)
8154 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +00008155
Douglas Gregor1efa4372009-03-11 18:59:21 +00008156 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
8157 Diag(Loc, diag::err_duplicate_member) << II;
8158 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
8159 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008160 }
8161
John McCall67da35c2010-02-04 22:26:26 +00008162 if (!InvalidDecl && getLangOptions().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +00008163 if (Record->isUnion()) {
8164 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
8165 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
8166 if (RDecl->getDefinition()) {
8167 // C++ [class.union]p1: An object of a class with a non-trivial
8168 // constructor, a non-trivial copy constructor, a non-trivial
8169 // destructor, or a non-trivial copy assignment operator
8170 // cannot be a member of a union, nor can an array of such
8171 // objects.
Alexis Hunt97ab5542011-05-16 22:41:40 +00008172 if (!getLangOptions().CPlusPlus0x && CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +00008173 NewFD->setInvalidDecl();
8174 }
8175 }
8176
8177 // C++ [class.union]p1: If a union contains a member of reference type,
8178 // the program is ill-formed.
8179 if (EltTy->isReferenceType()) {
8180 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
8181 << NewFD->getDeclName() << EltTy;
8182 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +00008183 }
8184 }
8185 }
8186
Douglas Gregor1efa4372009-03-11 18:59:21 +00008187 // FIXME: We need to pass in the attributes given an AST
8188 // representation, not a parser representation.
8189 if (D)
Douglas Gregor758a8692009-06-17 21:51:59 +00008190 // FIXME: What to pass instead of TUScope?
8191 ProcessDeclAttributes(TUScope, NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +00008192
John McCall31168b02011-06-15 23:02:42 +00008193 // In auto-retain/release, infer strong retension for fields of
8194 // retainable type.
8195 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
8196 NewFD->setInvalidDecl();
8197
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +00008198 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +00008199 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +00008200
Douglas Gregor4261e4c2009-03-11 20:50:30 +00008201 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +00008202 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00008203}
8204
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00008205bool Sema::CheckNontrivialField(FieldDecl *FD) {
8206 assert(FD);
8207 assert(getLangOptions().CPlusPlus && "valid check only for C++");
8208
8209 if (FD->isInvalidDecl())
8210 return true;
8211
8212 QualType EltTy = Context.getBaseElementType(FD->getType());
8213 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
8214 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
8215 if (RDecl->getDefinition()) {
8216 // We check for copy constructors before constructors
8217 // because otherwise we'll never get complaints about
8218 // copy constructors.
8219
8220 CXXSpecialMember member = CXXInvalid;
8221 if (!RDecl->hasTrivialCopyConstructor())
8222 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +00008223 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008224 member = CXXDefaultConstructor;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00008225 else if (!RDecl->hasTrivialCopyAssignment())
8226 member = CXXCopyAssignment;
8227 else if (!RDecl->hasTrivialDestructor())
8228 member = CXXDestructor;
8229
8230 if (member != CXXInvalid) {
John McCall31168b02011-06-15 23:02:42 +00008231 if (getLangOptions().ObjCAutoRefCount && RDecl->hasObjectMember()) {
8232 // Objective-C++ ARC: it is an error to have a non-trivial field of
8233 // a union. However, system headers in Objective-C programs
8234 // occasionally have Objective-C lifetime objects within unions,
8235 // and rather than cause the program to fail, we make those
8236 // members unavailable.
8237 SourceLocation Loc = FD->getLocation();
8238 if (getSourceManager().isInSystemHeader(Loc)) {
8239 if (!FD->hasAttr<UnavailableAttr>())
8240 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008241 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +00008242 return false;
8243 }
8244 }
8245
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00008246 Diag(FD->getLocation(), diag::err_illegal_union_or_anon_struct_member)
8247 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
8248 DiagnoseNontrivial(RT, member);
8249 return true;
8250 }
8251 }
8252 }
8253
8254 return false;
8255}
8256
Douglas Gregor8a273912009-07-22 18:25:24 +00008257/// DiagnoseNontrivial - Given that a class has a non-trivial
8258/// special member, figure out why.
8259void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
8260 QualType QT(T, 0U);
8261 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
8262
8263 // Check whether the member was user-declared.
8264 switch (member) {
Douglas Gregorfceea362010-04-22 14:36:26 +00008265 case CXXInvalid:
8266 break;
8267
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008268 case CXXDefaultConstructor:
Douglas Gregor8a273912009-07-22 18:25:24 +00008269 if (RD->hasUserDeclaredConstructor()) {
8270 typedef CXXRecordDecl::ctor_iterator ctor_iter;
Sebastian Redle24b1622009-10-25 22:31:45 +00008271 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
8272 const FunctionDecl *body = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00008273 ci->hasBody(body);
Anders Carlssonb7229932010-04-20 23:32:58 +00008274 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00008275 SourceLocation CtorLoc = ci->getLocation();
8276 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
8277 return;
8278 }
Sebastian Redle24b1622009-10-25 22:31:45 +00008279 }
Douglas Gregor8a273912009-07-22 18:25:24 +00008280
8281 assert(0 && "found no user-declared constructors");
8282 return;
8283 }
8284 break;
8285
8286 case CXXCopyConstructor:
8287 if (RD->hasUserDeclaredCopyConstructor()) {
8288 SourceLocation CtorLoc =
Alexis Huntfcaeae42011-05-25 20:50:04 +00008289 RD->getCopyConstructor(0)->getLocation();
8290 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
8291 return;
8292 }
8293 break;
8294
8295 case CXXMoveConstructor:
8296 if (RD->hasUserDeclaredMoveConstructor()) {
8297 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00008298 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
8299 return;
8300 }
8301 break;
8302
8303 case CXXCopyAssignment:
8304 if (RD->hasUserDeclaredCopyAssignment()) {
8305 // FIXME: this should use the location of the copy
8306 // assignment, not the type.
8307 SourceLocation TyLoc = RD->getSourceRange().getBegin();
8308 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
8309 return;
8310 }
8311 break;
8312
Alexis Huntfcaeae42011-05-25 20:50:04 +00008313 case CXXMoveAssignment:
8314 if (RD->hasUserDeclaredMoveAssignment()) {
8315 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
8316 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
8317 return;
8318 }
8319 break;
8320
Douglas Gregor8a273912009-07-22 18:25:24 +00008321 case CXXDestructor:
8322 if (RD->hasUserDeclaredDestructor()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00008323 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00008324 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
8325 return;
8326 }
8327 break;
8328 }
8329
8330 typedef CXXRecordDecl::base_class_iterator base_iter;
8331
8332 // Virtual bases and members inhibit trivial copying/construction,
8333 // but not trivial destruction.
8334 if (member != CXXDestructor) {
8335 // Check for virtual bases. vbases includes indirect virtual bases,
8336 // so we just iterate through the direct bases.
8337 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
8338 if (bi->isVirtual()) {
8339 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
8340 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
8341 return;
8342 }
8343
8344 // Check for virtual methods.
8345 typedef CXXRecordDecl::method_iterator meth_iter;
8346 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
8347 ++mi) {
8348 if (mi->isVirtual()) {
8349 SourceLocation MLoc = mi->getSourceRange().getBegin();
8350 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
8351 return;
8352 }
8353 }
8354 }
Mike Stump11289f42009-09-09 15:08:12 +00008355
Douglas Gregor8a273912009-07-22 18:25:24 +00008356 bool (CXXRecordDecl::*hasTrivial)() const;
8357 switch (member) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008358 case CXXDefaultConstructor:
Alexis Huntf479f1b2011-05-09 18:22:59 +00008359 hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
Douglas Gregor8a273912009-07-22 18:25:24 +00008360 case CXXCopyConstructor:
8361 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
8362 case CXXCopyAssignment:
8363 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
8364 case CXXDestructor:
8365 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
8366 default:
8367 assert(0 && "unexpected special member"); return;
8368 }
8369
8370 // Check for nontrivial bases (and recurse).
8371 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008372 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
Sebastian Redl1054fae2009-10-25 17:03:50 +00008373 assert(BaseRT && "Don't know how to handle dependent bases");
Douglas Gregor8a273912009-07-22 18:25:24 +00008374 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
8375 if (!(BaseRecTy->*hasTrivial)()) {
8376 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
8377 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
8378 DiagnoseNontrivial(BaseRT, member);
8379 return;
8380 }
8381 }
Mike Stump11289f42009-09-09 15:08:12 +00008382
Douglas Gregor8a273912009-07-22 18:25:24 +00008383 // Check for nontrivial members (and recurse).
8384 typedef RecordDecl::field_iterator field_iter;
8385 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
8386 ++fi) {
Douglas Gregor79f83ed2009-07-23 23:49:00 +00008387 QualType EltTy = Context.getBaseElementType((*fi)->getType());
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008388 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00008389 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
8390
8391 if (!(EltRD->*hasTrivial)()) {
8392 SourceLocation FLoc = (*fi)->getLocation();
8393 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
8394 DiagnoseNontrivial(EltRT, member);
8395 return;
8396 }
8397 }
John McCall31168b02011-06-15 23:02:42 +00008398
8399 if (EltTy->isObjCLifetimeType()) {
8400 switch (EltTy.getObjCLifetime()) {
8401 case Qualifiers::OCL_None:
8402 case Qualifiers::OCL_ExplicitNone:
8403 break;
8404
8405 case Qualifiers::OCL_Autoreleasing:
8406 case Qualifiers::OCL_Weak:
8407 case Qualifiers::OCL_Strong:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008408 Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership)
John McCall31168b02011-06-15 23:02:42 +00008409 << QT << EltTy.getObjCLifetime();
8410 return;
8411 }
8412 }
Douglas Gregor8a273912009-07-22 18:25:24 +00008413 }
8414
8415 assert(0 && "found no explanation for non-trivial member");
8416}
8417
Mike Stump11289f42009-09-09 15:08:12 +00008418/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00008419/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008420static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00008421TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00008422 switch (ivarVisibility) {
Chris Lattner79ef8432008-10-12 00:28:42 +00008423 default: assert(0 && "Unknown visitibility kind");
8424 case tok::objc_private: return ObjCIvarDecl::Private;
8425 case tok::objc_public: return ObjCIvarDecl::Public;
8426 case tok::objc_protected: return ObjCIvarDecl::Protected;
8427 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +00008428 }
8429}
8430
Mike Stump11289f42009-09-09 15:08:12 +00008431/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +00008432/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +00008433Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00008434 SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +00008435 Declarator &D, Expr *BitfieldWidth,
Chris Lattner83f095c2009-03-28 19:18:32 +00008436 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +00008437
Fariborz Jahaniande615832008-04-10 23:32:45 +00008438 IdentifierInfo *II = D.getIdentifier();
8439 Expr *BitWidth = (Expr*)BitfieldWidth;
8440 SourceLocation Loc = DeclStart;
8441 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00008442
Fariborz Jahaniande615832008-04-10 23:32:45 +00008443 // FIXME: Unnamed fields can be handled in various different ways, for
8444 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +00008445
John McCall8cb7bdf2010-06-04 23:28:52 +00008446 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8447 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00008448
Fariborz Jahaniande615832008-04-10 23:32:45 +00008449 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +00008450 // 6.7.2.1p3, 6.7.2.1p4
Chris Lattner73bf7b42009-03-05 22:45:59 +00008451 if (VerifyBitField(Loc, II, T, BitWidth)) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008452 D.setInvalidType();
Chris Lattner73bf7b42009-03-05 22:45:59 +00008453 BitWidth = 0;
8454 }
Fariborz Jahaniande615832008-04-10 23:32:45 +00008455 } else {
8456 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +00008457
Fariborz Jahaniande615832008-04-10 23:32:45 +00008458 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +00008459
Fariborz Jahaniande615832008-04-10 23:32:45 +00008460 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +00008461 if (T->isReferenceType()) {
8462 Diag(Loc, diag::err_ivar_reference_type);
8463 D.setInvalidType();
8464 }
Fariborz Jahaniande615832008-04-10 23:32:45 +00008465 // C99 6.7.2.1p8: A member of a structure or union may have any type other
8466 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +00008467 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +00008468 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008469 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +00008470 }
Mike Stump11289f42009-09-09 15:08:12 +00008471
Ted Kremenek73295fa2008-07-23 18:04:17 +00008472 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +00008473 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +00008474 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
8475 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +00008476 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00008477 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Daniel Dunbar229385c2010-04-02 18:29:09 +00008478 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +00008479 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +00008480 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00008481 if (!LangOpts.ObjCNonFragileABI2) {
Fariborz Jahanian68453832009-06-05 18:16:35 +00008482 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00008483 EnclosingContext = IMPDecl->getClassInterface();
8484 assert(EnclosingContext && "Implementation has no class interface!");
8485 }
8486 else
8487 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00008488 } else {
8489 if (ObjCCategoryDecl *CDecl =
8490 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
8491 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
8492 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +00008493 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00008494 }
8495 }
Daniel Dunbar229385c2010-04-02 18:29:09 +00008496 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00008497 }
Mike Stump11289f42009-09-09 15:08:12 +00008498
Ted Kremenek73295fa2008-07-23 18:04:17 +00008499 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +00008500 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
8501 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +00008502 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +00008503
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008504 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00008505 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +00008506 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +00008507 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008508 && !isa<TagDecl>(PrevDecl)) {
8509 Diag(Loc, diag::err_duplicate_member) << II;
8510 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
8511 NewID->setInvalidDecl();
8512 }
8513 }
8514
Ted Kremenek73295fa2008-07-23 18:04:17 +00008515 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +00008516 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +00008517
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008518 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +00008519 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +00008520
John McCall31168b02011-06-15 23:02:42 +00008521 // In ARC, infer 'retaining' for ivars of retainable type.
8522 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
8523 NewID->setInvalidDecl();
8524
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008525 if (II) {
8526 // FIXME: When interfaces are DeclContexts, we'll need to add
8527 // these to the interface.
John McCall48871652010-08-21 09:40:31 +00008528 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008529 IdResolver.AddDecl(NewID);
8530 }
8531
John McCall48871652010-08-21 09:40:31 +00008532 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +00008533}
8534
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00008535/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
8536/// class and class extensions. For every class @interface and class
8537/// extension @interface, if the last ivar is a bitfield of any type,
8538/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00008539void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008540 SmallVectorImpl<Decl *> &AllIvarDecls) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00008541 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
8542 return;
8543
8544 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
8545 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
8546
8547 if (!Ivar->isBitField())
8548 return;
8549 uint64_t BitFieldSize =
8550 Ivar->getBitWidth()->EvaluateAsInt(Context).getZExtValue();
8551 if (BitFieldSize == 0)
8552 return;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00008553 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00008554 if (!ID) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00008555 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00008556 if (!CD->IsClassExtension())
8557 return;
8558 }
8559 // No need to add this to end of @implementation.
8560 else
8561 return;
8562 }
8563 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor1d394802011-08-03 16:26:46 +00008564 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
8565 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00008566
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00008567 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaradff19302011-03-08 08:55:46 +00008568 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00008569 Context.CharTy,
Douglas Gregor1d394802011-08-03 16:26:46 +00008570 Context.getTrivialTypeSourceInfo(Context.CharTy,
8571 DeclLoc),
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00008572 ObjCIvarDecl::Private, BW,
8573 true);
8574 AllIvarDecls.push_back(Ivar);
8575}
8576
Fariborz Jahanian343f7092007-09-29 00:54:24 +00008577void Sema::ActOnFields(Scope* S,
John McCall48871652010-08-21 09:40:31 +00008578 SourceLocation RecLoc, Decl *EnclosingDecl,
8579 Decl **Fields, unsigned NumFields,
Daniel Dunbar15619c72008-10-03 02:03:53 +00008580 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar325601a2008-10-03 17:33:35 +00008581 AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00008582 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +00008583
Chris Lattnerd13b8b52009-02-23 22:00:08 +00008584 // If the decl this is being inserted into is invalid, then it may be a
8585 // redeclaration or some other bogus case. Don't try to add fields to it.
8586 if (EnclosingDecl->isInvalidDecl()) {
8587 // FIXME: Deallocate fields?
8588 return;
8589 }
8590
Mike Stump11289f42009-09-09 15:08:12 +00008591
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00008592 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +00008593 unsigned NumNamedMembers = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008594 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +00008595
Chris Lattnerd13b8b52009-02-23 22:00:08 +00008596 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
John McCall31168b02011-06-15 23:02:42 +00008597 bool ARCErrReported = false;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00008598 for (unsigned i = 0; i != NumFields; ++i) {
John McCall48871652010-08-21 09:40:31 +00008599 FieldDecl *FD = cast<FieldDecl>(Fields[i]);
Mike Stump11289f42009-09-09 15:08:12 +00008600
Chris Lattner720a0542007-01-25 00:44:24 +00008601 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +00008602 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +00008603
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008604 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00008605 // Remember all fields written by the user.
8606 RecFields.push_back(FD);
8607 }
Mike Stump11289f42009-09-09 15:08:12 +00008608
Chris Lattner73bf7b42009-03-05 22:45:59 +00008609 // If the field is already invalid for some reason, don't emit more
8610 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +00008611 if (FD->isInvalidDecl()) {
8612 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +00008613 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +00008614 }
Mike Stump11289f42009-09-09 15:08:12 +00008615
Douglas Gregorac1fb652009-03-24 19:52:54 +00008616 // C99 6.7.2.1p2:
8617 // A structure or union shall not contain a member with
8618 // incomplete or function type (hence, a structure shall not
8619 // contain an instance of itself, but may contain a pointer to
8620 // an instance of itself), except that the last member of a
8621 // structure with more than one named member may have incomplete
8622 // array type; such a structure (and any union containing,
8623 // possibly recursively, a member that is such a structure)
8624 // shall not be a member of a structure or an element of an
8625 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00008626 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00008627 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +00008628 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00008629 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00008630 FD->setInvalidDecl();
8631 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00008632 continue;
Francois Pichetf657b632010-09-15 00:14:08 +00008633 } else if (FDTy->isIncompleteArrayType() && Record &&
8634 ((i == NumFields - 1 && !Record->isUnion()) ||
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008635 ((getLangOptions().Microsoft || getLangOptions().CPlusPlus) &&
Francois Pichetf657b632010-09-15 00:14:08 +00008636 (i == NumFields - 1 || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00008637 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008638 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +00008639 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +00008640 // as the sole element of a struct/class.
Francois Pichetf657b632010-09-15 00:14:08 +00008641 if (getLangOptions().Microsoft) {
8642 if (Record->isUnion())
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008643 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
Francois Pichetf657b632010-09-15 00:14:08 +00008644 << FD->getDeclName();
8645 else if (NumFields == 1)
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008646 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
Francois Pichetf657b632010-09-15 00:14:08 +00008647 << FD->getDeclName() << Record->getTagKind();
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008648 } else if (getLangOptions().CPlusPlus) {
8649 if (Record->isUnion())
8650 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
8651 << FD->getDeclName();
8652 else if (NumFields == 1)
8653 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
8654 << FD->getDeclName() << Record->getTagKind();
8655 } else if (NumNamedMembers < 1) {
Chris Lattner651d42d2008-11-20 06:38:18 +00008656 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00008657 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00008658 FD->setInvalidDecl();
8659 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00008660 continue;
8661 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00008662 if (!FD->getType()->isDependentType() &&
John McCall31168b02011-06-15 23:02:42 +00008663 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00008664 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +00008665 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00008666 FD->setInvalidDecl();
8667 EnclosingDecl->setInvalidDecl();
8668 continue;
8669 }
Chris Lattner720a0542007-01-25 00:44:24 +00008670 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00008671 if (Record)
8672 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +00008673 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00008674 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +00008675 diag::err_field_incomplete)) {
8676 // Incomplete type
8677 FD->setInvalidDecl();
8678 EnclosingDecl->setInvalidDecl();
8679 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008680 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +00008681 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
8682 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00008683 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +00008684 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00008685 } else {
8686 // If this is a struct/class and this is not the last element, reject
8687 // it. Note that GCC supports variable sized arrays in the middle of
8688 // structures.
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00008689 if (i != NumFields-1)
8690 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +00008691 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00008692 else {
8693 // We support flexible arrays at the end of structs in
8694 // other structs as an extension.
8695 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
8696 << FD->getDeclName();
8697 if (Record)
8698 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00008699 }
Chris Lattner720a0542007-01-25 00:44:24 +00008700 }
8701 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00008702 if (Record && FDTTy->getDecl()->hasObjectMember())
8703 Record->setHasObjectMember(true);
John McCall8b07ec22010-05-15 11:32:37 +00008704 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00008705 /// A field cannot be an Objective-c object
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00008706 Diag(FD->getLocation(), diag::err_statically_allocated_object)
8707 << FixItHint::CreateInsertion(FD->getLocation(), "*");
8708 QualType T = Context.getObjCObjectPointerType(FD->getType());
8709 FD->setType(T);
John McCall31168b02011-06-15 23:02:42 +00008710 }
8711 else if (!getLangOptions().CPlusPlus) {
8712 if (getLangOptions().ObjCAutoRefCount && Record && !ARCErrReported) {
8713 // It's an error in ARC if a field has lifetime.
8714 // We don't want to report this in a system header, though,
8715 // so we just make the field unavailable.
8716 // FIXME: that's really not sufficient; we need to make the type
8717 // itself invalid to, say, initialize or copy.
8718 QualType T = FD->getType();
8719 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
8720 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
8721 SourceLocation loc = FD->getLocation();
8722 if (getSourceManager().isInSystemHeader(loc)) {
8723 if (!FD->hasAttr<UnavailableAttr>()) {
8724 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008725 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +00008726 }
8727 } else {
8728 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct);
8729 }
8730 ARCErrReported = true;
8731 }
8732 }
8733 else if (getLangOptions().ObjC1 &&
Mike Stump12b8ce12009-08-04 21:02:39 +00008734 getLangOptions().getGCMode() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +00008735 Record && !Record->hasObjectMember()) {
8736 if (FD->getType()->isObjCObjectPointerType() ||
8737 FD->getType().isObjCGCStrong())
8738 Record->setHasObjectMember(true);
8739 else if (Context.getAsArrayType(FD->getType())) {
8740 QualType BaseType = Context.getBaseElementType(FD->getType());
8741 if (BaseType->isRecordType() &&
8742 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
8743 Record->setHasObjectMember(true);
8744 else if (BaseType->isObjCObjectPointerType() ||
8745 BaseType.isObjCGCStrong())
8746 Record->setHasObjectMember(true);
8747 }
8748 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008749 }
Chris Lattner82625602007-01-24 02:26:21 +00008750 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008751 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +00008752 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00008753 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00008754
Chris Lattner82625602007-01-24 02:26:21 +00008755 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +00008756 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00008757 bool Completed = false;
8758 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
8759 if (!CXXRecord->isInvalidDecl()) {
8760 // Set access bits correctly on the directly-declared conversions.
8761 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
8762 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
8763 I != E; ++I)
8764 Convs->setAccess(I, (*I)->getAccess());
8765
8766 if (!CXXRecord->isDependentType()) {
John McCall31168b02011-06-15 23:02:42 +00008767 // Objective-C Automatic Reference Counting:
8768 // If a class has a non-static data member of Objective-C pointer
8769 // type (or array thereof), it is a non-POD type and its
8770 // default constructor (if any), copy constructor, copy assignment
8771 // operator, and destructor are non-trivial.
8772 //
8773 // This rule is also handled by CXXRecordDecl::completeDefinition().
8774 // However, here we check whether this particular class is only
8775 // non-POD because of the presence of an Objective-C pointer member.
8776 // If so, objects of this type cannot be shared between code compiled
8777 // with instant objects and code compiled with manual retain/release.
8778 if (getLangOptions().ObjCAutoRefCount &&
8779 CXXRecord->hasObjectMember() &&
8780 CXXRecord->getLinkage() == ExternalLinkage) {
8781 if (CXXRecord->isPOD()) {
8782 Diag(CXXRecord->getLocation(),
8783 diag::warn_arc_non_pod_class_with_object_member)
8784 << CXXRecord;
8785 } else {
8786 // FIXME: Fix-Its would be nice here, but finding a good location
8787 // for them is going to be tricky.
8788 if (CXXRecord->hasTrivialCopyConstructor())
8789 Diag(CXXRecord->getLocation(),
8790 diag::warn_arc_trivial_member_function_with_object_member)
8791 << CXXRecord << 0;
8792 if (CXXRecord->hasTrivialCopyAssignment())
8793 Diag(CXXRecord->getLocation(),
8794 diag::warn_arc_trivial_member_function_with_object_member)
8795 << CXXRecord << 1;
8796 if (CXXRecord->hasTrivialDestructor())
8797 Diag(CXXRecord->getLocation(),
8798 diag::warn_arc_trivial_member_function_with_object_member)
8799 << CXXRecord << 2;
8800 }
8801 }
8802
Sebastian Redl623ea822011-05-19 05:13:44 +00008803 // Adjust user-defined destructor exception spec.
8804 if (getLangOptions().CPlusPlus0x &&
8805 CXXRecord->hasUserDeclaredDestructor())
8806 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
8807
Douglas Gregor8fb95122010-09-29 00:15:42 +00008808 // Add any implicitly-declared members to this class.
8809 AddImplicitlyDeclaredMembersToClass(CXXRecord);
8810
8811 // If we have virtual base classes, we may end up finding multiple
8812 // final overriders for a given virtual function. Check for this
8813 // problem now.
8814 if (CXXRecord->getNumVBases()) {
8815 CXXFinalOverriderMap FinalOverriders;
8816 CXXRecord->getFinalOverriders(FinalOverriders);
8817
8818 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
8819 MEnd = FinalOverriders.end();
8820 M != MEnd; ++M) {
8821 for (OverridingMethods::iterator SO = M->second.begin(),
8822 SOEnd = M->second.end();
8823 SO != SOEnd; ++SO) {
8824 assert(SO->second.size() > 0 &&
8825 "Virtual function without overridding functions?");
8826 if (SO->second.size() == 1)
8827 continue;
8828
8829 // C++ [class.virtual]p2:
8830 // In a derived class, if a virtual member function of a base
8831 // class subobject has more than one final overrider the
8832 // program is ill-formed.
8833 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
8834 << (NamedDecl *)M->first << Record;
8835 Diag(M->first->getLocation(),
8836 diag::note_overridden_virtual_function);
8837 for (OverridingMethods::overriding_iterator
8838 OM = SO->second.begin(),
8839 OMEnd = SO->second.end();
8840 OM != OMEnd; ++OM)
8841 Diag(OM->Method->getLocation(), diag::note_final_overrider)
8842 << (NamedDecl *)M->first << OM->Method->getParent();
8843
8844 Record->setInvalidDecl();
8845 }
8846 }
8847 CXXRecord->completeDefinition(&FinalOverriders);
8848 Completed = true;
8849 }
8850 }
8851 }
8852 }
8853
8854 if (!Completed)
8855 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +00008856
8857 // Now that the record is complete, do any delayed exception spec checks
8858 // we were missing.
Richard Smith938f40b2011-06-11 17:19:42 +00008859 while (!DelayedDestructorExceptionSpecChecks.empty()) {
Sebastian Redl623ea822011-05-19 05:13:44 +00008860 const CXXDestructorDecl *Dtor =
8861 DelayedDestructorExceptionSpecChecks.back().first;
Richard Smith938f40b2011-06-11 17:19:42 +00008862 if (Dtor->getParent() != Record)
8863 break;
8864
8865 assert(!Dtor->getParent()->isDependentType() &&
8866 "Should not ever add destructors of templates into the list.");
8867 CheckOverridingFunctionExceptionSpec(Dtor,
8868 DelayedDestructorExceptionSpecChecks.back().second);
8869 DelayedDestructorExceptionSpecChecks.pop_back();
Sebastian Redl623ea822011-05-19 05:13:44 +00008870 }
8871
Chris Lattner622c1932008-02-06 00:51:33 +00008872 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +00008873 ObjCIvarDecl **ClsFields =
8874 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +00008875 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner22298722009-02-20 21:35:13 +00008876 ID->setLocEnd(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +00008877 // Add ivar's to class's DeclContext.
8878 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
8879 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008880 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +00008881 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +00008882 // Must enforce the rule that ivars in the base classes may not be
8883 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00008884 if (ID->getSuperClass())
8885 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +00008886 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +00008887 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008888 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +00008889 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
8890 // Ivar declared in @implementation never belongs to the implementation.
8891 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +00008892 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +00008893 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +00008894 } else if (ObjCCategoryDecl *CDecl =
8895 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00008896 // case of ivars in class extension; all other cases have been
8897 // reported as errors elsewhere.
8898 // FIXME. Class extension does not have a LocEnd field.
8899 // CDecl->setLocEnd(RBrac);
8900 // Add ivar's to class extension's DeclContext.
8901 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
8902 ClsFields[i]->setLexicalDeclContext(CDecl);
8903 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +00008904 }
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00008905 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00008906 }
Daniel Dunbar325601a2008-10-03 17:33:35 +00008907
8908 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00008909 ProcessDeclAttributeList(S, Record, Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00008910
8911 // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
8912 // set the visibility of this record.
8913 if (Record && !Record->getDeclContext()->isRecord())
8914 AddPushedVisibilityAttribute(Record);
Chris Lattner1300fb92007-01-23 23:42:53 +00008915}
8916
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008917/// \brief Determine whether the given integral value is representable within
8918/// the given type T.
8919static bool isRepresentableIntegerValue(ASTContext &Context,
8920 llvm::APSInt &Value,
8921 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +00008922 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +00008923 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008924
Douglas Gregor0bf31402010-10-08 23:50:27 +00008925 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008926 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +00008927 --BitWidth;
8928 return Value.getActiveBits() <= BitWidth;
8929 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008930 return Value.getMinSignedBits() <= BitWidth;
8931}
8932
8933// \brief Given an integral type, return the next larger integral type
8934// (or a NULL type of no such type exists).
8935static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
8936 // FIXME: Int128/UInt128 support, which also needs to be introduced into
8937 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +00008938 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008939 const unsigned NumTypes = 4;
8940 QualType SignedIntegralTypes[NumTypes] = {
8941 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
8942 };
8943 QualType UnsignedIntegralTypes[NumTypes] = {
8944 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
8945 Context.UnsignedLongLongTy
8946 };
8947
8948 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008949 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
8950 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008951 for (unsigned I = 0; I != NumTypes; ++I)
8952 if (Context.getTypeSize(Types[I]) > BitWidth)
8953 return Types[I];
8954
8955 return QualType();
8956}
8957
Douglas Gregor954f6b272009-03-17 19:05:46 +00008958EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
8959 EnumConstantDecl *LastEnumConst,
8960 SourceLocation IdLoc,
8961 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +00008962 Expr *Val) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00008963 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008964 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +00008965 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +00008966
8967 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
8968 Val = 0;
8969
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008970 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +00008971 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008972 EltTy = Context.DependentTy;
8973 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008974 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
8975 SourceLocation ExpLoc;
Douglas Gregordc70c3a2010-03-02 17:53:14 +00008976 if (!Val->isValueDependent() &&
8977 VerifyIntegerConstantExpression(Val, &EnumVal)) {
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008978 Val = 0;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008979 } else {
8980 if (!getLangOptions().CPlusPlus) {
8981 // C99 6.7.2.2p2:
8982 // The expression that defines the value of an enumeration constant
8983 // shall be an integer constant expression that has a value
8984 // representable as an int.
8985
8986 // Complain if the value is not representable in an int.
8987 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
8988 Diag(IdLoc, diag::ext_enum_value_not_int)
8989 << EnumVal.toString(10) << Val->getSourceRange()
Douglas Gregorc0b8c812010-02-17 22:40:11 +00008990 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008991 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
8992 // Force the type of the expression to 'int'.
John Wiegley01296292011-04-08 18:41:53 +00008993 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008994 }
8995 }
8996
Douglas Gregor0bf31402010-10-08 23:50:27 +00008997 if (Enum->isFixed()) {
8998 EltTy = Enum->getIntegerType();
8999
9000 // C++0x [dcl.enum]p5:
9001 // ... if the initializing value of an enumerator cannot be
9002 // represented by the underlying type, the program is ill-formed.
Francois Picheta3108062010-10-18 15:01:13 +00009003 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
9004 if (getLangOptions().Microsoft) {
9005 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley01296292011-04-08 18:41:53 +00009006 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Francois Picheta3108062010-10-18 15:01:13 +00009007 } else
9008 Diag(IdLoc, diag::err_enumerator_too_large)
9009 << EltTy;
9010 } else
John Wiegley01296292011-04-08 18:41:53 +00009011 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Douglas Gregor0bf31402010-10-08 23:50:27 +00009012 }
9013 else {
9014 // C++0x [dcl.enum]p5:
9015 // If the underlying type is not fixed, the type of each enumerator
9016 // is the type of its initializing value:
9017 // - If an initializer is specified for an enumerator, the
9018 // initializing value has the same type as the expression.
9019 EltTy = Val->getType();
9020 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +00009021 }
Douglas Gregor954f6b272009-03-17 19:05:46 +00009022 }
9023 }
Mike Stump11289f42009-09-09 15:08:12 +00009024
Douglas Gregor954f6b272009-03-17 19:05:46 +00009025 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +00009026 if (Enum->isDependentType())
9027 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009028 else if (!LastEnumConst) {
9029 // C++0x [dcl.enum]p5:
9030 // If the underlying type is not fixed, the type of each enumerator
9031 // is the type of its initializing value:
9032 // - If no initializer is specified for the first enumerator, the
9033 // initializing value has an unspecified integral type.
9034 //
9035 // GCC uses 'int' for its unspecified integral type, as does
9036 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +00009037 if (Enum->isFixed()) {
9038 EltTy = Enum->getIntegerType();
9039 }
9040 else {
9041 EltTy = Context.IntTy;
9042 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009043 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +00009044 // Assign the last value + 1.
9045 EnumVal = LastEnumConst->getInitVal();
9046 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009047 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +00009048
9049 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009050 if (EnumVal < LastEnumConst->getInitVal()) {
9051 // C++0x [dcl.enum]p5:
9052 // If the underlying type is not fixed, the type of each enumerator
9053 // is the type of its initializing value:
9054 //
9055 // - Otherwise the type of the initializing value is the same as
9056 // the type of the initializing value of the preceding enumerator
9057 // unless the incremented value is not representable in that type,
9058 // in which case the type is an unspecified integral type
9059 // sufficient to contain the incremented value. If no such type
9060 // exists, the program is ill-formed.
9061 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +00009062 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009063 // There is no integral type larger enough to represent this
9064 // value. Complain, then allow the value to wrap around.
9065 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +00009066 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +00009067 ++EnumVal;
9068 if (Enum->isFixed())
9069 // When the underlying type is fixed, this is ill-formed.
9070 Diag(IdLoc, diag::err_enumerator_wrapped)
9071 << EnumVal.toString(10)
9072 << EltTy;
9073 else
9074 Diag(IdLoc, diag::warn_enumerator_too_large)
9075 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009076 } else {
9077 EltTy = T;
9078 }
9079
9080 // Retrieve the last enumerator's value, extent that type to the
9081 // type that is supposed to be large enough to represent the incremented
9082 // value, then increment.
9083 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00009084 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +00009085 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009086 ++EnumVal;
9087
9088 // If we're not in C++, diagnose the overflow of enumerator values,
9089 // which in C99 means that the enumerator value is not representable in
9090 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
9091 // permits enumerator values that are representable in some larger
9092 // integral type.
9093 if (!getLangOptions().CPlusPlus && !T.isNull())
9094 Diag(IdLoc, diag::warn_enum_value_overflow);
9095 } else if (!getLangOptions().CPlusPlus &&
9096 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
9097 // Enforce C99 6.7.2.2p2 even when we compute the next value.
9098 Diag(IdLoc, diag::ext_enum_value_not_int)
9099 << EnumVal.toString(10) << 1;
9100 }
Douglas Gregor954f6b272009-03-17 19:05:46 +00009101 }
9102 }
Mike Stump11289f42009-09-09 15:08:12 +00009103
Douglas Gregordc70c3a2010-03-02 17:53:14 +00009104 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009105 // Make the enumerator value match the signedness and size of the
9106 // enumerator's type.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009107 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00009108 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009109 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +00009110
Douglas Gregor954f6b272009-03-17 19:05:46 +00009111 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +00009112 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +00009113}
9114
9115
John McCall811a0f52010-10-22 23:36:17 +00009116Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
9117 SourceLocation IdLoc, IdentifierInfo *Id,
9118 AttributeList *Attr,
Richard Trieu2bd04012011-09-09 02:00:50 +00009119 SourceLocation EqualLoc, Expr *val) {
John McCall48871652010-08-21 09:40:31 +00009120 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +00009121 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +00009122 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner4ef40012007-06-11 01:28:17 +00009123 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00009124
Chris Lattner1a76a3c2007-08-26 06:24:45 +00009125 // The scope passed in may not be a decl scope. Zip up the scope tree until
9126 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +00009127 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +00009128
Chris Lattner8116d1b2007-01-25 22:38:29 +00009129 // Verify that there isn't already something declared with this name in this
9130 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009131 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +00009132 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +00009133 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00009134 // Maybe we will complain about the shadowed template parameter.
9135 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
9136 // Just pretend that we didn't see the previous declaration.
9137 PrevDecl = 0;
9138 }
9139
9140 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +00009141 // When in C++, we may get a TagDecl with the same name; in this case the
9142 // enum constant will 'hide' the tag.
9143 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
9144 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +00009145 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00009146 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +00009147 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +00009148 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00009149 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +00009150 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00009151 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +00009152 }
9153 }
Chris Lattner4ef40012007-06-11 01:28:17 +00009154
Douglas Gregor36c22a22010-10-15 13:21:21 +00009155 // C++ [class.mem]p13:
9156 // If T is the name of a class, then each of the following shall have a
9157 // name different from T:
9158 // - every enumerator of every member of class T that is an enumerated
9159 // type
9160 if (CXXRecordDecl *Record
9161 = dyn_cast<CXXRecordDecl>(
9162 TheEnumDecl->getDeclContext()->getRedeclContext()))
9163 if (Record->getIdentifier() && Record->getIdentifier() == Id)
9164 Diag(IdLoc, diag::err_member_name_of_class) << Id;
9165
John McCall811a0f52010-10-22 23:36:17 +00009166 EnumConstantDecl *New =
9167 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +00009168
John McCall553c0792010-01-23 00:46:32 +00009169 if (New) {
John McCall811a0f52010-10-22 23:36:17 +00009170 // Process attributes.
9171 if (Attr) ProcessDeclAttributeList(S, New, Attr);
9172
9173 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +00009174 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +00009175 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +00009176 }
Douglas Gregor2f521192008-12-17 02:04:30 +00009177
John McCall48871652010-08-21 09:40:31 +00009178 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +00009179}
9180
Mike Stump6814d1c2009-05-16 07:06:02 +00009181void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +00009182 SourceLocation RBraceLoc, Decl *EnumDeclX,
9183 Decl **Elements, unsigned NumElements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00009184 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +00009185 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +00009186 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00009187
9188 if (Attr)
9189 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +00009190
Eli Friedmand0e60972009-12-11 01:34:50 +00009191 if (Enum->isDependentType()) {
9192 for (unsigned i = 0; i != NumElements; ++i) {
9193 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +00009194 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +00009195 if (!ECD) continue;
9196
9197 ECD->setType(EnumType);
9198 }
9199
John McCall9aa35be2010-05-06 08:49:23 +00009200 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +00009201 return;
9202 }
9203
Chris Lattner67933c02007-08-28 05:10:31 +00009204 // TODO: If the result value doesn't fit in an int, it must be a long or long
9205 // long value. ISO C does not support this, but GCC does as an extension,
9206 // emit a warning.
Douglas Gregore8bbc122011-09-02 00:18:52 +00009207 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
9208 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
9209 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +00009210
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009211 // Verify that all the values are okay, compute the size of the values, and
9212 // reverse the list.
9213 unsigned NumNegativeBits = 0;
9214 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +00009215
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009216 // Keep track of whether all elements have type int.
9217 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +00009218
Chris Lattnerc1915e22007-01-25 07:29:02 +00009219 for (unsigned i = 0; i != NumElements; ++i) {
9220 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +00009221 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +00009222 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +00009223
Chris Lattnerbf478cb2007-08-28 05:27:00 +00009224 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +00009225
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009226 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +00009227 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +00009228 NumPositiveBits = std::max(NumPositiveBits,
9229 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009230 else
Chris Lattner49f980c2008-01-14 21:47:29 +00009231 NumNegativeBits = std::max(NumNegativeBits,
9232 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00009233
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009234 // Keep track of whether every enum element has type int (very commmon).
9235 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +00009236 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +00009237 }
Mike Stump11289f42009-09-09 15:08:12 +00009238
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009239 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009240 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00009241 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00009242
John McCall56774992009-12-09 09:09:27 +00009243 // C++0x N3000 [conv.prom]p3:
9244 // An rvalue of an unscoped enumeration type whose underlying
9245 // type is not fixed can be converted to an rvalue of the first
9246 // of the following types that can represent all the values of
9247 // the enumeration: int, unsigned int, long int, unsigned long
9248 // int, long long int, or unsigned long long int.
9249 // C99 6.4.4.3p2:
9250 // An identifier declared as an enumeration constant has type int.
9251 // The C99 rule is modified by a gcc extension
9252 QualType BestPromotionType;
9253
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00009254 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +00009255 // -fshort-enums is the equivalent to specifying the packed attribute on all
9256 // enum definitions.
9257 if (LangOpts.ShortEnums)
9258 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00009259
Douglas Gregor0bf31402010-10-08 23:50:27 +00009260 if (Enum->isFixed()) {
9261 BestType = BestPromotionType = Enum->getIntegerType();
Duncan Sands38b918c2010-10-12 14:07:59 +00009262 // We don't need to set BestWidth, because BestType is going to be the type
9263 // of the enumerators, but we do anyway because otherwise some compilers
9264 // warn that it might be used uninitialized.
9265 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +00009266 }
9267 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +00009268 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009269 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00009270 // If it's packed, check also if it fits a char or a short.
9271 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +00009272 BestType = Context.SignedCharTy;
9273 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +00009274 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00009275 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +00009276 BestType = Context.ShortTy;
9277 BestWidth = ShortWidth;
9278 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009279 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00009280 BestWidth = IntWidth;
9281 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +00009282 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +00009283
John McCall56774992009-12-09 09:09:27 +00009284 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009285 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +00009286 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +00009287 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +00009288
Chris Lattner3a370bf2007-08-29 17:31:48 +00009289 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009290 Diag(Enum->getLocation(), diag::warn_enum_too_large);
9291 BestType = Context.LongLongTy;
9292 }
9293 }
John McCall56774992009-12-09 09:09:27 +00009294 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009295 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +00009296 // If there is no negative value, figure out the smallest type that fits
9297 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00009298 // If it's packed, check also if it fits a char or a short.
9299 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +00009300 BestType = Context.UnsignedCharTy;
9301 BestPromotionType = Context.IntTy;
9302 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00009303 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +00009304 BestType = Context.UnsignedShortTy;
9305 BestPromotionType = Context.IntTy;
9306 BestWidth = ShortWidth;
9307 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009308 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00009309 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +00009310 BestPromotionType
9311 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
9312 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00009313 } else if (NumPositiveBits <=
Douglas Gregore8bbc122011-09-02 00:18:52 +00009314 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009315 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +00009316 BestPromotionType
9317 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
9318 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +00009319 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +00009320 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +00009321 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009322 "How could an initializer get larger than ULL?");
9323 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +00009324 BestPromotionType
9325 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
9326 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009327 }
9328 }
Mike Stump11289f42009-09-09 15:08:12 +00009329
Chris Lattner3a370bf2007-08-29 17:31:48 +00009330 // Loop over all of the enumerator constants, changing their types to match
9331 // the type of the enum if needed.
9332 for (unsigned i = 0; i != NumElements; ++i) {
John McCall48871652010-08-21 09:40:31 +00009333 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +00009334 if (!ECD) continue; // Already issued a diagnostic.
9335
9336 // Standard C says the enumerators have int type, but we allow, as an
9337 // extension, the enumerators to be larger than int size. If each
9338 // enumerator value fits in an int, type it as an int, otherwise type it the
9339 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
9340 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +00009341
9342 // Determine whether the value fits into an int.
9343 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +00009344
9345 // If it fits into an integer type, force it. Otherwise force it to match
9346 // the enum decl type.
9347 QualType NewTy;
9348 unsigned NewWidth;
9349 bool NewSign;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009350 if (!getLangOptions().CPlusPlus &&
9351 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +00009352 NewTy = Context.IntTy;
9353 NewWidth = IntWidth;
9354 NewSign = true;
9355 } else if (ECD->getType() == BestType) {
9356 // Already the right type!
Douglas Gregor1d248c52008-12-12 02:00:36 +00009357 if (getLangOptions().CPlusPlus)
9358 // C++ [dcl.enum]p4: Following the closing brace of an
9359 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +00009360 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +00009361 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +00009362 continue;
9363 } else {
9364 NewTy = BestType;
9365 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00009366 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +00009367 }
9368
9369 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009370 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +00009371 InitVal.setIsSigned(NewSign);
9372 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +00009373
Chris Lattner3a370bf2007-08-29 17:31:48 +00009374 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +00009375 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00009376 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +00009377 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +00009378 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +00009379 ECD->getInitExpr(),
9380 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +00009381 VK_RValue));
Douglas Gregor1d248c52008-12-12 02:00:36 +00009382 if (getLangOptions().CPlusPlus)
9383 // C++ [dcl.enum]p4: Following the closing brace of an
9384 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +00009385 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +00009386 ECD->setType(EnumType);
9387 else
9388 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +00009389 }
Mike Stump11289f42009-09-09 15:08:12 +00009390
John McCall9aa35be2010-05-06 08:49:23 +00009391 Enum->completeDefinition(BestType, BestPromotionType,
9392 NumPositiveBits, NumNegativeBits);
Chris Lattnerc1915e22007-01-25 07:29:02 +00009393}
Chris Lattner1300fb92007-01-23 23:42:53 +00009394
Abramo Bagnara348823a2011-03-03 14:20:18 +00009395Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
9396 SourceLocation StartLoc,
9397 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +00009398 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +00009399
Douglas Gregor278f52e2009-05-30 00:08:05 +00009400 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +00009401 AsmString, StartLoc,
9402 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009403 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +00009404 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +00009405}
Eli Friedman5ed51982009-06-05 02:44:36 +00009406
Douglas Gregor08142532011-08-26 23:56:07 +00009407DeclResult Sema::ActOnModuleImport(SourceLocation ImportLoc,
9408 IdentifierInfo &ModuleName,
9409 SourceLocation ModuleNameLoc) {
9410 ModuleKey Module = PP.getModuleLoader().loadModule(ImportLoc,
9411 ModuleName, ModuleNameLoc);
9412 if (!Module)
9413 return true;
9414
9415 // FIXME: Actually create a declaration to describe the module import.
9416 (void)Module;
9417 return DeclResult((Decl *)0);
9418}
9419
Eli Friedman5ed51982009-06-05 02:44:36 +00009420void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
9421 SourceLocation PragmaLoc,
9422 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009423 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +00009424
Eli Friedman5ed51982009-06-05 02:44:36 +00009425 if (PrevDecl) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009426 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynn7d470f32009-07-30 03:15:39 +00009427 } else {
9428 (void)WeakUndeclaredIdentifiers.insert(
9429 std::pair<IdentifierInfo*,WeakInfo>
9430 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +00009431 }
Eli Friedman5ed51982009-06-05 02:44:36 +00009432}
9433
9434void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
9435 IdentifierInfo* AliasName,
9436 SourceLocation PragmaLoc,
9437 SourceLocation NameLoc,
9438 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009439 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
9440 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +00009441 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +00009442
Eli Friedman5ed51982009-06-05 02:44:36 +00009443 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +00009444 if (!PrevDecl->hasAttr<AliasAttr>())
9445 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +00009446 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +00009447 } else {
9448 (void)WeakUndeclaredIdentifiers.insert(
9449 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +00009450 }
Eli Friedman5ed51982009-06-05 02:44:36 +00009451}
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00009452
9453Decl *Sema::getObjCDeclContext() const {
9454 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
9455}