blob: 52ed28afb937eced2eccc91f15eebc06e2b11776 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000040#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000041#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000042
43using namespace clang;
44
Chris Lattner8123a952008-04-10 02:22:51 +000045//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
Chris Lattner9e979552008-04-12 23:52:44 +000049namespace {
50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51 /// the default argument of a parameter to determine whether it
52 /// contains any ill-formed subexpressions. For example, this will
53 /// diagnose the use of local variables or parameters within the
54 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000055 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000056 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000057 Expr *DefaultArg;
58 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 public:
Mike Stump1eb44332009-09-09 15:08:12 +000061 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000062 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000063
Chris Lattner9e979552008-04-12 23:52:44 +000064 bool VisitExpr(Expr *Node);
65 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000066 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000067 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattner9e979552008-04-12 23:52:44 +000068 };
Chris Lattner8123a952008-04-10 02:22:51 +000069
Chris Lattner9e979552008-04-12 23:52:44 +000070 /// VisitExpr - Visit all of the children of this expression.
71 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
72 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000073 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000074 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000075 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000076 }
77
Chris Lattner9e979552008-04-12 23:52:44 +000078 /// VisitDeclRefExpr - Visit a reference to a declaration, to
79 /// determine whether this declaration can be used in the default
80 /// argument expression.
81 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000082 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000083 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
84 // C++ [dcl.fct.default]p9
85 // Default arguments are evaluated each time the function is
86 // called. The order of evaluation of function arguments is
87 // unspecified. Consequently, parameters of a function shall not
88 // be used in default argument expressions, even if they are not
89 // evaluated. Parameters of a function declared before a default
90 // argument expression are in scope and can hide namespace and
91 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000092 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000093 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000094 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000095 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000096 // C++ [dcl.fct.default]p7
97 // Local variables shall not be used in default argument
98 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000099 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000100 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000101 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000102 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000103 }
Chris Lattner8123a952008-04-10 02:22:51 +0000104
Douglas Gregor3996f232008-11-04 13:41:56 +0000105 return false;
106 }
Chris Lattner9e979552008-04-12 23:52:44 +0000107
Douglas Gregor796da182008-11-04 14:32:21 +0000108 /// VisitCXXThisExpr - Visit a C++ "this" expression.
109 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
110 // C++ [dcl.fct.default]p8:
111 // The keyword this shall not be used in a default argument of a
112 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000113 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000114 diag::err_param_default_argument_references_this)
115 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000116 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000117
118 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
119 // C++11 [expr.lambda.prim]p13:
120 // A lambda-expression appearing in a default argument shall not
121 // implicitly or explicitly capture any entity.
122 if (Lambda->capture_begin() == Lambda->capture_end())
123 return false;
124
125 return S->Diag(Lambda->getLocStart(),
126 diag::err_lambda_capture_default_arg);
127 }
Chris Lattner8123a952008-04-10 02:22:51 +0000128}
129
Richard Smithe6975e92012-04-17 00:58:00 +0000130void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
131 CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000132 // If we have an MSAny spec already, don't bother.
133 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000134 return;
135
136 const FunctionProtoType *Proto
137 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000138 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
139 if (!Proto)
140 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000141
142 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
143
144 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000145 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000146 ClearExceptions();
147 ComputedEST = EST;
148 return;
149 }
150
Richard Smith7a614d82011-06-11 17:19:42 +0000151 // FIXME: If the call to this decl is using any of its default arguments, we
152 // need to search them for potentially-throwing calls.
153
Sean Hunt001cad92011-05-10 00:49:42 +0000154 // If this function has a basic noexcept, it doesn't affect the outcome.
155 if (EST == EST_BasicNoexcept)
156 return;
157
158 // If we have a throw-all spec at this point, ignore the function.
159 if (ComputedEST == EST_None)
160 return;
161
162 // If we're still at noexcept(true) and there's a nothrow() callee,
163 // change to that specification.
164 if (EST == EST_DynamicNone) {
165 if (ComputedEST == EST_BasicNoexcept)
166 ComputedEST = EST_DynamicNone;
167 return;
168 }
169
170 // Check out noexcept specs.
171 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000172 FunctionProtoType::NoexceptResult NR =
173 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000174 assert(NR != FunctionProtoType::NR_NoNoexcept &&
175 "Must have noexcept result for EST_ComputedNoexcept.");
176 assert(NR != FunctionProtoType::NR_Dependent &&
177 "Should not generate implicit declarations for dependent cases, "
178 "and don't know how to handle them anyway.");
179
180 // noexcept(false) -> no spec on the new function
181 if (NR == FunctionProtoType::NR_Throw) {
182 ClearExceptions();
183 ComputedEST = EST_None;
184 }
185 // noexcept(true) won't change anything either.
186 return;
187 }
188
189 assert(EST == EST_Dynamic && "EST case not considered earlier.");
190 assert(ComputedEST != EST_None &&
191 "Shouldn't collect exceptions when throw-all is guaranteed.");
192 ComputedEST = EST_Dynamic;
193 // Record the exceptions in this function's exception specification.
194 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
195 EEnd = Proto->exception_end();
196 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000197 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000198 Exceptions.push_back(*E);
199}
200
Richard Smith7a614d82011-06-11 17:19:42 +0000201void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000202 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000203 return;
204
205 // FIXME:
206 //
207 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000208 // [An] implicit exception-specification specifies the type-id T if and
209 // only if T is allowed by the exception-specification of a function directly
210 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000211 // function it directly invokes allows all exceptions, and f shall allow no
212 // exceptions if every function it directly invokes allows no exceptions.
213 //
214 // Note in particular that if an implicit exception-specification is generated
215 // for a function containing a throw-expression, that specification can still
216 // be noexcept(true).
217 //
218 // Note also that 'directly invoked' is not defined in the standard, and there
219 // is no indication that we should only consider potentially-evaluated calls.
220 //
221 // Ultimately we should implement the intent of the standard: the exception
222 // specification should be the set of exceptions which can be thrown by the
223 // implicit definition. For now, we assume that any non-nothrow expression can
224 // throw any exception.
225
Richard Smithe6975e92012-04-17 00:58:00 +0000226 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000227 ComputedEST = EST_None;
228}
229
Anders Carlssoned961f92009-08-25 02:29:20 +0000230bool
John McCall9ae2f072010-08-23 23:25:46 +0000231Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000232 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000233 if (RequireCompleteType(Param->getLocation(), Param->getType(),
234 diag::err_typecheck_decl_incomplete_type)) {
235 Param->setInvalidDecl();
236 return true;
237 }
238
Anders Carlssoned961f92009-08-25 02:29:20 +0000239 // C++ [dcl.fct.default]p5
240 // A default argument expression is implicitly converted (clause
241 // 4) to the parameter type. The default argument expression has
242 // the same semantic constraints as the initializer expression in
243 // a declaration of a variable of the parameter type, using the
244 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000245 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
246 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000247 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
248 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000249 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000250 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000251 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000252 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000253 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000254
Richard Smith6c3af3d2013-01-17 01:17:56 +0000255 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000256 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // Okay: add the default argument to the parameter
259 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000261 // We have already instantiated this parameter; provide each of the
262 // instantiations with the uninstantiated default argument.
263 UnparsedDefaultArgInstantiationsMap::iterator InstPos
264 = UnparsedDefaultArgInstantiations.find(Param);
265 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
266 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
267 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
268
269 // We're done tracking this parameter's instantiations.
270 UnparsedDefaultArgInstantiations.erase(InstPos);
271 }
272
Anders Carlsson9351c172009-08-25 03:18:48 +0000273 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000274}
275
Chris Lattner8123a952008-04-10 02:22:51 +0000276/// ActOnParamDefaultArgument - Check whether the default argument
277/// provided for a function parameter is well-formed. If so, attach it
278/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000279void
John McCalld226f652010-08-21 09:40:31 +0000280Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000281 Expr *DefaultArg) {
282 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000283 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000284
John McCalld226f652010-08-21 09:40:31 +0000285 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000286 UnparsedDefaultArgLocs.erase(Param);
287
Chris Lattner3d1cee32008-04-08 05:04:30 +0000288 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000289 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000290 Diag(EqualLoc, diag::err_param_default_argument)
291 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000292 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000293 return;
294 }
295
Douglas Gregor6f526752010-12-16 08:48:57 +0000296 // Check for unexpanded parameter packs.
297 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
298 Param->setInvalidDecl();
299 return;
300 }
301
Anders Carlsson66e30672009-08-25 01:02:06 +0000302 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000303 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
304 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000305 Param->setInvalidDecl();
306 return;
307 }
Mike Stump1eb44332009-09-09 15:08:12 +0000308
John McCall9ae2f072010-08-23 23:25:46 +0000309 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000310}
311
Douglas Gregor61366e92008-12-24 00:01:03 +0000312/// ActOnParamUnparsedDefaultArgument - We've seen a default
313/// argument for a function parameter, but we can't parse it yet
314/// because we're inside a class definition. Note that this default
315/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000316void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000317 SourceLocation EqualLoc,
318 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000319 if (!param)
320 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000321
John McCalld226f652010-08-21 09:40:31 +0000322 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000323 if (Param)
324 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Anders Carlsson5e300d12009-06-12 16:51:40 +0000326 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000327}
328
Douglas Gregor72b505b2008-12-16 21:30:33 +0000329/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
330/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000331void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000332 if (!param)
333 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000334
John McCalld226f652010-08-21 09:40:31 +0000335 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Anders Carlsson5e300d12009-06-12 16:51:40 +0000337 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Anders Carlsson5e300d12009-06-12 16:51:40 +0000339 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000340}
341
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000342/// CheckExtraCXXDefaultArguments - Check for any extra default
343/// arguments in the declarator, which is not a function declaration
344/// or definition and therefore is not permitted to have default
345/// arguments. This routine should be invoked for every declarator
346/// that is not a function declaration or definition.
347void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
348 // C++ [dcl.fct.default]p3
349 // A default argument expression shall be specified only in the
350 // parameter-declaration-clause of a function declaration or in a
351 // template-parameter (14.1). It shall not be specified for a
352 // parameter pack. If it is specified in a
353 // parameter-declaration-clause, it shall not occur within a
354 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000355 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000356 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000357 DeclaratorChunk &chunk = D.getTypeObject(i);
358 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000359 if (MightBeFunction) {
360 // This is a function declaration. It can have default arguments, but
361 // keep looking in case its return type is a function type with default
362 // arguments.
363 MightBeFunction = false;
364 continue;
365 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000366 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
367 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000368 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000369 if (Param->hasUnparsedDefaultArg()) {
370 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000371 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000372 << SourceRange((*Toks)[1].getLocation(),
373 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000374 delete Toks;
375 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000376 } else if (Param->getDefaultArg()) {
377 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
378 << Param->getDefaultArg()->getSourceRange();
379 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000380 }
381 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000382 } else if (chunk.Kind != DeclaratorChunk::Paren) {
383 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000384 }
385 }
386}
387
Craig Topper1a6eac82012-09-21 04:33:26 +0000388/// MergeCXXFunctionDecl - Merge two declarations of the same C++
389/// function, once we already know that they have the same
390/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
391/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000392bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
393 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000394 bool Invalid = false;
395
Chris Lattner3d1cee32008-04-08 05:04:30 +0000396 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 // For non-template functions, default arguments can be added in
398 // later declarations of a function in the same
399 // scope. Declarations in different scopes have completely
400 // distinct sets of default arguments. That is, declarations in
401 // inner scopes do not acquire default arguments from
402 // declarations in outer scopes, and vice versa. In a given
403 // function declaration, all parameters subsequent to a
404 // parameter with a default argument shall have default
405 // arguments supplied in this or previous declarations. A
406 // default argument shall not be redefined by a later
407 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000408 //
409 // C++ [dcl.fct.default]p6:
410 // Except for member functions of class templates, the default arguments
411 // in a member function definition that appears outside of the class
412 // definition are added to the set of default arguments provided by the
413 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000414 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
415 ParmVarDecl *OldParam = Old->getParamDecl(p);
416 ParmVarDecl *NewParam = New->getParamDecl(p);
417
James Molloy9cda03f2012-03-13 08:55:35 +0000418 bool OldParamHasDfl = OldParam->hasDefaultArg();
419 bool NewParamHasDfl = NewParam->hasDefaultArg();
420
421 NamedDecl *ND = Old;
422 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
423 // Ignore default parameters of old decl if they are not in
424 // the same scope.
425 OldParamHasDfl = false;
426
427 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000428
Francois Pichet8d051e02011-04-10 03:03:52 +0000429 unsigned DiagDefaultParamID =
430 diag::err_param_default_argument_redefinition;
431
432 // MSVC accepts that default parameters be redefined for member functions
433 // of template class. The new default parameter's value is ignored.
434 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000435 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000436 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
437 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000438 // Merge the old default argument into the new parameter.
439 NewParam->setHasInheritedDefaultArg();
440 if (OldParam->hasUninstantiatedDefaultArg())
441 NewParam->setUninstantiatedDefaultArg(
442 OldParam->getUninstantiatedDefaultArg());
443 else
444 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000445 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000446 Invalid = false;
447 }
448 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000449
Francois Pichet8cf90492011-04-10 04:58:30 +0000450 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
451 // hint here. Alternatively, we could walk the type-source information
452 // for NewParam to find the last source location in the type... but it
453 // isn't worth the effort right now. This is the kind of test case that
454 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000455 // int f(int);
456 // void g(int (*fp)(int) = f);
457 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000458 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000459 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000460
461 // Look for the function declaration where the default argument was
462 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000463 for (FunctionDecl *Older = Old->getPreviousDecl();
464 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000465 if (!Older->getParamDecl(p)->hasDefaultArg())
466 break;
467
468 OldParam = Older->getParamDecl(p);
469 }
470
471 Diag(OldParam->getLocation(), diag::note_previous_definition)
472 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000473 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000474 // Merge the old default argument into the new parameter.
475 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000476 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000477 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000478 if (OldParam->hasUninstantiatedDefaultArg())
479 NewParam->setUninstantiatedDefaultArg(
480 OldParam->getUninstantiatedDefaultArg());
481 else
John McCall3d6c1782010-05-04 01:53:42 +0000482 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000483 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000484 if (New->getDescribedFunctionTemplate()) {
485 // Paragraph 4, quoted above, only applies to non-template functions.
486 Diag(NewParam->getLocation(),
487 diag::err_param_default_argument_template_redecl)
488 << NewParam->getDefaultArgRange();
489 Diag(Old->getLocation(), diag::note_template_prev_declaration)
490 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000491 } else if (New->getTemplateSpecializationKind()
492 != TSK_ImplicitInstantiation &&
493 New->getTemplateSpecializationKind() != TSK_Undeclared) {
494 // C++ [temp.expr.spec]p21:
495 // Default function arguments shall not be specified in a declaration
496 // or a definition for one of the following explicit specializations:
497 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000498 // - the explicit specialization of a member function template;
499 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000500 // template where the class template specialization to which the
501 // member function specialization belongs is implicitly
502 // instantiated.
503 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
504 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
505 << New->getDeclName()
506 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000507 } else if (New->getDeclContext()->isDependentContext()) {
508 // C++ [dcl.fct.default]p6 (DR217):
509 // Default arguments for a member function of a class template shall
510 // be specified on the initial declaration of the member function
511 // within the class template.
512 //
513 // Reading the tea leaves a bit in DR217 and its reference to DR205
514 // leads me to the conclusion that one cannot add default function
515 // arguments for an out-of-line definition of a member function of a
516 // dependent type.
517 int WhichKind = 2;
518 if (CXXRecordDecl *Record
519 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
520 if (Record->getDescribedClassTemplate())
521 WhichKind = 0;
522 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
523 WhichKind = 1;
524 else
525 WhichKind = 2;
526 }
527
528 Diag(NewParam->getLocation(),
529 diag::err_param_default_argument_member_template_redecl)
530 << WhichKind
531 << NewParam->getDefaultArgRange();
532 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000533 }
534 }
535
Richard Smithb8abff62012-11-28 03:45:24 +0000536 // DR1344: If a default argument is added outside a class definition and that
537 // default argument makes the function a special member function, the program
538 // is ill-formed. This can only happen for constructors.
539 if (isa<CXXConstructorDecl>(New) &&
540 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
541 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
542 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
543 if (NewSM != OldSM) {
544 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
545 assert(NewParam->hasDefaultArg());
546 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
547 << NewParam->getDefaultArgRange() << NewSM;
548 Diag(Old->getLocation(), diag::note_previous_declaration);
549 }
550 }
551
Richard Smithff234882012-02-20 23:28:05 +0000552 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000553 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000554 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000555 if (New->isConstexpr() != Old->isConstexpr()) {
556 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
557 << New << New->isConstexpr();
558 Diag(Old->getLocation(), diag::note_previous_declaration);
559 Invalid = true;
560 }
561
Douglas Gregore13ad832010-02-12 07:32:17 +0000562 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000563 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000564
Douglas Gregorcda9c672009-02-16 17:45:42 +0000565 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000566}
567
Sebastian Redl60618fa2011-03-12 11:50:43 +0000568/// \brief Merge the exception specifications of two variable declarations.
569///
570/// This is called when there's a redeclaration of a VarDecl. The function
571/// checks if the redeclaration might have an exception specification and
572/// validates compatibility and merges the specs if necessary.
573void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
574 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000575 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000576 return;
577
578 assert(Context.hasSameType(New->getType(), Old->getType()) &&
579 "Should only be called if types are otherwise the same.");
580
581 QualType NewType = New->getType();
582 QualType OldType = Old->getType();
583
584 // We're only interested in pointers and references to functions, as well
585 // as pointers to member functions.
586 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
587 NewType = R->getPointeeType();
588 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
589 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
590 NewType = P->getPointeeType();
591 OldType = OldType->getAs<PointerType>()->getPointeeType();
592 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
593 NewType = M->getPointeeType();
594 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
595 }
596
597 if (!NewType->isFunctionProtoType())
598 return;
599
600 // There's lots of special cases for functions. For function pointers, system
601 // libraries are hopefully not as broken so that we don't need these
602 // workarounds.
603 if (CheckEquivalentExceptionSpec(
604 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
605 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
606 New->setInvalidDecl();
607 }
608}
609
Chris Lattner3d1cee32008-04-08 05:04:30 +0000610/// CheckCXXDefaultArguments - Verify that the default arguments for a
611/// function declaration are well-formed according to C++
612/// [dcl.fct.default].
613void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
614 unsigned NumParams = FD->getNumParams();
615 unsigned p;
616
Douglas Gregorc6889e72012-02-14 22:28:59 +0000617 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
618 isa<CXXMethodDecl>(FD) &&
619 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
620
Chris Lattner3d1cee32008-04-08 05:04:30 +0000621 // Find first parameter with a default argument
622 for (p = 0; p < NumParams; ++p) {
623 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000624 if (Param->hasDefaultArg()) {
625 // C++11 [expr.prim.lambda]p5:
626 // [...] Default arguments (8.3.6) shall not be specified in the
627 // parameter-declaration-clause of a lambda-declarator.
628 //
629 // FIXME: Core issue 974 strikes this sentence, we only provide an
630 // extension warning.
631 if (IsLambda)
632 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
633 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000634 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000635 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000636 }
637
638 // C++ [dcl.fct.default]p4:
639 // In a given function declaration, all parameters
640 // subsequent to a parameter with a default argument shall
641 // have default arguments supplied in this or previous
642 // declarations. A default argument shall not be redefined
643 // by a later declaration (not even to the same value).
644 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000645 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000646 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000647 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000648 if (Param->isInvalidDecl())
649 /* We already complained about this parameter. */;
650 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000651 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000652 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000653 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000654 else
Mike Stump1eb44332009-09-09 15:08:12 +0000655 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000656 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Chris Lattner3d1cee32008-04-08 05:04:30 +0000658 LastMissingDefaultArg = p;
659 }
660 }
661
662 if (LastMissingDefaultArg > 0) {
663 // Some default arguments were missing. Clear out all of the
664 // default arguments up to (and including) the last missing
665 // default argument, so that we leave the function parameters
666 // in a semantically valid state.
667 for (p = 0; p <= LastMissingDefaultArg; ++p) {
668 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000669 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000670 Param->setDefaultArg(0);
671 }
672 }
673 }
674}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000675
Richard Smith9f569cc2011-10-01 02:31:28 +0000676// CheckConstexprParameterTypes - Check whether a function's parameter types
677// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000678// diagnostic and return false.
679static bool CheckConstexprParameterTypes(Sema &SemaRef,
680 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000681 unsigned ArgIndex = 0;
682 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
683 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
684 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
685 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
686 SourceLocation ParamLoc = PD->getLocation();
687 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000688 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000689 diag::err_constexpr_non_literal_param,
690 ArgIndex+1, PD->getSourceRange(),
691 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000692 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000693 }
Joao Matos17d35c32012-08-31 22:18:20 +0000694 return true;
695}
696
697/// \brief Get diagnostic %select index for tag kind for
698/// record diagnostic message.
699/// WARNING: Indexes apply to particular diagnostics only!
700///
701/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000702static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000703 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000704 case TTK_Struct: return 0;
705 case TTK_Interface: return 1;
706 case TTK_Class: return 2;
707 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000708 }
Joao Matos17d35c32012-08-31 22:18:20 +0000709}
710
711// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
712// the requirements of a constexpr function definition or a constexpr
713// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000714// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000715//
Richard Smith86c3ae42012-02-13 03:54:03 +0000716// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
717bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000718 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
719 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000720 // C++11 [dcl.constexpr]p4:
721 // The definition of a constexpr constructor shall satisfy the following
722 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000723 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000724 const CXXRecordDecl *RD = MD->getParent();
725 if (RD->getNumVBases()) {
726 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
727 << isa<CXXConstructorDecl>(NewFD)
728 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
729 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
730 E = RD->vbases_end(); I != E; ++I)
731 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000732 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000733 return false;
734 }
Richard Smith35340502012-01-13 04:54:00 +0000735 }
736
737 if (!isa<CXXConstructorDecl>(NewFD)) {
738 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000739 // The definition of a constexpr function shall satisfy the following
740 // constraints:
741 // - it shall not be virtual;
742 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
743 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000744 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000745
Richard Smith86c3ae42012-02-13 03:54:03 +0000746 // If it's not obvious why this function is virtual, find an overridden
747 // function which uses the 'virtual' keyword.
748 const CXXMethodDecl *WrittenVirtual = Method;
749 while (!WrittenVirtual->isVirtualAsWritten())
750 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
751 if (WrittenVirtual != Method)
752 Diag(WrittenVirtual->getLocation(),
753 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000754 return false;
755 }
756
757 // - its return type shall be a literal type;
758 QualType RT = NewFD->getResultType();
759 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000760 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000761 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000762 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000763 }
764
Richard Smith35340502012-01-13 04:54:00 +0000765 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000766 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000767 return false;
768
Richard Smith9f569cc2011-10-01 02:31:28 +0000769 return true;
770}
771
772/// Check the given declaration statement is legal within a constexpr function
773/// body. C++0x [dcl.constexpr]p3,p4.
774///
775/// \return true if the body is OK, false if we have diagnosed a problem.
776static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
777 DeclStmt *DS) {
778 // C++0x [dcl.constexpr]p3 and p4:
779 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
780 // contain only
781 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
782 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
783 switch ((*DclIt)->getKind()) {
784 case Decl::StaticAssert:
785 case Decl::Using:
786 case Decl::UsingShadow:
787 case Decl::UsingDirective:
788 case Decl::UnresolvedUsingTypename:
789 // - static_assert-declarations
790 // - using-declarations,
791 // - using-directives,
792 continue;
793
794 case Decl::Typedef:
795 case Decl::TypeAlias: {
796 // - typedef declarations and alias-declarations that do not define
797 // classes or enumerations,
798 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
799 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
800 // Don't allow variably-modified types in constexpr functions.
801 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
802 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
803 << TL.getSourceRange() << TL.getType()
804 << isa<CXXConstructorDecl>(Dcl);
805 return false;
806 }
807 continue;
808 }
809
810 case Decl::Enum:
811 case Decl::CXXRecord:
812 // As an extension, we allow the declaration (but not the definition) of
813 // classes and enumerations in all declarations, not just in typedef and
814 // alias declarations.
815 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
816 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
817 << isa<CXXConstructorDecl>(Dcl);
818 return false;
819 }
820 continue;
821
822 case Decl::Var:
823 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
824 << isa<CXXConstructorDecl>(Dcl);
825 return false;
826
827 default:
828 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
829 << isa<CXXConstructorDecl>(Dcl);
830 return false;
831 }
832 }
833
834 return true;
835}
836
837/// Check that the given field is initialized within a constexpr constructor.
838///
839/// \param Dcl The constexpr constructor being checked.
840/// \param Field The field being checked. This may be a member of an anonymous
841/// struct or union nested within the class being checked.
842/// \param Inits All declarations, including anonymous struct/union members and
843/// indirect members, for which any initialization was provided.
844/// \param Diagnosed Set to true if an error is produced.
845static void CheckConstexprCtorInitializer(Sema &SemaRef,
846 const FunctionDecl *Dcl,
847 FieldDecl *Field,
848 llvm::SmallSet<Decl*, 16> &Inits,
849 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000850 if (Field->isUnnamedBitfield())
851 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000852
853 if (Field->isAnonymousStructOrUnion() &&
854 Field->getType()->getAsCXXRecordDecl()->isEmpty())
855 return;
856
Richard Smith9f569cc2011-10-01 02:31:28 +0000857 if (!Inits.count(Field)) {
858 if (!Diagnosed) {
859 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
860 Diagnosed = true;
861 }
862 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
863 } else if (Field->isAnonymousStructOrUnion()) {
864 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
865 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
866 I != E; ++I)
867 // If an anonymous union contains an anonymous struct of which any member
868 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000869 if (!RD->isUnion() || Inits.count(*I))
870 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000871 }
872}
873
874/// Check the body for the given constexpr function declaration only contains
875/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
876///
877/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000878bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000879 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000880 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000881 // The definition of a constexpr function shall satisfy the following
882 // constraints: [...]
883 // - its function-body shall be = delete, = default, or a
884 // compound-statement
885 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000886 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000887 // In the definition of a constexpr constructor, [...]
888 // - its function-body shall not be a function-try-block;
889 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
890 << isa<CXXConstructorDecl>(Dcl);
891 return false;
892 }
893
894 // - its function-body shall be [...] a compound-statement that contains only
895 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
896
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000897 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smith9f569cc2011-10-01 02:31:28 +0000898 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
899 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
900 switch ((*BodyIt)->getStmtClass()) {
901 case Stmt::NullStmtClass:
902 // - null statements,
903 continue;
904
905 case Stmt::DeclStmtClass:
906 // - static_assert-declarations
907 // - using-declarations,
908 // - using-directives,
909 // - typedef declarations and alias-declarations that do not define
910 // classes or enumerations,
911 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
912 return false;
913 continue;
914
915 case Stmt::ReturnStmtClass:
916 // - and exactly one return statement;
917 if (isa<CXXConstructorDecl>(Dcl))
918 break;
919
920 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000921 continue;
922
923 default:
924 break;
925 }
926
927 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
928 << isa<CXXConstructorDecl>(Dcl);
929 return false;
930 }
931
932 if (const CXXConstructorDecl *Constructor
933 = dyn_cast<CXXConstructorDecl>(Dcl)) {
934 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000935 // DR1359:
936 // - every non-variant non-static data member and base class sub-object
937 // shall be initialized;
938 // - if the class is a non-empty union, or for each non-empty anonymous
939 // union member of a non-union class, exactly one non-static data member
940 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000941 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000942 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000943 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
944 return false;
945 }
Richard Smith6e433752011-10-10 16:38:04 +0000946 } else if (!Constructor->isDependentContext() &&
947 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000948 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
949
950 // Skip detailed checking if we have enough initializers, and we would
951 // allow at most one initializer per member.
952 bool AnyAnonStructUnionMembers = false;
953 unsigned Fields = 0;
954 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
955 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000956 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000957 AnyAnonStructUnionMembers = true;
958 break;
959 }
960 }
961 if (AnyAnonStructUnionMembers ||
962 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
963 // Check initialization of non-static data members. Base classes are
964 // always initialized so do not need to be checked. Dependent bases
965 // might not have initializers in the member initializer list.
966 llvm::SmallSet<Decl*, 16> Inits;
967 for (CXXConstructorDecl::init_const_iterator
968 I = Constructor->init_begin(), E = Constructor->init_end();
969 I != E; ++I) {
970 if (FieldDecl *FD = (*I)->getMember())
971 Inits.insert(FD);
972 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
973 Inits.insert(ID->chain_begin(), ID->chain_end());
974 }
975
976 bool Diagnosed = false;
977 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
978 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000979 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000980 if (Diagnosed)
981 return false;
982 }
983 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000984 } else {
985 if (ReturnStmts.empty()) {
986 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
987 return false;
988 }
989 if (ReturnStmts.size() > 1) {
990 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
991 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
992 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
993 return false;
994 }
995 }
996
Richard Smith5ba73e12012-02-04 00:33:54 +0000997 // C++11 [dcl.constexpr]p5:
998 // if no function argument values exist such that the function invocation
999 // substitution would produce a constant expression, the program is
1000 // ill-formed; no diagnostic required.
1001 // C++11 [dcl.constexpr]p3:
1002 // - every constructor call and implicit conversion used in initializing the
1003 // return value shall be one of those allowed in a constant expression.
1004 // C++11 [dcl.constexpr]p4:
1005 // - every constructor involved in initializing non-static data members and
1006 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001007 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001008 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001009 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001010 << isa<CXXConstructorDecl>(Dcl);
1011 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1012 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001013 // Don't return false here: we allow this for compatibility in
1014 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001015 }
1016
Richard Smith9f569cc2011-10-01 02:31:28 +00001017 return true;
1018}
1019
Douglas Gregorb48fe382008-10-31 09:07:45 +00001020/// isCurrentClassName - Determine whether the identifier II is the
1021/// name of the class type currently being defined. In the case of
1022/// nested classes, this will only return true if II is the name of
1023/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001024bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1025 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001026 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001027
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001028 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001029 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001030 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001031 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1032 } else
1033 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1034
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001035 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001036 return &II == CurDecl->getIdentifier();
1037 else
1038 return false;
1039}
1040
Douglas Gregor229d47a2012-11-10 07:24:09 +00001041/// \brief Determine whether the given class is a base class of the given
1042/// class, including looking at dependent bases.
1043static bool findCircularInheritance(const CXXRecordDecl *Class,
1044 const CXXRecordDecl *Current) {
1045 SmallVector<const CXXRecordDecl*, 8> Queue;
1046
1047 Class = Class->getCanonicalDecl();
1048 while (true) {
1049 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1050 E = Current->bases_end();
1051 I != E; ++I) {
1052 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1053 if (!Base)
1054 continue;
1055
1056 Base = Base->getDefinition();
1057 if (!Base)
1058 continue;
1059
1060 if (Base->getCanonicalDecl() == Class)
1061 return true;
1062
1063 Queue.push_back(Base);
1064 }
1065
1066 if (Queue.empty())
1067 return false;
1068
1069 Current = Queue.back();
1070 Queue.pop_back();
1071 }
1072
1073 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001074}
1075
Mike Stump1eb44332009-09-09 15:08:12 +00001076/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001077///
1078/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1079/// and returns NULL otherwise.
1080CXXBaseSpecifier *
1081Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1082 SourceRange SpecifierRange,
1083 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001084 TypeSourceInfo *TInfo,
1085 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001086 QualType BaseType = TInfo->getType();
1087
Douglas Gregor2943aed2009-03-03 04:44:36 +00001088 // C++ [class.union]p1:
1089 // A union shall not have base classes.
1090 if (Class->isUnion()) {
1091 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1092 << SpecifierRange;
1093 return 0;
1094 }
1095
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001096 if (EllipsisLoc.isValid() &&
1097 !TInfo->getType()->containsUnexpandedParameterPack()) {
1098 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1099 << TInfo->getTypeLoc().getSourceRange();
1100 EllipsisLoc = SourceLocation();
1101 }
Douglas Gregord777e282012-11-10 01:18:17 +00001102
1103 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1104
1105 if (BaseType->isDependentType()) {
1106 // Make sure that we don't have circular inheritance among our dependent
1107 // bases. For non-dependent bases, the check for completeness below handles
1108 // this.
1109 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1110 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1111 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001112 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001113 Diag(BaseLoc, diag::err_circular_inheritance)
1114 << BaseType << Context.getTypeDeclType(Class);
1115
1116 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1117 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1118 << BaseType;
1119
1120 return 0;
1121 }
1122 }
1123
Mike Stump1eb44332009-09-09 15:08:12 +00001124 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001125 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001126 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001127 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001128
1129 // Base specifiers must be record types.
1130 if (!BaseType->isRecordType()) {
1131 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1132 return 0;
1133 }
1134
1135 // C++ [class.union]p1:
1136 // A union shall not be used as a base class.
1137 if (BaseType->isUnionType()) {
1138 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1139 return 0;
1140 }
1141
1142 // C++ [class.derived]p2:
1143 // The class-name in a base-specifier shall not be an incompletely
1144 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001145 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001146 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001147 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001148 return 0;
John McCall572fc622010-08-17 07:23:57 +00001149 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001150
Eli Friedman1d954f62009-08-15 21:55:26 +00001151 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001152 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001153 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001154 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001155 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001156 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1157 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001158
Anders Carlsson1d209272011-03-25 14:55:14 +00001159 // C++ [class]p3:
1160 // If a class is marked final and it appears as a base-type-specifier in
1161 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001162 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001163 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1164 << CXXBaseDecl->getDeclName();
1165 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1166 << CXXBaseDecl->getDeclName();
1167 return 0;
1168 }
1169
John McCall572fc622010-08-17 07:23:57 +00001170 if (BaseDecl->isInvalidDecl())
1171 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001172
1173 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001174 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001175 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001176 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001177}
1178
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001179/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1180/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001181/// example:
1182/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001183/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001184BaseResult
John McCalld226f652010-08-21 09:40:31 +00001185Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001186 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001187 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001188 ParsedType basetype, SourceLocation BaseLoc,
1189 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001190 if (!classdecl)
1191 return true;
1192
Douglas Gregor40808ce2009-03-09 23:48:35 +00001193 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001194 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001195 if (!Class)
1196 return true;
1197
Richard Smith05321402013-02-19 23:47:15 +00001198 // We do not support any C++11 attributes on base-specifiers yet.
1199 // Diagnose any attributes we see.
1200 if (!Attributes.empty()) {
1201 for (AttributeList *Attr = Attributes.getList(); Attr;
1202 Attr = Attr->getNext()) {
1203 if (Attr->isInvalid() ||
1204 Attr->getKind() == AttributeList::IgnoredAttribute)
1205 continue;
1206 Diag(Attr->getLoc(),
1207 Attr->getKind() == AttributeList::UnknownAttribute
1208 ? diag::warn_unknown_attribute_ignored
1209 : diag::err_base_specifier_attribute)
1210 << Attr->getName();
1211 }
1212 }
1213
Nick Lewycky56062202010-07-26 16:56:01 +00001214 TypeSourceInfo *TInfo = 0;
1215 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001216
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001217 if (EllipsisLoc.isInvalid() &&
1218 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001219 UPPC_BaseType))
1220 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001221
Douglas Gregor2943aed2009-03-03 04:44:36 +00001222 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001223 Virtual, Access, TInfo,
1224 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001225 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001226 else
1227 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Douglas Gregor2943aed2009-03-03 04:44:36 +00001229 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001230}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001231
Douglas Gregor2943aed2009-03-03 04:44:36 +00001232/// \brief Performs the actual work of attaching the given base class
1233/// specifiers to a C++ class.
1234bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1235 unsigned NumBases) {
1236 if (NumBases == 0)
1237 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001238
1239 // Used to keep track of which base types we have already seen, so
1240 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001241 // that the key is always the unqualified canonical type of the base
1242 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001243 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1244
1245 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001246 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001247 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001248 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001249 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001250 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001251 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001252
1253 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1254 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001255 // C++ [class.mi]p3:
1256 // A class shall not be specified as a direct base class of a
1257 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001258 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001259 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001260 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001261 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001262
1263 // Delete the duplicate base class specifier; we're going to
1264 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001265 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001266
1267 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001268 } else {
1269 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001270 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001271 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001272 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1273 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1274 if (Class->isInterface() &&
1275 (!RD->isInterface() ||
1276 KnownBase->getAccessSpecifier() != AS_public)) {
1277 // The Microsoft extension __interface does not permit bases that
1278 // are not themselves public interfaces.
1279 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1280 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1281 << RD->getSourceRange();
1282 Invalid = true;
1283 }
1284 if (RD->hasAttr<WeakAttr>())
1285 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1286 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001287 }
1288 }
1289
1290 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001291 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001292
1293 // Delete the remaining (good) base class specifiers, since their
1294 // data has been copied into the CXXRecordDecl.
1295 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001296 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001297
1298 return Invalid;
1299}
1300
1301/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1302/// class, after checking whether there are any duplicate base
1303/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001304void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001305 unsigned NumBases) {
1306 if (!ClassDecl || !Bases || !NumBases)
1307 return;
1308
1309 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001310 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001311 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001312}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001313
John McCall3cb0ebd2010-03-10 03:28:59 +00001314static CXXRecordDecl *GetClassForType(QualType T) {
1315 if (const RecordType *RT = T->getAs<RecordType>())
1316 return cast<CXXRecordDecl>(RT->getDecl());
1317 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1318 return ICT->getDecl();
1319 else
1320 return 0;
1321}
1322
Douglas Gregora8f32e02009-10-06 17:59:45 +00001323/// \brief Determine whether the type \p Derived is a C++ class that is
1324/// derived from the type \p Base.
1325bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001326 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001327 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001328
1329 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1330 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001331 return false;
1332
John McCall3cb0ebd2010-03-10 03:28:59 +00001333 CXXRecordDecl *BaseRD = GetClassForType(Base);
1334 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001335 return false;
1336
John McCall86ff3082010-02-04 22:26:26 +00001337 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1338 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001339}
1340
1341/// \brief Determine whether the type \p Derived is a C++ class that is
1342/// derived from the type \p Base.
1343bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001344 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001345 return false;
1346
John McCall3cb0ebd2010-03-10 03:28:59 +00001347 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1348 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001349 return false;
1350
John McCall3cb0ebd2010-03-10 03:28:59 +00001351 CXXRecordDecl *BaseRD = GetClassForType(Base);
1352 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001353 return false;
1354
Douglas Gregora8f32e02009-10-06 17:59:45 +00001355 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1356}
1357
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001358void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001359 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001360 assert(BasePathArray.empty() && "Base path array must be empty!");
1361 assert(Paths.isRecordingPaths() && "Must record paths!");
1362
1363 const CXXBasePath &Path = Paths.front();
1364
1365 // We first go backward and check if we have a virtual base.
1366 // FIXME: It would be better if CXXBasePath had the base specifier for
1367 // the nearest virtual base.
1368 unsigned Start = 0;
1369 for (unsigned I = Path.size(); I != 0; --I) {
1370 if (Path[I - 1].Base->isVirtual()) {
1371 Start = I - 1;
1372 break;
1373 }
1374 }
1375
1376 // Now add all bases.
1377 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001378 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001379}
1380
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001381/// \brief Determine whether the given base path includes a virtual
1382/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001383bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1384 for (CXXCastPath::const_iterator B = BasePath.begin(),
1385 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001386 B != BEnd; ++B)
1387 if ((*B)->isVirtual())
1388 return true;
1389
1390 return false;
1391}
1392
Douglas Gregora8f32e02009-10-06 17:59:45 +00001393/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1394/// conversion (where Derived and Base are class types) is
1395/// well-formed, meaning that the conversion is unambiguous (and
1396/// that all of the base classes are accessible). Returns true
1397/// and emits a diagnostic if the code is ill-formed, returns false
1398/// otherwise. Loc is the location where this routine should point to
1399/// if there is an error, and Range is the source range to highlight
1400/// if there is an error.
1401bool
1402Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001403 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001404 unsigned AmbigiousBaseConvID,
1405 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001406 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001407 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001408 // First, determine whether the path from Derived to Base is
1409 // ambiguous. This is slightly more expensive than checking whether
1410 // the Derived to Base conversion exists, because here we need to
1411 // explore multiple paths to determine if there is an ambiguity.
1412 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1413 /*DetectVirtual=*/false);
1414 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1415 assert(DerivationOkay &&
1416 "Can only be used with a derived-to-base conversion");
1417 (void)DerivationOkay;
1418
1419 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001420 if (InaccessibleBaseID) {
1421 // Check that the base class can be accessed.
1422 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1423 InaccessibleBaseID)) {
1424 case AR_inaccessible:
1425 return true;
1426 case AR_accessible:
1427 case AR_dependent:
1428 case AR_delayed:
1429 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001430 }
John McCall6b2accb2010-02-10 09:31:12 +00001431 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001432
1433 // Build a base path if necessary.
1434 if (BasePath)
1435 BuildBasePathArray(Paths, *BasePath);
1436 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001437 }
1438
1439 // We know that the derived-to-base conversion is ambiguous, and
1440 // we're going to produce a diagnostic. Perform the derived-to-base
1441 // search just one more time to compute all of the possible paths so
1442 // that we can print them out. This is more expensive than any of
1443 // the previous derived-to-base checks we've done, but at this point
1444 // performance isn't as much of an issue.
1445 Paths.clear();
1446 Paths.setRecordingPaths(true);
1447 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1448 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1449 (void)StillOkay;
1450
1451 // Build up a textual representation of the ambiguous paths, e.g.,
1452 // D -> B -> A, that will be used to illustrate the ambiguous
1453 // conversions in the diagnostic. We only print one of the paths
1454 // to each base class subobject.
1455 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1456
1457 Diag(Loc, AmbigiousBaseConvID)
1458 << Derived << Base << PathDisplayStr << Range << Name;
1459 return true;
1460}
1461
1462bool
1463Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001464 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001465 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001466 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001467 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001468 IgnoreAccess ? 0
1469 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001470 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001471 Loc, Range, DeclarationName(),
1472 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001473}
1474
1475
1476/// @brief Builds a string representing ambiguous paths from a
1477/// specific derived class to different subobjects of the same base
1478/// class.
1479///
1480/// This function builds a string that can be used in error messages
1481/// to show the different paths that one can take through the
1482/// inheritance hierarchy to go from the derived class to different
1483/// subobjects of a base class. The result looks something like this:
1484/// @code
1485/// struct D -> struct B -> struct A
1486/// struct D -> struct C -> struct A
1487/// @endcode
1488std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1489 std::string PathDisplayStr;
1490 std::set<unsigned> DisplayedPaths;
1491 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1492 Path != Paths.end(); ++Path) {
1493 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1494 // We haven't displayed a path to this particular base
1495 // class subobject yet.
1496 PathDisplayStr += "\n ";
1497 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1498 for (CXXBasePath::const_iterator Element = Path->begin();
1499 Element != Path->end(); ++Element)
1500 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1501 }
1502 }
1503
1504 return PathDisplayStr;
1505}
1506
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001507//===----------------------------------------------------------------------===//
1508// C++ class member Handling
1509//===----------------------------------------------------------------------===//
1510
Abramo Bagnara6206d532010-06-05 05:09:32 +00001511/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001512bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1513 SourceLocation ASLoc,
1514 SourceLocation ColonLoc,
1515 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001516 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001517 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001518 ASLoc, ColonLoc);
1519 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001520 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001521}
1522
Richard Smitha4b39652012-08-06 03:25:17 +00001523/// CheckOverrideControl - Check C++11 override control semantics.
1524void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001525 if (D->isInvalidDecl())
1526 return;
1527
Chris Lattner5f9e2722011-07-23 10:55:15 +00001528 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001529
Richard Smitha4b39652012-08-06 03:25:17 +00001530 // Do we know which functions this declaration might be overriding?
1531 bool OverridesAreKnown = !MD ||
1532 (!MD->getParent()->hasAnyDependentBases() &&
1533 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001534
Richard Smitha4b39652012-08-06 03:25:17 +00001535 if (!MD || !MD->isVirtual()) {
1536 if (OverridesAreKnown) {
1537 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1538 Diag(OA->getLocation(),
1539 diag::override_keyword_only_allowed_on_virtual_member_functions)
1540 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1541 D->dropAttr<OverrideAttr>();
1542 }
1543 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1544 Diag(FA->getLocation(),
1545 diag::override_keyword_only_allowed_on_virtual_member_functions)
1546 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1547 D->dropAttr<FinalAttr>();
1548 }
1549 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001550 return;
1551 }
Richard Smitha4b39652012-08-06 03:25:17 +00001552
1553 if (!OverridesAreKnown)
1554 return;
1555
1556 // C++11 [class.virtual]p5:
1557 // If a virtual function is marked with the virt-specifier override and
1558 // does not override a member function of a base class, the program is
1559 // ill-formed.
1560 bool HasOverriddenMethods =
1561 MD->begin_overridden_methods() != MD->end_overridden_methods();
1562 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1563 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1564 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001565}
1566
Richard Smitha4b39652012-08-06 03:25:17 +00001567/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001568/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001569/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001570bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1571 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001572 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001573 return false;
1574
1575 Diag(New->getLocation(), diag::err_final_function_overridden)
1576 << New->getDeclName();
1577 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1578 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001579}
1580
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001581static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001582 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1583 // FIXME: Destruction of ObjC lifetime types has side-effects.
1584 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1585 return !RD->isCompleteDefinition() ||
1586 !RD->hasTrivialDefaultConstructor() ||
1587 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001588 return false;
1589}
1590
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001591/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1592/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001593/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001594/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1595/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001596NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001597Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001598 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001599 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001600 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001601 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001602 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1603 DeclarationName Name = NameInfo.getName();
1604 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001605
1606 // For anonymous bitfields, the location should point to the type.
1607 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001608 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001609
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001610 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001611
John McCall4bde1e12010-06-04 08:34:12 +00001612 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001613 assert(!DS.isFriendSpecified());
1614
Richard Smith1ab0d902011-06-25 02:28:38 +00001615 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001616
John McCalle402e722012-09-25 07:32:39 +00001617 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1618 // The Microsoft extension __interface only permits public member functions
1619 // and prohibits constructors, destructors, operators, non-public member
1620 // functions, static methods and data members.
1621 unsigned InvalidDecl;
1622 bool ShowDeclName = true;
1623 if (!isFunc)
1624 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1625 else if (AS != AS_public)
1626 InvalidDecl = 2;
1627 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1628 InvalidDecl = 3;
1629 else switch (Name.getNameKind()) {
1630 case DeclarationName::CXXConstructorName:
1631 InvalidDecl = 4;
1632 ShowDeclName = false;
1633 break;
1634
1635 case DeclarationName::CXXDestructorName:
1636 InvalidDecl = 5;
1637 ShowDeclName = false;
1638 break;
1639
1640 case DeclarationName::CXXOperatorName:
1641 case DeclarationName::CXXConversionFunctionName:
1642 InvalidDecl = 6;
1643 break;
1644
1645 default:
1646 InvalidDecl = 0;
1647 break;
1648 }
1649
1650 if (InvalidDecl) {
1651 if (ShowDeclName)
1652 Diag(Loc, diag::err_invalid_member_in_interface)
1653 << (InvalidDecl-1) << Name;
1654 else
1655 Diag(Loc, diag::err_invalid_member_in_interface)
1656 << (InvalidDecl-1) << "";
1657 return 0;
1658 }
1659 }
1660
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001661 // C++ 9.2p6: A member shall not be declared to have automatic storage
1662 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001663 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1664 // data members and cannot be applied to names declared const or static,
1665 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001666 switch (DS.getStorageClassSpec()) {
1667 case DeclSpec::SCS_unspecified:
1668 case DeclSpec::SCS_typedef:
1669 case DeclSpec::SCS_static:
1670 // FALL THROUGH.
1671 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001672 case DeclSpec::SCS_mutable:
1673 if (isFunc) {
1674 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001675 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001676 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001677 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Sebastian Redla11f42f2008-11-17 23:24:37 +00001679 // FIXME: It would be nicer if the keyword was ignored only for this
1680 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001681 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001682 }
1683 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001684 default:
1685 if (DS.getStorageClassSpecLoc().isValid())
1686 Diag(DS.getStorageClassSpecLoc(),
1687 diag::err_storageclass_invalid_for_member);
1688 else
1689 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1690 D.getMutableDeclSpec().ClearStorageClassSpecs();
1691 }
1692
Sebastian Redl669d5d72008-11-14 23:42:31 +00001693 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1694 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001695 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001696
David Blaikie1d87fba2013-01-30 01:22:18 +00001697 if (DS.isConstexprSpecified() && isInstField) {
1698 SemaDiagnosticBuilder B =
1699 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1700 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1701 if (InitStyle == ICIS_NoInit) {
1702 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1703 D.getMutableDeclSpec().ClearConstexprSpec();
1704 const char *PrevSpec;
1705 unsigned DiagID;
1706 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1707 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001708 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001709 assert(!Failed && "Making a constexpr member const shouldn't fail");
1710 } else {
1711 B << 1;
1712 const char *PrevSpec;
1713 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001714 if (D.getMutableDeclSpec().SetStorageClassSpec(
1715 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001716 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001717 "This is the only DeclSpec that should fail to be applied");
1718 B << 1;
1719 } else {
1720 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1721 isInstField = false;
1722 }
1723 }
1724 }
1725
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001726 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001727 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001728 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001729
1730 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001731 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001732 Diag(Loc, diag::err_bad_variable_name)
1733 << Name;
1734 return 0;
1735 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001736
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001737 IdentifierInfo *II = Name.getAsIdentifierInfo();
1738
Douglas Gregorf2503652011-09-21 14:40:46 +00001739 // Member field could not be with "template" keyword.
1740 // So TemplateParameterLists should be empty in this case.
1741 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001742 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001743 if (TemplateParams->size()) {
1744 // There is no such thing as a member field template.
1745 Diag(D.getIdentifierLoc(), diag::err_template_member)
1746 << II
1747 << SourceRange(TemplateParams->getTemplateLoc(),
1748 TemplateParams->getRAngleLoc());
1749 } else {
1750 // There is an extraneous 'template<>' for this member.
1751 Diag(TemplateParams->getTemplateLoc(),
1752 diag::err_template_member_noparams)
1753 << II
1754 << SourceRange(TemplateParams->getTemplateLoc(),
1755 TemplateParams->getRAngleLoc());
1756 }
1757 return 0;
1758 }
1759
Douglas Gregor922fff22010-10-13 22:19:53 +00001760 if (SS.isSet() && !SS.isInvalid()) {
1761 // The user provided a superfluous scope specifier inside a class
1762 // definition:
1763 //
1764 // class X {
1765 // int X::member;
1766 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001767 if (DeclContext *DC = computeDeclContext(SS, false))
1768 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001769 else
1770 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1771 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001772
Douglas Gregor922fff22010-10-13 22:19:53 +00001773 SS.clear();
1774 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001775
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001776 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001777 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001778 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001779 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001780 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001781
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001782 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001783 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001784 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001785 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001786
1787 // Non-instance-fields can't have a bitfield.
1788 if (BitWidth) {
1789 if (Member->isInvalidDecl()) {
1790 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001791 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001792 // C++ 9.6p3: A bit-field shall not be a static member.
1793 // "static member 'A' cannot be a bit-field"
1794 Diag(Loc, diag::err_static_not_bitfield)
1795 << Name << BitWidth->getSourceRange();
1796 } else if (isa<TypedefDecl>(Member)) {
1797 // "typedef member 'x' cannot be a bit-field"
1798 Diag(Loc, diag::err_typedef_not_bitfield)
1799 << Name << BitWidth->getSourceRange();
1800 } else {
1801 // A function typedef ("typedef int f(); f a;").
1802 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1803 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001804 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001805 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001806 }
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Chris Lattner8b963ef2009-03-05 23:01:03 +00001808 BitWidth = 0;
1809 Member->setInvalidDecl();
1810 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001811
1812 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Douglas Gregor37b372b2009-08-20 22:52:58 +00001814 // If we have declared a member function template, set the access of the
1815 // templated declaration as well.
1816 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1817 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001818 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001819
Richard Smitha4b39652012-08-06 03:25:17 +00001820 if (VS.isOverrideSpecified())
1821 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1822 if (VS.isFinalSpecified())
1823 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001824
Douglas Gregorf5251602011-03-08 17:10:18 +00001825 if (VS.getLastLocation().isValid()) {
1826 // Update the end location of a method that has a virt-specifiers.
1827 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1828 MD->setRangeEnd(VS.getLastLocation());
1829 }
Richard Smitha4b39652012-08-06 03:25:17 +00001830
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001831 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001832
Douglas Gregor10bd3682008-11-17 22:58:34 +00001833 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001834
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001835 if (isInstField) {
1836 FieldDecl *FD = cast<FieldDecl>(Member);
1837 FieldCollector->Add(FD);
1838
1839 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1840 FD->getLocation())
1841 != DiagnosticsEngine::Ignored) {
1842 // Remember all explicit private FieldDecls that have a name, no side
1843 // effects and are not part of a dependent type declaration.
1844 if (!FD->isImplicit() && FD->getDeclName() &&
1845 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001846 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001847 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001848 !InitializationHasSideEffects(*FD))
1849 UnusedPrivateFields.insert(FD);
1850 }
1851 }
1852
John McCalld226f652010-08-21 09:40:31 +00001853 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001854}
1855
Hans Wennborg471f9852012-09-18 15:58:06 +00001856namespace {
1857 class UninitializedFieldVisitor
1858 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1859 Sema &S;
1860 ValueDecl *VD;
1861 public:
1862 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1863 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001864 S(S) {
1865 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1866 this->VD = IFD->getAnonField();
1867 else
1868 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001869 }
1870
1871 void HandleExpr(Expr *E) {
1872 if (!E) return;
1873
1874 // Expressions like x(x) sometimes lack the surrounding expressions
1875 // but need to be checked anyways.
1876 HandleValue(E);
1877 Visit(E);
1878 }
1879
1880 void HandleValue(Expr *E) {
1881 E = E->IgnoreParens();
1882
1883 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1884 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001885 return;
1886
1887 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1888 // or union.
1889 MemberExpr *FieldME = ME;
1890
Hans Wennborg471f9852012-09-18 15:58:06 +00001891 Expr *Base = E;
1892 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001893 ME = cast<MemberExpr>(Base);
1894
1895 if (isa<VarDecl>(ME->getMemberDecl()))
1896 return;
1897
1898 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1899 if (!FD->isAnonymousStructOrUnion())
1900 FieldME = ME;
1901
Hans Wennborg471f9852012-09-18 15:58:06 +00001902 Base = ME->getBase();
1903 }
1904
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001905 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00001906 unsigned diag = VD->getType()->isReferenceType()
1907 ? diag::warn_reference_field_is_uninit
1908 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001909 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001910 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001911 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00001912 }
1913
1914 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1915 HandleValue(CO->getTrueExpr());
1916 HandleValue(CO->getFalseExpr());
1917 return;
1918 }
1919
1920 if (BinaryConditionalOperator *BCO =
1921 dyn_cast<BinaryConditionalOperator>(E)) {
1922 HandleValue(BCO->getCommon());
1923 HandleValue(BCO->getFalseExpr());
1924 return;
1925 }
1926
1927 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1928 switch (BO->getOpcode()) {
1929 default:
1930 return;
1931 case(BO_PtrMemD):
1932 case(BO_PtrMemI):
1933 HandleValue(BO->getLHS());
1934 return;
1935 case(BO_Comma):
1936 HandleValue(BO->getRHS());
1937 return;
1938 }
1939 }
1940 }
1941
1942 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1943 if (E->getCastKind() == CK_LValueToRValue)
1944 HandleValue(E->getSubExpr());
1945
1946 Inherited::VisitImplicitCastExpr(E);
1947 }
1948
1949 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1950 Expr *Callee = E->getCallee();
1951 if (isa<MemberExpr>(Callee))
1952 HandleValue(Callee);
1953
1954 Inherited::VisitCXXMemberCallExpr(E);
1955 }
1956 };
1957 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1958 ValueDecl *VD) {
1959 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1960 }
1961} // namespace
1962
Richard Smith7a614d82011-06-11 17:19:42 +00001963/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001964/// in-class initializer for a non-static C++ class member, and after
1965/// instantiating an in-class initializer in a class template. Such actions
1966/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001967void
Richard Smithca523302012-06-10 03:12:00 +00001968Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001969 Expr *InitExpr) {
1970 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001971 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1972 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001973
1974 if (!InitExpr) {
1975 FD->setInvalidDecl();
1976 FD->removeInClassInitializer();
1977 return;
1978 }
1979
Peter Collingbournefef21892011-10-23 18:59:44 +00001980 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1981 FD->setInvalidDecl();
1982 FD->removeInClassInitializer();
1983 return;
1984 }
1985
Hans Wennborg471f9852012-09-18 15:58:06 +00001986 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1987 != DiagnosticsEngine::Ignored) {
1988 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1989 }
1990
Richard Smith7a614d82011-06-11 17:19:42 +00001991 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00001992 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001993 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001994 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001995 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1996 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001997 Expr **Inits = &InitExpr;
1998 unsigned NumInits = 1;
1999 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002000 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002001 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002002 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00002003 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
2004 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00002005 if (Init.isInvalid()) {
2006 FD->setInvalidDecl();
2007 return;
2008 }
Richard Smith7a614d82011-06-11 17:19:42 +00002009 }
2010
Richard Smith41956372013-01-14 22:39:08 +00002011 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002012 // The initialization of each base and member constitutes a
2013 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002014 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002015 if (Init.isInvalid()) {
2016 FD->setInvalidDecl();
2017 return;
2018 }
2019
2020 InitExpr = Init.release();
2021
2022 FD->setInClassInitializer(InitExpr);
2023}
2024
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002025/// \brief Find the direct and/or virtual base specifiers that
2026/// correspond to the given base type, for use in base initialization
2027/// within a constructor.
2028static bool FindBaseInitializer(Sema &SemaRef,
2029 CXXRecordDecl *ClassDecl,
2030 QualType BaseType,
2031 const CXXBaseSpecifier *&DirectBaseSpec,
2032 const CXXBaseSpecifier *&VirtualBaseSpec) {
2033 // First, check for a direct base class.
2034 DirectBaseSpec = 0;
2035 for (CXXRecordDecl::base_class_const_iterator Base
2036 = ClassDecl->bases_begin();
2037 Base != ClassDecl->bases_end(); ++Base) {
2038 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2039 // We found a direct base of this type. That's what we're
2040 // initializing.
2041 DirectBaseSpec = &*Base;
2042 break;
2043 }
2044 }
2045
2046 // Check for a virtual base class.
2047 // FIXME: We might be able to short-circuit this if we know in advance that
2048 // there are no virtual bases.
2049 VirtualBaseSpec = 0;
2050 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2051 // We haven't found a base yet; search the class hierarchy for a
2052 // virtual base class.
2053 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2054 /*DetectVirtual=*/false);
2055 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2056 BaseType, Paths)) {
2057 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2058 Path != Paths.end(); ++Path) {
2059 if (Path->back().Base->isVirtual()) {
2060 VirtualBaseSpec = Path->back().Base;
2061 break;
2062 }
2063 }
2064 }
2065 }
2066
2067 return DirectBaseSpec || VirtualBaseSpec;
2068}
2069
Sebastian Redl6df65482011-09-24 17:48:25 +00002070/// \brief Handle a C++ member initializer using braced-init-list syntax.
2071MemInitResult
2072Sema::ActOnMemInitializer(Decl *ConstructorD,
2073 Scope *S,
2074 CXXScopeSpec &SS,
2075 IdentifierInfo *MemberOrBase,
2076 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002077 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002078 SourceLocation IdLoc,
2079 Expr *InitList,
2080 SourceLocation EllipsisLoc) {
2081 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002082 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002083 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002084}
2085
2086/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002087MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002088Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002089 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002090 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002091 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002092 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002093 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002094 SourceLocation IdLoc,
2095 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002096 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002097 SourceLocation RParenLoc,
2098 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002099 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2100 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002101 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002102 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002103 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002104}
2105
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002106namespace {
2107
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002108// Callback to only accept typo corrections that can be a valid C++ member
2109// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002110class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2111 public:
2112 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2113 : ClassDecl(ClassDecl) {}
2114
2115 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2116 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2117 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2118 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2119 else
2120 return isa<TypeDecl>(ND);
2121 }
2122 return false;
2123 }
2124
2125 private:
2126 CXXRecordDecl *ClassDecl;
2127};
2128
2129}
2130
Sebastian Redl6df65482011-09-24 17:48:25 +00002131/// \brief Handle a C++ member initializer.
2132MemInitResult
2133Sema::BuildMemInitializer(Decl *ConstructorD,
2134 Scope *S,
2135 CXXScopeSpec &SS,
2136 IdentifierInfo *MemberOrBase,
2137 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002138 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002139 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002140 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002141 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002142 if (!ConstructorD)
2143 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002145 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002146
2147 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002148 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002149 if (!Constructor) {
2150 // The user wrote a constructor initializer on a function that is
2151 // not a C++ constructor. Ignore the error for now, because we may
2152 // have more member initializers coming; we'll diagnose it just
2153 // once in ActOnMemInitializers.
2154 return true;
2155 }
2156
2157 CXXRecordDecl *ClassDecl = Constructor->getParent();
2158
2159 // C++ [class.base.init]p2:
2160 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002161 // constructor's class and, if not found in that scope, are looked
2162 // up in the scope containing the constructor's definition.
2163 // [Note: if the constructor's class contains a member with the
2164 // same name as a direct or virtual base class of the class, a
2165 // mem-initializer-id naming the member or base class and composed
2166 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002167 // mem-initializer-id for the hidden base class may be specified
2168 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002169 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002170 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002171 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002172 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002173 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002174 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002175 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2176 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002177 if (EllipsisLoc.isValid())
2178 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002179 << MemberOrBase
2180 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002181
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002182 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002183 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002184 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002185 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002186 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002187 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002188 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002189
2190 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002191 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002192 } else if (DS.getTypeSpecType() == TST_decltype) {
2193 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002194 } else {
2195 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2196 LookupParsedName(R, S, &SS);
2197
2198 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2199 if (!TyD) {
2200 if (R.isAmbiguous()) return true;
2201
John McCallfd225442010-04-09 19:01:14 +00002202 // We don't want access-control diagnostics here.
2203 R.suppressDiagnostics();
2204
Douglas Gregor7a886e12010-01-19 06:46:48 +00002205 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2206 bool NotUnknownSpecialization = false;
2207 DeclContext *DC = computeDeclContext(SS, false);
2208 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2209 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2210
2211 if (!NotUnknownSpecialization) {
2212 // When the scope specifier can refer to a member of an unknown
2213 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002214 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2215 SS.getWithLocInContext(Context),
2216 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002217 if (BaseType.isNull())
2218 return true;
2219
Douglas Gregor7a886e12010-01-19 06:46:48 +00002220 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002221 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002222 }
2223 }
2224
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002225 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002226 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002227 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002228 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002229 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002230 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002231 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2232 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002233 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002234 // We have found a non-static data member with a similar
2235 // name to what was typed; complain and initialize that
2236 // member.
2237 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2238 << MemberOrBase << true << CorrectedQuotedStr
2239 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2240 Diag(Member->getLocation(), diag::note_previous_decl)
2241 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002242
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002243 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002244 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002245 const CXXBaseSpecifier *DirectBaseSpec;
2246 const CXXBaseSpecifier *VirtualBaseSpec;
2247 if (FindBaseInitializer(*this, ClassDecl,
2248 Context.getTypeDeclType(Type),
2249 DirectBaseSpec, VirtualBaseSpec)) {
2250 // We have found a direct or virtual base class with a
2251 // similar name to what was typed; complain and initialize
2252 // that base class.
2253 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002254 << MemberOrBase << false << CorrectedQuotedStr
2255 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002256
2257 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2258 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002259 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002260 diag::note_base_class_specified_here)
2261 << BaseSpec->getType()
2262 << BaseSpec->getSourceRange();
2263
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002264 TyD = Type;
2265 }
2266 }
2267 }
2268
Douglas Gregor7a886e12010-01-19 06:46:48 +00002269 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002270 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002271 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002272 return true;
2273 }
John McCall2b194412009-12-21 10:41:20 +00002274 }
2275
Douglas Gregor7a886e12010-01-19 06:46:48 +00002276 if (BaseType.isNull()) {
2277 BaseType = Context.getTypeDeclType(TyD);
2278 if (SS.isSet()) {
2279 NestedNameSpecifier *Qualifier =
2280 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002281
Douglas Gregor7a886e12010-01-19 06:46:48 +00002282 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002283 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002284 }
John McCall2b194412009-12-21 10:41:20 +00002285 }
2286 }
Mike Stump1eb44332009-09-09 15:08:12 +00002287
John McCalla93c9342009-12-07 02:54:59 +00002288 if (!TInfo)
2289 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002290
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002291 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002292}
2293
Chandler Carruth81c64772011-09-03 01:14:15 +00002294/// Checks a member initializer expression for cases where reference (or
2295/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002296static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2297 Expr *Init,
2298 SourceLocation IdLoc) {
2299 QualType MemberTy = Member->getType();
2300
2301 // We only handle pointers and references currently.
2302 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2303 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2304 return;
2305
2306 const bool IsPointer = MemberTy->isPointerType();
2307 if (IsPointer) {
2308 if (const UnaryOperator *Op
2309 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2310 // The only case we're worried about with pointers requires taking the
2311 // address.
2312 if (Op->getOpcode() != UO_AddrOf)
2313 return;
2314
2315 Init = Op->getSubExpr();
2316 } else {
2317 // We only handle address-of expression initializers for pointers.
2318 return;
2319 }
2320 }
2321
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002322 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2323 // Taking the address of a temporary will be diagnosed as a hard error.
2324 if (IsPointer)
2325 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002326
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002327 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2328 << Member << Init->getSourceRange();
2329 } else if (const DeclRefExpr *DRE
2330 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2331 // We only warn when referring to a non-reference parameter declaration.
2332 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2333 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002334 return;
2335
2336 S.Diag(Init->getExprLoc(),
2337 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2338 : diag::warn_bind_ref_member_to_parameter)
2339 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002340 } else {
2341 // Other initializers are fine.
2342 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002343 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002344
2345 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2346 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002347}
2348
John McCallf312b1e2010-08-26 23:41:50 +00002349MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002350Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002351 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002352 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2353 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2354 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002355 "Member must be a FieldDecl or IndirectFieldDecl");
2356
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002357 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002358 return true;
2359
Douglas Gregor464b2f02010-11-05 22:21:31 +00002360 if (Member->isInvalidDecl())
2361 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002362
John McCallb4190042009-11-04 23:02:40 +00002363 // Diagnose value-uses of fields to initialize themselves, e.g.
2364 // foo(foo)
2365 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002366 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002367 Expr **Args;
2368 unsigned NumArgs;
2369 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2370 Args = ParenList->getExprs();
2371 NumArgs = ParenList->getNumExprs();
Richard Smithc83c2302012-12-19 01:39:02 +00002372 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002373 Args = InitList->getInits();
2374 NumArgs = InitList->getNumInits();
Richard Smithc83c2302012-12-19 01:39:02 +00002375 } else {
2376 // Template instantiation doesn't reconstruct ParenListExprs for us.
2377 Args = &Init;
2378 NumArgs = 1;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002379 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002380
Richard Trieude5e75c2012-06-14 23:11:34 +00002381 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2382 != DiagnosticsEngine::Ignored)
2383 for (unsigned i = 0; i < NumArgs; ++i)
2384 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002385 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002386 // initializing the i'th field, throw a warning if any of the >= i'th
2387 // fields are used, as they are not yet initialized.
2388 // Right now we are only handling the case where the i'th field uses
2389 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002390 // Also need to take into account that some fields may be initialized by
2391 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002392 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002393
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002394 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002395
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002396 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002397 // Can't check initialization for a member of dependent type or when
2398 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002399 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002400 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002401 bool InitList = false;
2402 if (isa<InitListExpr>(Init)) {
2403 InitList = true;
2404 Args = &Init;
2405 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002406
2407 if (isStdInitializerList(Member->getType(), 0)) {
2408 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2409 << /*at end of ctor*/1 << InitRange;
2410 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002411 }
2412
Chandler Carruth894aed92010-12-06 09:23:57 +00002413 // Initialize the member.
2414 InitializedEntity MemberEntity =
2415 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2416 : InitializedEntity::InitializeMember(IndirectMember, 0);
2417 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002418 InitList ? InitializationKind::CreateDirectList(IdLoc)
2419 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2420 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002421
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002422 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2423 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002424 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002425 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002426 if (MemberInit.isInvalid())
2427 return true;
2428
Richard Smith41956372013-01-14 22:39:08 +00002429 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002430 // The initialization of each base and member constitutes a
2431 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002432 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002433 if (MemberInit.isInvalid())
2434 return true;
2435
Richard Smithc83c2302012-12-19 01:39:02 +00002436 Init = MemberInit.get();
2437 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002438 }
2439
Chandler Carruth894aed92010-12-06 09:23:57 +00002440 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002441 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2442 InitRange.getBegin(), Init,
2443 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002444 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002445 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2446 InitRange.getBegin(), Init,
2447 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002448 }
Eli Friedman59c04372009-07-29 19:44:27 +00002449}
2450
John McCallf312b1e2010-08-26 23:41:50 +00002451MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002452Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002453 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002454 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002455 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002456 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002457 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002458 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002459
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002460 bool InitList = true;
2461 Expr **Args = &Init;
2462 unsigned NumArgs = 1;
2463 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2464 InitList = false;
2465 Args = ParenList->getExprs();
2466 NumArgs = ParenList->getNumExprs();
2467 }
2468
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002469 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002470 // Initialize the object.
2471 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2472 QualType(ClassDecl->getTypeForDecl(), 0));
2473 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002474 InitList ? InitializationKind::CreateDirectList(NameLoc)
2475 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2476 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002477 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2478 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002479 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002480 0);
Sean Hunt41717662011-02-26 19:13:13 +00002481 if (DelegationInit.isInvalid())
2482 return true;
2483
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002484 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2485 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002486
Richard Smith41956372013-01-14 22:39:08 +00002487 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002488 // The initialization of each base and member constitutes a
2489 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002490 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2491 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002492 if (DelegationInit.isInvalid())
2493 return true;
2494
Eli Friedmand21016f2012-05-19 23:35:23 +00002495 // If we are in a dependent context, template instantiation will
2496 // perform this type-checking again. Just save the arguments that we
2497 // received in a ParenListExpr.
2498 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2499 // of the information that we have about the base
2500 // initializer. However, deconstructing the ASTs is a dicey process,
2501 // and this approach is far more likely to get the corner cases right.
2502 if (CurContext->isDependentContext())
2503 DelegationInit = Owned(Init);
2504
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002505 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002506 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002507 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002508}
2509
2510MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002511Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002512 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002513 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002514 SourceLocation BaseLoc
2515 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002516
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002517 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2518 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2519 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2520
2521 // C++ [class.base.init]p2:
2522 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002523 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002524 // of that class, the mem-initializer is ill-formed. A
2525 // mem-initializer-list can initialize a base class using any
2526 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002527 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002528
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002529 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002530 if (EllipsisLoc.isValid()) {
2531 // This is a pack expansion.
2532 if (!BaseType->containsUnexpandedParameterPack()) {
2533 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002534 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002535
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002536 EllipsisLoc = SourceLocation();
2537 }
2538 } else {
2539 // Check for any unexpanded parameter packs.
2540 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2541 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002542
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002543 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002544 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002545 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002546
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002547 // Check for direct and virtual base classes.
2548 const CXXBaseSpecifier *DirectBaseSpec = 0;
2549 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2550 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002551 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2552 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002553 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002554
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002555 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2556 VirtualBaseSpec);
2557
2558 // C++ [base.class.init]p2:
2559 // Unless the mem-initializer-id names a nonstatic data member of the
2560 // constructor's class or a direct or virtual base of that class, the
2561 // mem-initializer is ill-formed.
2562 if (!DirectBaseSpec && !VirtualBaseSpec) {
2563 // If the class has any dependent bases, then it's possible that
2564 // one of those types will resolve to the same type as
2565 // BaseType. Therefore, just treat this as a dependent base
2566 // class initialization. FIXME: Should we try to check the
2567 // initialization anyway? It seems odd.
2568 if (ClassDecl->hasAnyDependentBases())
2569 Dependent = true;
2570 else
2571 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2572 << BaseType << Context.getTypeDeclType(ClassDecl)
2573 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2574 }
2575 }
2576
2577 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002578 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002579
Sebastian Redl6df65482011-09-24 17:48:25 +00002580 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2581 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002582 InitRange.getBegin(), Init,
2583 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002584 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002585
2586 // C++ [base.class.init]p2:
2587 // If a mem-initializer-id is ambiguous because it designates both
2588 // a direct non-virtual base class and an inherited virtual base
2589 // class, the mem-initializer is ill-formed.
2590 if (DirectBaseSpec && VirtualBaseSpec)
2591 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002592 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002593
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002594 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002595 if (!BaseSpec)
2596 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2597
2598 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002599 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002600 Expr **Args = &Init;
2601 unsigned NumArgs = 1;
2602 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002603 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002604 Args = ParenList->getExprs();
2605 NumArgs = ParenList->getNumExprs();
2606 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002607
2608 InitializedEntity BaseEntity =
2609 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2610 InitializationKind Kind =
2611 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2612 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2613 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002614 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2615 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002616 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002617 if (BaseInit.isInvalid())
2618 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002619
Richard Smith41956372013-01-14 22:39:08 +00002620 // C++11 [class.base.init]p7:
2621 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002622 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002623 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002624 if (BaseInit.isInvalid())
2625 return true;
2626
2627 // If we are in a dependent context, template instantiation will
2628 // perform this type-checking again. Just save the arguments that we
2629 // received in a ParenListExpr.
2630 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2631 // of the information that we have about the base
2632 // initializer. However, deconstructing the ASTs is a dicey process,
2633 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002634 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002635 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002636
Sean Huntcbb67482011-01-08 20:30:50 +00002637 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002638 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002639 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002640 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002641 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002642}
2643
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002644// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002645static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2646 if (T.isNull()) T = E->getType();
2647 QualType TargetType = SemaRef.BuildReferenceType(
2648 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002649 SourceLocation ExprLoc = E->getLocStart();
2650 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2651 TargetType, ExprLoc);
2652
2653 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2654 SourceRange(ExprLoc, ExprLoc),
2655 E->getSourceRange()).take();
2656}
2657
Anders Carlssone5ef7402010-04-23 03:10:23 +00002658/// ImplicitInitializerKind - How an implicit base or member initializer should
2659/// initialize its base or member.
2660enum ImplicitInitializerKind {
2661 IIK_Default,
2662 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002663 IIK_Move,
2664 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002665};
2666
Anders Carlssondefefd22010-04-23 02:00:02 +00002667static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002668BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002669 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002670 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002671 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002672 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002673 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002674 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2675 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002676
John McCall60d7b3a2010-08-24 06:29:42 +00002677 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002678
2679 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002680 case IIK_Inherit: {
2681 const CXXRecordDecl *Inherited =
2682 Constructor->getInheritedConstructor()->getParent();
2683 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2684 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2685 // C++11 [class.inhctor]p8:
2686 // Each expression in the expression-list is of the form
2687 // static_cast<T&&>(p), where p is the name of the corresponding
2688 // constructor parameter and T is the declared type of p.
2689 SmallVector<Expr*, 16> Args;
2690 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2691 ParmVarDecl *PD = Constructor->getParamDecl(I);
2692 ExprResult ArgExpr =
2693 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2694 VK_LValue, SourceLocation());
2695 if (ArgExpr.isInvalid())
2696 return true;
2697 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2698 }
2699
2700 InitializationKind InitKind = InitializationKind::CreateDirect(
2701 Constructor->getLocation(), SourceLocation(), SourceLocation());
2702 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2703 Args.data(), Args.size());
2704 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2705 break;
2706 }
2707 }
2708 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002709 case IIK_Default: {
2710 InitializationKind InitKind
2711 = InitializationKind::CreateDefault(Constructor->getLocation());
2712 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002713 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002714 break;
2715 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002716
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002717 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002718 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002719 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002720 ParmVarDecl *Param = Constructor->getParamDecl(0);
2721 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002722
Anders Carlssone5ef7402010-04-23 03:10:23 +00002723 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002724 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002725 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002726 Constructor->getLocation(), ParamType,
2727 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002728
Eli Friedman5f2987c2012-02-02 03:46:19 +00002729 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2730
Anders Carlssonc7957502010-04-24 22:02:54 +00002731 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002732 QualType ArgTy =
2733 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2734 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002735
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002736 if (Moving) {
2737 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2738 }
2739
John McCallf871d0c2010-08-07 06:22:56 +00002740 CXXCastPath BasePath;
2741 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002742 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2743 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002744 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002745 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002746
Anders Carlssone5ef7402010-04-23 03:10:23 +00002747 InitializationKind InitKind
2748 = InitializationKind::CreateDirect(Constructor->getLocation(),
2749 SourceLocation(), SourceLocation());
2750 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2751 &CopyCtorArg, 1);
2752 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002753 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002754 break;
2755 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002756 }
John McCall9ae2f072010-08-23 23:25:46 +00002757
Douglas Gregor53c374f2010-12-07 00:41:46 +00002758 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002759 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002760 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002761
Anders Carlssondefefd22010-04-23 02:00:02 +00002762 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002763 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002764 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2765 SourceLocation()),
2766 BaseSpec->isVirtual(),
2767 SourceLocation(),
2768 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002769 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002770 SourceLocation());
2771
Anders Carlssondefefd22010-04-23 02:00:02 +00002772 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002773}
2774
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002775static bool RefersToRValueRef(Expr *MemRef) {
2776 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2777 return Referenced->getType()->isRValueReferenceType();
2778}
2779
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002780static bool
2781BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002782 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002783 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002784 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002785 if (Field->isInvalidDecl())
2786 return true;
2787
Chandler Carruthf186b542010-06-29 23:50:44 +00002788 SourceLocation Loc = Constructor->getLocation();
2789
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002790 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2791 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002792 ParmVarDecl *Param = Constructor->getParamDecl(0);
2793 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002794
2795 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002796 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2797 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002798
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002799 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002800 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002801 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002802 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002803
Eli Friedman5f2987c2012-02-02 03:46:19 +00002804 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2805
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002806 if (Moving) {
2807 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2808 }
2809
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002810 // Build a reference to this field within the parameter.
2811 CXXScopeSpec SS;
2812 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2813 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002814 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2815 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002816 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002817 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002818 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002819 ParamType, Loc,
2820 /*IsArrow=*/false,
2821 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002822 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002823 /*FirstQualifierInScope=*/0,
2824 MemberLookup,
2825 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002826 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002827 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002828
2829 // C++11 [class.copy]p15:
2830 // - if a member m has rvalue reference type T&&, it is direct-initialized
2831 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002832 if (RefersToRValueRef(CtorArg.get())) {
2833 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002834 }
2835
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002836 // When the field we are copying is an array, create index variables for
2837 // each dimension of the array. We use these index variables to subscript
2838 // the source array, and other clients (e.g., CodeGen) will perform the
2839 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002840 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002841 QualType BaseType = Field->getType();
2842 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002843 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002844 while (const ConstantArrayType *Array
2845 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002846 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002847 // Create the iteration variable for this array index.
2848 IdentifierInfo *IterationVarName = 0;
2849 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002850 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002851 llvm::raw_svector_ostream OS(Str);
2852 OS << "__i" << IndexVariables.size();
2853 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2854 }
2855 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002856 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002857 IterationVarName, SizeType,
2858 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002859 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002860 IndexVariables.push_back(IterationVar);
2861
2862 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002863 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002864 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002865 assert(!IterationVarRef.isInvalid() &&
2866 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002867 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2868 assert(!IterationVarRef.isInvalid() &&
2869 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002870
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002871 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002872 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002873 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002874 Loc);
2875 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002876 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002877
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002878 BaseType = Array->getElementType();
2879 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002880
2881 // The array subscript expression is an lvalue, which is wrong for moving.
2882 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002883 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002884
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002885 // Construct the entity that we will be initializing. For an array, this
2886 // will be first element in the array, which may require several levels
2887 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002888 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002889 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002890 if (Indirect)
2891 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2892 else
2893 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002894 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2895 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2896 0,
2897 Entities.back()));
2898
2899 // Direct-initialize to use the copy constructor.
2900 InitializationKind InitKind =
2901 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2902
Sebastian Redl74e611a2011-09-04 18:14:28 +00002903 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002904 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002905 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002906
John McCall60d7b3a2010-08-24 06:29:42 +00002907 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002908 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002909 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002910 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002911 if (MemberInit.isInvalid())
2912 return true;
2913
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002914 if (Indirect) {
2915 assert(IndexVariables.size() == 0 &&
2916 "Indirect field improperly initialized");
2917 CXXMemberInit
2918 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2919 Loc, Loc,
2920 MemberInit.takeAs<Expr>(),
2921 Loc);
2922 } else
2923 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2924 Loc, MemberInit.takeAs<Expr>(),
2925 Loc,
2926 IndexVariables.data(),
2927 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002928 return false;
2929 }
2930
Richard Smith07b0fdc2013-03-18 21:12:30 +00002931 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
2932 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002933
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002934 QualType FieldBaseElementType =
2935 SemaRef.Context.getBaseElementType(Field->getType());
2936
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002937 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002938 InitializedEntity InitEntity
2939 = Indirect? InitializedEntity::InitializeMember(Indirect)
2940 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002941 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002942 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002943
2944 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002945 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002946 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002947
Douglas Gregor53c374f2010-12-07 00:41:46 +00002948 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002949 if (MemberInit.isInvalid())
2950 return true;
2951
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002952 if (Indirect)
2953 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2954 Indirect, Loc,
2955 Loc,
2956 MemberInit.get(),
2957 Loc);
2958 else
2959 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2960 Field, Loc, Loc,
2961 MemberInit.get(),
2962 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002963 return false;
2964 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002965
Sean Hunt1f2f3842011-05-17 00:19:05 +00002966 if (!Field->getParent()->isUnion()) {
2967 if (FieldBaseElementType->isReferenceType()) {
2968 SemaRef.Diag(Constructor->getLocation(),
2969 diag::err_uninitialized_member_in_ctor)
2970 << (int)Constructor->isImplicit()
2971 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2972 << 0 << Field->getDeclName();
2973 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2974 return true;
2975 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002976
Sean Hunt1f2f3842011-05-17 00:19:05 +00002977 if (FieldBaseElementType.isConstQualified()) {
2978 SemaRef.Diag(Constructor->getLocation(),
2979 diag::err_uninitialized_member_in_ctor)
2980 << (int)Constructor->isImplicit()
2981 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2982 << 1 << Field->getDeclName();
2983 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2984 return true;
2985 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002986 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002987
David Blaikie4e4d0842012-03-11 07:00:24 +00002988 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002989 FieldBaseElementType->isObjCRetainableType() &&
2990 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2991 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002992 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002993 // Default-initialize Objective-C pointers to NULL.
2994 CXXMemberInit
2995 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2996 Loc, Loc,
2997 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2998 Loc);
2999 return false;
3000 }
3001
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003002 // Nothing to initialize.
3003 CXXMemberInit = 0;
3004 return false;
3005}
John McCallf1860e52010-05-20 23:23:51 +00003006
3007namespace {
3008struct BaseAndFieldInfo {
3009 Sema &S;
3010 CXXConstructorDecl *Ctor;
3011 bool AnyErrorsInInits;
3012 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003013 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003014 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003015
3016 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3017 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003018 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3019 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003020 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003021 else if (Generated && Ctor->isMoveConstructor())
3022 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003023 else if (Ctor->getInheritedConstructor())
3024 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003025 else
3026 IIK = IIK_Default;
3027 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003028
3029 bool isImplicitCopyOrMove() const {
3030 switch (IIK) {
3031 case IIK_Copy:
3032 case IIK_Move:
3033 return true;
3034
3035 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003036 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003037 return false;
3038 }
David Blaikie30263482012-01-20 21:50:17 +00003039
3040 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003041 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003042
3043 bool addFieldInitializer(CXXCtorInitializer *Init) {
3044 AllToInit.push_back(Init);
3045
3046 // Check whether this initializer makes the field "used".
3047 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
3048 S.UnusedPrivateFields.remove(Init->getAnyMember());
3049
3050 return false;
3051 }
John McCallf1860e52010-05-20 23:23:51 +00003052};
3053}
3054
Richard Smitha4950662011-09-19 13:34:43 +00003055/// \brief Determine whether the given indirect field declaration is somewhere
3056/// within an anonymous union.
3057static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3058 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3059 CEnd = F->chain_end();
3060 C != CEnd; ++C)
3061 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3062 if (Record->isUnion())
3063 return true;
3064
3065 return false;
3066}
3067
Douglas Gregorddb21472011-11-02 23:04:16 +00003068/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3069/// array type.
3070static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3071 if (T->isIncompleteArrayType())
3072 return true;
3073
3074 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3075 if (!ArrayT->getSize())
3076 return true;
3077
3078 T = ArrayT->getElementType();
3079 }
3080
3081 return false;
3082}
3083
Richard Smith7a614d82011-06-11 17:19:42 +00003084static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003085 FieldDecl *Field,
3086 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003087
Chandler Carruthe861c602010-06-30 02:59:29 +00003088 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003089 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3090 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003091
Richard Smith0b8220a2012-08-07 21:30:42 +00003092 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003093 // has a brace-or-equal-initializer, the entity is initialized as specified
3094 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003095 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003096 CXXCtorInitializer *Init;
3097 if (Indirect)
3098 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3099 SourceLocation(),
3100 SourceLocation(), 0,
3101 SourceLocation());
3102 else
3103 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3104 SourceLocation(),
3105 SourceLocation(), 0,
3106 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003107 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003108 }
3109
Richard Smithc115f632011-09-18 11:14:50 +00003110 // Don't build an implicit initializer for union members if none was
3111 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003112 if (Field->getParent()->isUnion() ||
3113 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003114 return false;
3115
Douglas Gregorddb21472011-11-02 23:04:16 +00003116 // Don't initialize incomplete or zero-length arrays.
3117 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3118 return false;
3119
John McCallf1860e52010-05-20 23:23:51 +00003120 // Don't try to build an implicit initializer if there were semantic
3121 // errors in any of the initializers (and therefore we might be
3122 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003123 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003124 return false;
3125
Sean Huntcbb67482011-01-08 20:30:50 +00003126 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003127 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3128 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003129 return true;
John McCallf1860e52010-05-20 23:23:51 +00003130
Richard Smith0b8220a2012-08-07 21:30:42 +00003131 if (!Init)
3132 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003133
Richard Smith0b8220a2012-08-07 21:30:42 +00003134 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003135}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003136
3137bool
3138Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3139 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003140 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003141 Constructor->setNumCtorInitializers(1);
3142 CXXCtorInitializer **initializer =
3143 new (Context) CXXCtorInitializer*[1];
3144 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3145 Constructor->setCtorInitializers(initializer);
3146
Sean Huntb76af9c2011-05-03 23:05:34 +00003147 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003148 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003149 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3150 }
3151
Sean Huntc1598702011-05-05 00:05:47 +00003152 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003153
Sean Hunt059ce0d2011-05-01 07:04:31 +00003154 return false;
3155}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003156
David Blaikie93c86172013-01-17 05:26:25 +00003157bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3158 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003159 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003160 // Just store the initializers as written, they will be checked during
3161 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003162 if (!Initializers.empty()) {
3163 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003164 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003165 new (Context) CXXCtorInitializer*[Initializers.size()];
3166 memcpy(baseOrMemberInitializers, Initializers.data(),
3167 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003168 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003169 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003170
3171 // Let template instantiation know whether we had errors.
3172 if (AnyErrors)
3173 Constructor->setInvalidDecl();
3174
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003175 return false;
3176 }
3177
John McCallf1860e52010-05-20 23:23:51 +00003178 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003179
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003180 // We need to build the initializer AST according to order of construction
3181 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003182 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003183 if (!ClassDecl)
3184 return true;
3185
Eli Friedman80c30da2009-11-09 19:20:36 +00003186 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003187
David Blaikie93c86172013-01-17 05:26:25 +00003188 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003189 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003190
3191 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003192 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003193 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003194 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003195 }
3196
Anders Carlsson711f34a2010-04-21 19:52:01 +00003197 // Keep track of the direct virtual bases.
3198 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3199 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3200 E = ClassDecl->bases_end(); I != E; ++I) {
3201 if (I->isVirtual())
3202 DirectVBases.insert(I);
3203 }
3204
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003205 // Push virtual bases before others.
3206 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3207 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3208
Sean Huntcbb67482011-01-08 20:30:50 +00003209 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003210 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3211 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003212 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003213 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003214 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003215 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003216 VBase, IsInheritedVirtualBase,
3217 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003218 HadError = true;
3219 continue;
3220 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003221
John McCallf1860e52010-05-20 23:23:51 +00003222 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003223 }
3224 }
Mike Stump1eb44332009-09-09 15:08:12 +00003225
John McCallf1860e52010-05-20 23:23:51 +00003226 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003227 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3228 E = ClassDecl->bases_end(); Base != E; ++Base) {
3229 // Virtuals are in the virtual base list and already constructed.
3230 if (Base->isVirtual())
3231 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003232
Sean Huntcbb67482011-01-08 20:30:50 +00003233 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003234 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3235 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003236 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003237 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003238 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003239 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003240 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003241 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003242 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003243 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003244
John McCallf1860e52010-05-20 23:23:51 +00003245 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003246 }
3247 }
Mike Stump1eb44332009-09-09 15:08:12 +00003248
John McCallf1860e52010-05-20 23:23:51 +00003249 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003250 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3251 MemEnd = ClassDecl->decls_end();
3252 Mem != MemEnd; ++Mem) {
3253 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003254 // C++ [class.bit]p2:
3255 // A declaration for a bit-field that omits the identifier declares an
3256 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3257 // initialized.
3258 if (F->isUnnamedBitfield())
3259 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003260
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003261 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003262 // handle anonymous struct/union fields based on their individual
3263 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003264 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003265 continue;
3266
3267 if (CollectFieldInitializer(*this, Info, F))
3268 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003269 continue;
3270 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003271
3272 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003273 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003274 continue;
3275
3276 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3277 if (F->getType()->isIncompleteArrayType()) {
3278 assert(ClassDecl->hasFlexibleArrayMember() &&
3279 "Incomplete array type is not valid");
3280 continue;
3281 }
3282
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003283 // Initialize each field of an anonymous struct individually.
3284 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3285 HadError = true;
3286
3287 continue;
3288 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003289 }
Mike Stump1eb44332009-09-09 15:08:12 +00003290
David Blaikie93c86172013-01-17 05:26:25 +00003291 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003292 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003293 Constructor->setNumCtorInitializers(NumInitializers);
3294 CXXCtorInitializer **baseOrMemberInitializers =
3295 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003296 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003297 NumInitializers * sizeof(CXXCtorInitializer*));
3298 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003299
John McCallef027fe2010-03-16 21:39:52 +00003300 // Constructors implicitly reference the base and member
3301 // destructors.
3302 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3303 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003304 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003305
3306 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003307}
3308
David Blaikieee000bb2013-01-17 08:49:22 +00003309static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003310 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003311 const RecordDecl *RD = RT->getDecl();
3312 if (RD->isAnonymousStructOrUnion()) {
3313 for (RecordDecl::field_iterator Field = RD->field_begin(),
3314 E = RD->field_end(); Field != E; ++Field)
3315 PopulateKeysForFields(*Field, IdealInits);
3316 return;
3317 }
Eli Friedman6347f422009-07-21 19:28:10 +00003318 }
David Blaikieee000bb2013-01-17 08:49:22 +00003319 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003320}
3321
Anders Carlssonea356fb2010-04-02 05:42:15 +00003322static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003323 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003324}
3325
Anders Carlssonea356fb2010-04-02 05:42:15 +00003326static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003327 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003328 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003329 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003330
David Blaikieee000bb2013-01-17 08:49:22 +00003331 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003332}
3333
David Blaikie93c86172013-01-17 05:26:25 +00003334static void DiagnoseBaseOrMemInitializerOrder(
3335 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3336 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003337 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003338 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003339
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003340 // Don't check initializers order unless the warning is enabled at the
3341 // location of at least one initializer.
3342 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003343 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003344 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003345 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3346 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003347 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003348 ShouldCheckOrder = true;
3349 break;
3350 }
3351 }
3352 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003353 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003354
John McCalld6ca8da2010-04-10 07:37:23 +00003355 // Build the list of bases and members in the order that they'll
3356 // actually be initialized. The explicit initializers should be in
3357 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003358 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003359
Anders Carlsson071d6102010-04-02 03:38:04 +00003360 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3361
John McCalld6ca8da2010-04-10 07:37:23 +00003362 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003363 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003364 ClassDecl->vbases_begin(),
3365 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003366 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003367
John McCalld6ca8da2010-04-10 07:37:23 +00003368 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003369 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003370 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003371 if (Base->isVirtual())
3372 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003373 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003374 }
Mike Stump1eb44332009-09-09 15:08:12 +00003375
John McCalld6ca8da2010-04-10 07:37:23 +00003376 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003377 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003378 E = ClassDecl->field_end(); Field != E; ++Field) {
3379 if (Field->isUnnamedBitfield())
3380 continue;
3381
David Blaikieee000bb2013-01-17 08:49:22 +00003382 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003383 }
3384
John McCalld6ca8da2010-04-10 07:37:23 +00003385 unsigned NumIdealInits = IdealInitKeys.size();
3386 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003387
Sean Huntcbb67482011-01-08 20:30:50 +00003388 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003389 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003390 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003391 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003392
3393 // Scan forward to try to find this initializer in the idealized
3394 // initializers list.
3395 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3396 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003397 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003398
3399 // If we didn't find this initializer, it must be because we
3400 // scanned past it on a previous iteration. That can only
3401 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003402 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003403 Sema::SemaDiagnosticBuilder D =
3404 SemaRef.Diag(PrevInit->getSourceLocation(),
3405 diag::warn_initializer_out_of_order);
3406
Francois Pichet00eb3f92010-12-04 09:14:42 +00003407 if (PrevInit->isAnyMemberInitializer())
3408 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003409 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003410 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003411
Francois Pichet00eb3f92010-12-04 09:14:42 +00003412 if (Init->isAnyMemberInitializer())
3413 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003414 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003415 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003416
3417 // Move back to the initializer's location in the ideal list.
3418 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3419 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003420 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003421
3422 assert(IdealIndex != NumIdealInits &&
3423 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003424 }
John McCalld6ca8da2010-04-10 07:37:23 +00003425
3426 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003427 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003428}
3429
John McCall3c3ccdb2010-04-10 09:28:51 +00003430namespace {
3431bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003432 CXXCtorInitializer *Init,
3433 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003434 if (!PrevInit) {
3435 PrevInit = Init;
3436 return false;
3437 }
3438
3439 if (FieldDecl *Field = Init->getMember())
3440 S.Diag(Init->getSourceLocation(),
3441 diag::err_multiple_mem_initialization)
3442 << Field->getDeclName()
3443 << Init->getSourceRange();
3444 else {
John McCallf4c73712011-01-19 06:33:43 +00003445 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003446 assert(BaseClass && "neither field nor base");
3447 S.Diag(Init->getSourceLocation(),
3448 diag::err_multiple_base_initialization)
3449 << QualType(BaseClass, 0)
3450 << Init->getSourceRange();
3451 }
3452 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3453 << 0 << PrevInit->getSourceRange();
3454
3455 return true;
3456}
3457
Sean Huntcbb67482011-01-08 20:30:50 +00003458typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003459typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3460
3461bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003462 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003463 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003464 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003465 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003466 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003467
3468 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003469 if (Parent->isUnion()) {
3470 UnionEntry &En = Unions[Parent];
3471 if (En.first && En.first != Child) {
3472 S.Diag(Init->getSourceLocation(),
3473 diag::err_multiple_mem_union_initialization)
3474 << Field->getDeclName()
3475 << Init->getSourceRange();
3476 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3477 << 0 << En.second->getSourceRange();
3478 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003479 }
3480 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003481 En.first = Child;
3482 En.second = Init;
3483 }
David Blaikie6fe29652011-11-17 06:01:57 +00003484 if (!Parent->isAnonymousStructOrUnion())
3485 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003486 }
3487
3488 Child = Parent;
3489 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003490 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003491
3492 return false;
3493}
3494}
3495
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003496/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003497void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003498 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003499 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003500 bool AnyErrors) {
3501 if (!ConstructorDecl)
3502 return;
3503
3504 AdjustDeclIfTemplate(ConstructorDecl);
3505
3506 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003507 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003508
3509 if (!Constructor) {
3510 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3511 return;
3512 }
3513
John McCall3c3ccdb2010-04-10 09:28:51 +00003514 // Mapping for the duplicate initializers check.
3515 // For member initializers, this is keyed with a FieldDecl*.
3516 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003517 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003518
3519 // Mapping for the inconsistent anonymous-union initializers check.
3520 RedundantUnionMap MemberUnions;
3521
Anders Carlssonea356fb2010-04-02 05:42:15 +00003522 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003523 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003524 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003525
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003526 // Set the source order index.
3527 Init->setSourceOrder(i);
3528
Francois Pichet00eb3f92010-12-04 09:14:42 +00003529 if (Init->isAnyMemberInitializer()) {
3530 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003531 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3532 CheckRedundantUnionInit(*this, Init, MemberUnions))
3533 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003534 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003535 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3536 if (CheckRedundantInit(*this, Init, Members[Key]))
3537 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003538 } else {
3539 assert(Init->isDelegatingInitializer());
3540 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003541 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003542 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003543 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003544 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003545 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003546 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003547 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003548 // Return immediately as the initializer is set.
3549 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003550 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003551 }
3552
Anders Carlssonea356fb2010-04-02 05:42:15 +00003553 if (HadError)
3554 return;
3555
David Blaikie93c86172013-01-17 05:26:25 +00003556 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003557
David Blaikie93c86172013-01-17 05:26:25 +00003558 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003559}
3560
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003561void
John McCallef027fe2010-03-16 21:39:52 +00003562Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3563 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003564 // Ignore dependent contexts. Also ignore unions, since their members never
3565 // have destructors implicitly called.
3566 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003567 return;
John McCall58e6f342010-03-16 05:22:47 +00003568
3569 // FIXME: all the access-control diagnostics are positioned on the
3570 // field/base declaration. That's probably good; that said, the
3571 // user might reasonably want to know why the destructor is being
3572 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003573
Anders Carlsson9f853df2009-11-17 04:44:12 +00003574 // Non-static data members.
3575 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3576 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003577 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003578 if (Field->isInvalidDecl())
3579 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003580
3581 // Don't destroy incomplete or zero-length arrays.
3582 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3583 continue;
3584
Anders Carlsson9f853df2009-11-17 04:44:12 +00003585 QualType FieldType = Context.getBaseElementType(Field->getType());
3586
3587 const RecordType* RT = FieldType->getAs<RecordType>();
3588 if (!RT)
3589 continue;
3590
3591 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003592 if (FieldClassDecl->isInvalidDecl())
3593 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003594 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003595 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003596 // The destructor for an implicit anonymous union member is never invoked.
3597 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3598 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003599
Douglas Gregordb89f282010-07-01 22:47:18 +00003600 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003601 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003602 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003603 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003604 << Field->getDeclName()
3605 << FieldType);
3606
Eli Friedman5f2987c2012-02-02 03:46:19 +00003607 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003608 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003609 }
3610
John McCall58e6f342010-03-16 05:22:47 +00003611 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3612
Anders Carlsson9f853df2009-11-17 04:44:12 +00003613 // Bases.
3614 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3615 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003616 // Bases are always records in a well-formed non-dependent class.
3617 const RecordType *RT = Base->getType()->getAs<RecordType>();
3618
3619 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003620 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003621 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003622
John McCall58e6f342010-03-16 05:22:47 +00003623 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003624 // If our base class is invalid, we probably can't get its dtor anyway.
3625 if (BaseClassDecl->isInvalidDecl())
3626 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003627 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003628 continue;
John McCall58e6f342010-03-16 05:22:47 +00003629
Douglas Gregordb89f282010-07-01 22:47:18 +00003630 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003631 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003632
3633 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003634 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003635 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003636 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003637 << Base->getSourceRange(),
3638 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003639
Eli Friedman5f2987c2012-02-02 03:46:19 +00003640 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003641 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003642 }
3643
3644 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003645 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3646 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003647
3648 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003649 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003650
3651 // Ignore direct virtual bases.
3652 if (DirectVirtualBases.count(RT))
3653 continue;
3654
John McCall58e6f342010-03-16 05:22:47 +00003655 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003656 // If our base class is invalid, we probably can't get its dtor anyway.
3657 if (BaseClassDecl->isInvalidDecl())
3658 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003659 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003660 continue;
John McCall58e6f342010-03-16 05:22:47 +00003661
Douglas Gregordb89f282010-07-01 22:47:18 +00003662 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003663 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003664 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003665 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003666 << VBase->getType(),
3667 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003668
Eli Friedman5f2987c2012-02-02 03:46:19 +00003669 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003670 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003671 }
3672}
3673
John McCalld226f652010-08-21 09:40:31 +00003674void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003675 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003676 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003677
Mike Stump1eb44332009-09-09 15:08:12 +00003678 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003679 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003680 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003681}
3682
Mike Stump1eb44332009-09-09 15:08:12 +00003683bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003684 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003685 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3686 unsigned DiagID;
3687 AbstractDiagSelID SelID;
3688
3689 public:
3690 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3691 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3692
3693 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003694 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003695 if (SelID == -1)
3696 S.Diag(Loc, DiagID) << T;
3697 else
3698 S.Diag(Loc, DiagID) << SelID << T;
3699 }
3700 } Diagnoser(DiagID, SelID);
3701
3702 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003703}
3704
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003705bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003706 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003707 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003708 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003709
Anders Carlsson11f21a02009-03-23 19:10:31 +00003710 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003711 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003712
Ted Kremenek6217b802009-07-29 21:53:49 +00003713 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003714 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003715 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003716 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003717
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003718 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003719 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003720 }
Mike Stump1eb44332009-09-09 15:08:12 +00003721
Ted Kremenek6217b802009-07-29 21:53:49 +00003722 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003723 if (!RT)
3724 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003725
John McCall86ff3082010-02-04 22:26:26 +00003726 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003727
John McCall94c3b562010-08-18 09:41:07 +00003728 // We can't answer whether something is abstract until it has a
3729 // definition. If it's currently being defined, we'll walk back
3730 // over all the declarations when we have a full definition.
3731 const CXXRecordDecl *Def = RD->getDefinition();
3732 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003733 return false;
3734
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003735 if (!RD->isAbstract())
3736 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003737
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003738 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003739 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003740
John McCall94c3b562010-08-18 09:41:07 +00003741 return true;
3742}
3743
3744void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3745 // Check if we've already emitted the list of pure virtual functions
3746 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003747 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003748 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003749
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003750 CXXFinalOverriderMap FinalOverriders;
3751 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003752
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003753 // Keep a set of seen pure methods so we won't diagnose the same method
3754 // more than once.
3755 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3756
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003757 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3758 MEnd = FinalOverriders.end();
3759 M != MEnd;
3760 ++M) {
3761 for (OverridingMethods::iterator SO = M->second.begin(),
3762 SOEnd = M->second.end();
3763 SO != SOEnd; ++SO) {
3764 // C++ [class.abstract]p4:
3765 // A class is abstract if it contains or inherits at least one
3766 // pure virtual function for which the final overrider is pure
3767 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003768
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003769 //
3770 if (SO->second.size() != 1)
3771 continue;
3772
3773 if (!SO->second.front().Method->isPure())
3774 continue;
3775
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003776 if (!SeenPureMethods.insert(SO->second.front().Method))
3777 continue;
3778
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003779 Diag(SO->second.front().Method->getLocation(),
3780 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003781 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003782 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003783 }
3784
3785 if (!PureVirtualClassDiagSet)
3786 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3787 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003788}
3789
Anders Carlsson8211eff2009-03-24 01:19:16 +00003790namespace {
John McCall94c3b562010-08-18 09:41:07 +00003791struct AbstractUsageInfo {
3792 Sema &S;
3793 CXXRecordDecl *Record;
3794 CanQualType AbstractType;
3795 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003796
John McCall94c3b562010-08-18 09:41:07 +00003797 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3798 : S(S), Record(Record),
3799 AbstractType(S.Context.getCanonicalType(
3800 S.Context.getTypeDeclType(Record))),
3801 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003802
John McCall94c3b562010-08-18 09:41:07 +00003803 void DiagnoseAbstractType() {
3804 if (Invalid) return;
3805 S.DiagnoseAbstractType(Record);
3806 Invalid = true;
3807 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003808
John McCall94c3b562010-08-18 09:41:07 +00003809 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3810};
3811
3812struct CheckAbstractUsage {
3813 AbstractUsageInfo &Info;
3814 const NamedDecl *Ctx;
3815
3816 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3817 : Info(Info), Ctx(Ctx) {}
3818
3819 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3820 switch (TL.getTypeLocClass()) {
3821#define ABSTRACT_TYPELOC(CLASS, PARENT)
3822#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003823 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003824#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003825 }
John McCall94c3b562010-08-18 09:41:07 +00003826 }
Mike Stump1eb44332009-09-09 15:08:12 +00003827
John McCall94c3b562010-08-18 09:41:07 +00003828 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3829 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3830 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003831 if (!TL.getArg(I))
3832 continue;
3833
John McCall94c3b562010-08-18 09:41:07 +00003834 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3835 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003836 }
John McCall94c3b562010-08-18 09:41:07 +00003837 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003838
John McCall94c3b562010-08-18 09:41:07 +00003839 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3840 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3841 }
Mike Stump1eb44332009-09-09 15:08:12 +00003842
John McCall94c3b562010-08-18 09:41:07 +00003843 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3844 // Visit the type parameters from a permissive context.
3845 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3846 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3847 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3848 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3849 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3850 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003851 }
John McCall94c3b562010-08-18 09:41:07 +00003852 }
Mike Stump1eb44332009-09-09 15:08:12 +00003853
John McCall94c3b562010-08-18 09:41:07 +00003854 // Visit pointee types from a permissive context.
3855#define CheckPolymorphic(Type) \
3856 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3857 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3858 }
3859 CheckPolymorphic(PointerTypeLoc)
3860 CheckPolymorphic(ReferenceTypeLoc)
3861 CheckPolymorphic(MemberPointerTypeLoc)
3862 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003863 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003864
John McCall94c3b562010-08-18 09:41:07 +00003865 /// Handle all the types we haven't given a more specific
3866 /// implementation for above.
3867 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3868 // Every other kind of type that we haven't called out already
3869 // that has an inner type is either (1) sugar or (2) contains that
3870 // inner type in some way as a subobject.
3871 if (TypeLoc Next = TL.getNextTypeLoc())
3872 return Visit(Next, Sel);
3873
3874 // If there's no inner type and we're in a permissive context,
3875 // don't diagnose.
3876 if (Sel == Sema::AbstractNone) return;
3877
3878 // Check whether the type matches the abstract type.
3879 QualType T = TL.getType();
3880 if (T->isArrayType()) {
3881 Sel = Sema::AbstractArrayType;
3882 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003883 }
John McCall94c3b562010-08-18 09:41:07 +00003884 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3885 if (CT != Info.AbstractType) return;
3886
3887 // It matched; do some magic.
3888 if (Sel == Sema::AbstractArrayType) {
3889 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3890 << T << TL.getSourceRange();
3891 } else {
3892 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3893 << Sel << T << TL.getSourceRange();
3894 }
3895 Info.DiagnoseAbstractType();
3896 }
3897};
3898
3899void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3900 Sema::AbstractDiagSelID Sel) {
3901 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3902}
3903
3904}
3905
3906/// Check for invalid uses of an abstract type in a method declaration.
3907static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3908 CXXMethodDecl *MD) {
3909 // No need to do the check on definitions, which require that
3910 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003911 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003912 return;
3913
3914 // For safety's sake, just ignore it if we don't have type source
3915 // information. This should never happen for non-implicit methods,
3916 // but...
3917 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3918 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3919}
3920
3921/// Check for invalid uses of an abstract type within a class definition.
3922static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3923 CXXRecordDecl *RD) {
3924 for (CXXRecordDecl::decl_iterator
3925 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3926 Decl *D = *I;
3927 if (D->isImplicit()) continue;
3928
3929 // Methods and method templates.
3930 if (isa<CXXMethodDecl>(D)) {
3931 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3932 } else if (isa<FunctionTemplateDecl>(D)) {
3933 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3934 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3935
3936 // Fields and static variables.
3937 } else if (isa<FieldDecl>(D)) {
3938 FieldDecl *FD = cast<FieldDecl>(D);
3939 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3940 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3941 } else if (isa<VarDecl>(D)) {
3942 VarDecl *VD = cast<VarDecl>(D);
3943 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3944 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3945
3946 // Nested classes and class templates.
3947 } else if (isa<CXXRecordDecl>(D)) {
3948 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3949 } else if (isa<ClassTemplateDecl>(D)) {
3950 CheckAbstractClassUsage(Info,
3951 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3952 }
3953 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003954}
3955
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003956/// \brief Perform semantic checks on a class definition that has been
3957/// completing, introducing implicitly-declared members, checking for
3958/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003959void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003960 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003961 return;
3962
John McCall94c3b562010-08-18 09:41:07 +00003963 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3964 AbstractUsageInfo Info(*this, Record);
3965 CheckAbstractClassUsage(Info, Record);
3966 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003967
3968 // If this is not an aggregate type and has no user-declared constructor,
3969 // complain about any non-static data members of reference or const scalar
3970 // type, since they will never get initializers.
3971 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003972 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3973 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003974 bool Complained = false;
3975 for (RecordDecl::field_iterator F = Record->field_begin(),
3976 FEnd = Record->field_end();
3977 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003978 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003979 continue;
3980
Douglas Gregor325e5932010-04-15 00:00:53 +00003981 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003982 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003983 if (!Complained) {
3984 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3985 << Record->getTagKind() << Record;
3986 Complained = true;
3987 }
3988
3989 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3990 << F->getType()->isReferenceType()
3991 << F->getDeclName();
3992 }
3993 }
3994 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003995
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003996 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003997 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003998
3999 if (Record->getIdentifier()) {
4000 // C++ [class.mem]p13:
4001 // If T is the name of a class, then each of the following shall have a
4002 // name different from T:
4003 // - every member of every anonymous union that is a member of class T.
4004 //
4005 // C++ [class.mem]p14:
4006 // In addition, if class T has a user-declared constructor (12.1), every
4007 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004008 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4009 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4010 ++I) {
4011 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004012 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4013 isa<IndirectFieldDecl>(D)) {
4014 Diag(D->getLocation(), diag::err_member_name_of_class)
4015 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004016 break;
4017 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004018 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004019 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004020
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004021 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004022 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004023 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004024 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004025 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4026 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4027 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004028
David Blaikieb6b5b972012-09-21 03:21:07 +00004029 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4030 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4031 DiagnoseAbstractType(Record);
4032 }
4033
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004034 if (!Record->isDependentType()) {
4035 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4036 MEnd = Record->method_end();
4037 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004038 // See if a method overloads virtual methods in a base
4039 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004040 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004041 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004042
4043 // Check whether the explicitly-defaulted special members are valid.
4044 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4045 CheckExplicitlyDefaultedSpecialMember(*M);
4046
4047 // For an explicitly defaulted or deleted special member, we defer
4048 // determining triviality until the class is complete. That time is now!
4049 if (!M->isImplicit() && !M->isUserProvided()) {
4050 CXXSpecialMember CSM = getSpecialMember(*M);
4051 if (CSM != CXXInvalid) {
4052 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4053
4054 // Inform the class that we've finished declaring this member.
4055 Record->finishedDefaultedOrDeletedMember(*M);
4056 }
4057 }
4058 }
4059 }
4060
4061 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4062 // function that is not a constructor declares that member function to be
4063 // const. [...] The class of which that function is a member shall be
4064 // a literal type.
4065 //
4066 // If the class has virtual bases, any constexpr members will already have
4067 // been diagnosed by the checks performed on the member declaration, so
4068 // suppress this (less useful) diagnostic.
4069 //
4070 // We delay this until we know whether an explicitly-defaulted (or deleted)
4071 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004072 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004073 !Record->isLiteral() && !Record->getNumVBases()) {
4074 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4075 MEnd = Record->method_end();
4076 M != MEnd; ++M) {
4077 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4078 switch (Record->getTemplateSpecializationKind()) {
4079 case TSK_ImplicitInstantiation:
4080 case TSK_ExplicitInstantiationDeclaration:
4081 case TSK_ExplicitInstantiationDefinition:
4082 // If a template instantiates to a non-literal type, but its members
4083 // instantiate to constexpr functions, the template is technically
4084 // ill-formed, but we allow it for sanity.
4085 continue;
4086
4087 case TSK_Undeclared:
4088 case TSK_ExplicitSpecialization:
4089 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4090 diag::err_constexpr_method_non_literal);
4091 break;
4092 }
4093
4094 // Only produce one error per class.
4095 break;
4096 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004097 }
4098 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004099
Richard Smith07b0fdc2013-03-18 21:12:30 +00004100 // Declare inheriting constructors. We do this eagerly here because:
4101 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004102 // constructors from different classes.
4103 // - The lazy declaration of the other implicit constructors is so as to not
4104 // waste space and performance on classes that are not meant to be
4105 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004106 // have inheriting constructors.
4107 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004108}
4109
Richard Smith7756afa2012-06-10 05:43:50 +00004110/// Is the special member function which would be selected to perform the
4111/// specified operation on the specified class type a constexpr constructor?
4112static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4113 Sema::CXXSpecialMember CSM,
4114 bool ConstArg) {
4115 Sema::SpecialMemberOverloadResult *SMOR =
4116 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4117 false, false, false, false);
4118 if (!SMOR || !SMOR->getMethod())
4119 // A constructor we wouldn't select can't be "involved in initializing"
4120 // anything.
4121 return true;
4122 return SMOR->getMethod()->isConstexpr();
4123}
4124
4125/// Determine whether the specified special member function would be constexpr
4126/// if it were implicitly defined.
4127static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4128 Sema::CXXSpecialMember CSM,
4129 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004130 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004131 return false;
4132
4133 // C++11 [dcl.constexpr]p4:
4134 // In the definition of a constexpr constructor [...]
4135 switch (CSM) {
4136 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004137 // Since default constructor lookup is essentially trivial (and cannot
4138 // involve, for instance, template instantiation), we compute whether a
4139 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4140 //
4141 // This is important for performance; we need to know whether the default
4142 // constructor is constexpr to determine whether the type is a literal type.
4143 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4144
Richard Smith7756afa2012-06-10 05:43:50 +00004145 case Sema::CXXCopyConstructor:
4146 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004147 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004148 break;
4149
4150 case Sema::CXXCopyAssignment:
4151 case Sema::CXXMoveAssignment:
4152 case Sema::CXXDestructor:
4153 case Sema::CXXInvalid:
4154 return false;
4155 }
4156
4157 // -- if the class is a non-empty union, or for each non-empty anonymous
4158 // union member of a non-union class, exactly one non-static data member
4159 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004160 //
4161 // If we squint, this is guaranteed, since exactly one non-static data member
4162 // will be initialized (if the constructor isn't deleted), we just don't know
4163 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004164 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004165 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004166
4167 // -- the class shall not have any virtual base classes;
4168 if (ClassDecl->getNumVBases())
4169 return false;
4170
4171 // -- every constructor involved in initializing [...] base class
4172 // sub-objects shall be a constexpr constructor;
4173 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4174 BEnd = ClassDecl->bases_end();
4175 B != BEnd; ++B) {
4176 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4177 if (!BaseType) continue;
4178
4179 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4180 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4181 return false;
4182 }
4183
4184 // -- every constructor involved in initializing non-static data members
4185 // [...] shall be a constexpr constructor;
4186 // -- every non-static data member and base class sub-object shall be
4187 // initialized
4188 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4189 FEnd = ClassDecl->field_end();
4190 F != FEnd; ++F) {
4191 if (F->isInvalidDecl())
4192 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004193 if (const RecordType *RecordTy =
4194 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004195 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4196 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4197 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004198 }
4199 }
4200
4201 // All OK, it's constexpr!
4202 return true;
4203}
4204
Richard Smithb9d0b762012-07-27 04:22:15 +00004205static Sema::ImplicitExceptionSpecification
4206computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4207 switch (S.getSpecialMember(MD)) {
4208 case Sema::CXXDefaultConstructor:
4209 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4210 case Sema::CXXCopyConstructor:
4211 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4212 case Sema::CXXCopyAssignment:
4213 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4214 case Sema::CXXMoveConstructor:
4215 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4216 case Sema::CXXMoveAssignment:
4217 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4218 case Sema::CXXDestructor:
4219 return S.ComputeDefaultedDtorExceptionSpec(MD);
4220 case Sema::CXXInvalid:
4221 break;
4222 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004223 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4224 "only special members have implicit exception specs");
4225 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004226}
4227
Richard Smithdd25e802012-07-30 23:48:14 +00004228static void
4229updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4230 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4231 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4232 ExceptSpec.getEPI(EPI);
4233 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
Richard Smith07b0fdc2013-03-18 21:12:30 +00004234 S.Context.getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004235 FD->setType(QualType(NewFPT, 0));
4236}
4237
Richard Smithb9d0b762012-07-27 04:22:15 +00004238void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4239 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4240 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4241 return;
4242
Richard Smithdd25e802012-07-30 23:48:14 +00004243 // Evaluate the exception specification.
4244 ImplicitExceptionSpecification ExceptSpec =
4245 computeImplicitExceptionSpec(*this, Loc, MD);
4246
4247 // Update the type of the special member to use it.
4248 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4249
4250 // A user-provided destructor can be defined outside the class. When that
4251 // happens, be sure to update the exception specification on both
4252 // declarations.
4253 const FunctionProtoType *CanonicalFPT =
4254 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4255 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4256 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4257 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004258}
4259
Richard Smith3003e1d2012-05-15 04:39:51 +00004260void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4261 CXXRecordDecl *RD = MD->getParent();
4262 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004263
Richard Smith3003e1d2012-05-15 04:39:51 +00004264 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4265 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004266
4267 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004268 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004269 bool First = MD == MD->getCanonicalDecl();
4270
4271 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004272
4273 // C++11 [dcl.fct.def.default]p1:
4274 // A function that is explicitly defaulted shall
4275 // -- be a special member function (checked elsewhere),
4276 // -- have the same type (except for ref-qualifiers, and except that a
4277 // copy operation can take a non-const reference) as an implicit
4278 // declaration, and
4279 // -- not have default arguments.
4280 unsigned ExpectedParams = 1;
4281 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4282 ExpectedParams = 0;
4283 if (MD->getNumParams() != ExpectedParams) {
4284 // This also checks for default arguments: a copy or move constructor with a
4285 // default argument is classified as a default constructor, and assignment
4286 // operations and destructors can't have default arguments.
4287 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4288 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004289 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004290 } else if (MD->isVariadic()) {
4291 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4292 << CSM << MD->getSourceRange();
4293 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004294 }
4295
Richard Smith3003e1d2012-05-15 04:39:51 +00004296 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004297
Richard Smith7756afa2012-06-10 05:43:50 +00004298 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004299 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004300 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004301 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004302 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004303
Richard Smith3003e1d2012-05-15 04:39:51 +00004304 QualType ReturnType = Context.VoidTy;
4305 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4306 // Check for return type matching.
4307 ReturnType = Type->getResultType();
4308 QualType ExpectedReturnType =
4309 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4310 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4311 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4312 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4313 HadError = true;
4314 }
4315
4316 // A defaulted special member cannot have cv-qualifiers.
4317 if (Type->getTypeQuals()) {
4318 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4319 << (CSM == CXXMoveAssignment);
4320 HadError = true;
4321 }
4322 }
4323
4324 // Check for parameter type matching.
4325 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004326 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004327 if (ExpectedParams && ArgType->isReferenceType()) {
4328 // Argument must be reference to possibly-const T.
4329 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004330 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004331
4332 if (ReferentType.isVolatileQualified()) {
4333 Diag(MD->getLocation(),
4334 diag::err_defaulted_special_member_volatile_param) << CSM;
4335 HadError = true;
4336 }
4337
Richard Smith7756afa2012-06-10 05:43:50 +00004338 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004339 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4340 Diag(MD->getLocation(),
4341 diag::err_defaulted_special_member_copy_const_param)
4342 << (CSM == CXXCopyAssignment);
4343 // FIXME: Explain why this special member can't be const.
4344 } else {
4345 Diag(MD->getLocation(),
4346 diag::err_defaulted_special_member_move_const_param)
4347 << (CSM == CXXMoveAssignment);
4348 }
4349 HadError = true;
4350 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004351 } else if (ExpectedParams) {
4352 // A copy assignment operator can take its argument by value, but a
4353 // defaulted one cannot.
4354 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004355 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004356 HadError = true;
4357 }
Sean Huntbe631222011-05-17 20:44:43 +00004358
Richard Smith61802452011-12-22 02:22:31 +00004359 // C++11 [dcl.fct.def.default]p2:
4360 // An explicitly-defaulted function may be declared constexpr only if it
4361 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004362 // Do not apply this rule to members of class templates, since core issue 1358
4363 // makes such functions always instantiate to constexpr functions. For
4364 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004365 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4366 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004367 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4368 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4369 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004370 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004371 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004372 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004373
Richard Smith61802452011-12-22 02:22:31 +00004374 // and may have an explicit exception-specification only if it is compatible
4375 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004376 if (Type->hasExceptionSpec()) {
4377 // Delay the check if this is the first declaration of the special member,
4378 // since we may not have parsed some necessary in-class initializers yet.
4379 if (First)
4380 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4381 else
4382 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4383 }
Richard Smith61802452011-12-22 02:22:31 +00004384
4385 // If a function is explicitly defaulted on its first declaration,
4386 if (First) {
4387 // -- it is implicitly considered to be constexpr if the implicit
4388 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004389 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004390
Richard Smith3003e1d2012-05-15 04:39:51 +00004391 // -- it is implicitly considered to have the same exception-specification
4392 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004393 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4394 EPI.ExceptionSpecType = EST_Unevaluated;
4395 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004396 MD->setType(Context.getFunctionType(ReturnType,
4397 ArrayRef<QualType>(&ArgType,
4398 ExpectedParams),
4399 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004400 }
4401
Richard Smith3003e1d2012-05-15 04:39:51 +00004402 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004403 if (First) {
4404 MD->setDeletedAsWritten();
4405 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004406 // C++11 [dcl.fct.def.default]p4:
4407 // [For a] user-provided explicitly-defaulted function [...] if such a
4408 // function is implicitly defined as deleted, the program is ill-formed.
4409 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4410 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004411 }
4412 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004413
Richard Smith3003e1d2012-05-15 04:39:51 +00004414 if (HadError)
4415 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004416}
4417
Richard Smith1d28caf2012-12-11 01:14:52 +00004418/// Check whether the exception specification provided for an
4419/// explicitly-defaulted special member matches the exception specification
4420/// that would have been generated for an implicit special member, per
4421/// C++11 [dcl.fct.def.default]p2.
4422void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4423 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4424 // Compute the implicit exception specification.
4425 FunctionProtoType::ExtProtoInfo EPI;
4426 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4427 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Jordan Rosebea522f2013-03-08 21:51:21 +00004428 Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004429
4430 // Ensure that it matches.
4431 CheckEquivalentExceptionSpec(
4432 PDiag(diag::err_incorrect_defaulted_exception_spec)
4433 << getSpecialMember(MD), PDiag(),
4434 ImplicitType, SourceLocation(),
4435 SpecifiedType, MD->getLocation());
4436}
4437
4438void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4439 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4440 I != N; ++I)
4441 CheckExplicitlyDefaultedMemberExceptionSpec(
4442 DelayedDefaultedMemberExceptionSpecs[I].first,
4443 DelayedDefaultedMemberExceptionSpecs[I].second);
4444
4445 DelayedDefaultedMemberExceptionSpecs.clear();
4446}
4447
Richard Smith7d5088a2012-02-18 02:02:13 +00004448namespace {
4449struct SpecialMemberDeletionInfo {
4450 Sema &S;
4451 CXXMethodDecl *MD;
4452 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004453 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004454
4455 // Properties of the special member, computed for convenience.
4456 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4457 SourceLocation Loc;
4458
4459 bool AllFieldsAreConst;
4460
4461 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004462 Sema::CXXSpecialMember CSM, bool Diagnose)
4463 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004464 IsConstructor(false), IsAssignment(false), IsMove(false),
4465 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4466 AllFieldsAreConst(true) {
4467 switch (CSM) {
4468 case Sema::CXXDefaultConstructor:
4469 case Sema::CXXCopyConstructor:
4470 IsConstructor = true;
4471 break;
4472 case Sema::CXXMoveConstructor:
4473 IsConstructor = true;
4474 IsMove = true;
4475 break;
4476 case Sema::CXXCopyAssignment:
4477 IsAssignment = true;
4478 break;
4479 case Sema::CXXMoveAssignment:
4480 IsAssignment = true;
4481 IsMove = true;
4482 break;
4483 case Sema::CXXDestructor:
4484 break;
4485 case Sema::CXXInvalid:
4486 llvm_unreachable("invalid special member kind");
4487 }
4488
4489 if (MD->getNumParams()) {
4490 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4491 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4492 }
4493 }
4494
4495 bool inUnion() const { return MD->getParent()->isUnion(); }
4496
4497 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004498 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4499 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004500 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004501 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4502 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4503 Quals = 0;
4504 return S.LookupSpecialMember(Class, CSM,
4505 ConstArg || (Quals & Qualifiers::Const),
4506 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004507 MD->getRefQualifier() == RQ_RValue,
4508 TQ & Qualifiers::Const,
4509 TQ & Qualifiers::Volatile);
4510 }
4511
Richard Smith6c4c36c2012-03-30 20:53:28 +00004512 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004513
Richard Smith6c4c36c2012-03-30 20:53:28 +00004514 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004515 bool shouldDeleteForField(FieldDecl *FD);
4516 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004517
Richard Smith517bb842012-07-18 03:51:16 +00004518 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4519 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004520 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4521 Sema::SpecialMemberOverloadResult *SMOR,
4522 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004523
4524 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004525};
4526}
4527
John McCall12d8d802012-04-09 20:53:23 +00004528/// Is the given special member inaccessible when used on the given
4529/// sub-object.
4530bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4531 CXXMethodDecl *target) {
4532 /// If we're operating on a base class, the object type is the
4533 /// type of this special member.
4534 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004535 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004536 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4537 objectTy = S.Context.getTypeDeclType(MD->getParent());
4538 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4539
4540 // If we're operating on a field, the object type is the type of the field.
4541 } else {
4542 objectTy = S.Context.getTypeDeclType(target->getParent());
4543 }
4544
4545 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4546}
4547
Richard Smith6c4c36c2012-03-30 20:53:28 +00004548/// Check whether we should delete a special member due to the implicit
4549/// definition containing a call to a special member of a subobject.
4550bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4551 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4552 bool IsDtorCallInCtor) {
4553 CXXMethodDecl *Decl = SMOR->getMethod();
4554 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4555
4556 int DiagKind = -1;
4557
4558 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4559 DiagKind = !Decl ? 0 : 1;
4560 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4561 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004562 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004563 DiagKind = 3;
4564 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4565 !Decl->isTrivial()) {
4566 // A member of a union must have a trivial corresponding special member.
4567 // As a weird special case, a destructor call from a union's constructor
4568 // must be accessible and non-deleted, but need not be trivial. Such a
4569 // destructor is never actually called, but is semantically checked as
4570 // if it were.
4571 DiagKind = 4;
4572 }
4573
4574 if (DiagKind == -1)
4575 return false;
4576
4577 if (Diagnose) {
4578 if (Field) {
4579 S.Diag(Field->getLocation(),
4580 diag::note_deleted_special_member_class_subobject)
4581 << CSM << MD->getParent() << /*IsField*/true
4582 << Field << DiagKind << IsDtorCallInCtor;
4583 } else {
4584 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4585 S.Diag(Base->getLocStart(),
4586 diag::note_deleted_special_member_class_subobject)
4587 << CSM << MD->getParent() << /*IsField*/false
4588 << Base->getType() << DiagKind << IsDtorCallInCtor;
4589 }
4590
4591 if (DiagKind == 1)
4592 S.NoteDeletedFunction(Decl);
4593 // FIXME: Explain inaccessibility if DiagKind == 3.
4594 }
4595
4596 return true;
4597}
4598
Richard Smith9a561d52012-02-26 09:11:52 +00004599/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004600/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004601bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004602 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004603 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004604
4605 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004606 // -- any direct or virtual base class, or non-static data member with no
4607 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004608 // either M has no default constructor or overload resolution as applied
4609 // to M's default constructor results in an ambiguity or in a function
4610 // that is deleted or inaccessible
4611 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4612 // -- a direct or virtual base class B that cannot be copied/moved because
4613 // overload resolution, as applied to B's corresponding special member,
4614 // results in an ambiguity or a function that is deleted or inaccessible
4615 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004616 // C++11 [class.dtor]p5:
4617 // -- any direct or virtual base class [...] has a type with a destructor
4618 // that is deleted or inaccessible
4619 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004620 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004621 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004622 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004623
Richard Smith6c4c36c2012-03-30 20:53:28 +00004624 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4625 // -- any direct or virtual base class or non-static data member has a
4626 // type with a destructor that is deleted or inaccessible
4627 if (IsConstructor) {
4628 Sema::SpecialMemberOverloadResult *SMOR =
4629 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4630 false, false, false, false, false);
4631 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4632 return true;
4633 }
4634
Richard Smith9a561d52012-02-26 09:11:52 +00004635 return false;
4636}
4637
4638/// Check whether we should delete a special member function due to the class
4639/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004640bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004641 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004642 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004643}
4644
4645/// Check whether we should delete a special member function due to the class
4646/// having a particular non-static data member.
4647bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4648 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4649 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4650
4651 if (CSM == Sema::CXXDefaultConstructor) {
4652 // For a default constructor, all references must be initialized in-class
4653 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004654 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4655 if (Diagnose)
4656 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4657 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004658 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004659 }
Richard Smith79363f52012-02-27 06:07:25 +00004660 // C++11 [class.ctor]p5: any non-variant non-static data member of
4661 // const-qualified type (or array thereof) with no
4662 // brace-or-equal-initializer does not have a user-provided default
4663 // constructor.
4664 if (!inUnion() && FieldType.isConstQualified() &&
4665 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004666 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4667 if (Diagnose)
4668 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004669 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004670 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004671 }
4672
4673 if (inUnion() && !FieldType.isConstQualified())
4674 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004675 } else if (CSM == Sema::CXXCopyConstructor) {
4676 // For a copy constructor, data members must not be of rvalue reference
4677 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004678 if (FieldType->isRValueReferenceType()) {
4679 if (Diagnose)
4680 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4681 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004682 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004683 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004684 } else if (IsAssignment) {
4685 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004686 if (FieldType->isReferenceType()) {
4687 if (Diagnose)
4688 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4689 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004690 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004691 }
4692 if (!FieldRecord && FieldType.isConstQualified()) {
4693 // C++11 [class.copy]p23:
4694 // -- a non-static data member of const non-class type (or array thereof)
4695 if (Diagnose)
4696 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004697 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004698 return true;
4699 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004700 }
4701
4702 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004703 // Some additional restrictions exist on the variant members.
4704 if (!inUnion() && FieldRecord->isUnion() &&
4705 FieldRecord->isAnonymousStructOrUnion()) {
4706 bool AllVariantFieldsAreConst = true;
4707
Richard Smithdf8dc862012-03-29 19:00:10 +00004708 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004709 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4710 UE = FieldRecord->field_end();
4711 UI != UE; ++UI) {
4712 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004713
4714 if (!UnionFieldType.isConstQualified())
4715 AllVariantFieldsAreConst = false;
4716
Richard Smith9a561d52012-02-26 09:11:52 +00004717 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4718 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004719 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4720 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004721 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004722 }
4723
4724 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004725 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004726 FieldRecord->field_begin() != FieldRecord->field_end()) {
4727 if (Diagnose)
4728 S.Diag(FieldRecord->getLocation(),
4729 diag::note_deleted_default_ctor_all_const)
4730 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004731 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004732 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004733
Richard Smithdf8dc862012-03-29 19:00:10 +00004734 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004735 // This is technically non-conformant, but sanity demands it.
4736 return false;
4737 }
4738
Richard Smith517bb842012-07-18 03:51:16 +00004739 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4740 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004741 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004742 }
4743
4744 return false;
4745}
4746
4747/// C++11 [class.ctor] p5:
4748/// A defaulted default constructor for a class X is defined as deleted if
4749/// X is a union and all of its variant members are of const-qualified type.
4750bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004751 // This is a silly definition, because it gives an empty union a deleted
4752 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004753 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4754 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4755 if (Diagnose)
4756 S.Diag(MD->getParent()->getLocation(),
4757 diag::note_deleted_default_ctor_all_const)
4758 << MD->getParent() << /*not anonymous union*/0;
4759 return true;
4760 }
4761 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004762}
4763
4764/// Determine whether a defaulted special member function should be defined as
4765/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4766/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004767bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4768 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004769 if (MD->isInvalidDecl())
4770 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004771 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004772 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004773 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004774 return false;
4775
Richard Smith7d5088a2012-02-18 02:02:13 +00004776 // C++11 [expr.lambda.prim]p19:
4777 // The closure type associated with a lambda-expression has a
4778 // deleted (8.4.3) default constructor and a deleted copy
4779 // assignment operator.
4780 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004781 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4782 if (Diagnose)
4783 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004784 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004785 }
4786
Richard Smith5bdaac52012-04-02 20:59:25 +00004787 // For an anonymous struct or union, the copy and assignment special members
4788 // will never be used, so skip the check. For an anonymous union declared at
4789 // namespace scope, the constructor and destructor are used.
4790 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4791 RD->isAnonymousStructOrUnion())
4792 return false;
4793
Richard Smith6c4c36c2012-03-30 20:53:28 +00004794 // C++11 [class.copy]p7, p18:
4795 // If the class definition declares a move constructor or move assignment
4796 // operator, an implicitly declared copy constructor or copy assignment
4797 // operator is defined as deleted.
4798 if (MD->isImplicit() &&
4799 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4800 CXXMethodDecl *UserDeclaredMove = 0;
4801
4802 // In Microsoft mode, a user-declared move only causes the deletion of the
4803 // corresponding copy operation, not both copy operations.
4804 if (RD->hasUserDeclaredMoveConstructor() &&
4805 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4806 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004807
4808 // Find any user-declared move constructor.
4809 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4810 E = RD->ctor_end(); I != E; ++I) {
4811 if (I->isMoveConstructor()) {
4812 UserDeclaredMove = *I;
4813 break;
4814 }
4815 }
Richard Smith1c931be2012-04-02 18:40:40 +00004816 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004817 } else if (RD->hasUserDeclaredMoveAssignment() &&
4818 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4819 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004820
4821 // Find any user-declared move assignment operator.
4822 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4823 E = RD->method_end(); I != E; ++I) {
4824 if (I->isMoveAssignmentOperator()) {
4825 UserDeclaredMove = *I;
4826 break;
4827 }
4828 }
Richard Smith1c931be2012-04-02 18:40:40 +00004829 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004830 }
4831
4832 if (UserDeclaredMove) {
4833 Diag(UserDeclaredMove->getLocation(),
4834 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004835 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004836 << UserDeclaredMove->isMoveAssignmentOperator();
4837 return true;
4838 }
4839 }
Sean Hunte16da072011-10-10 06:18:57 +00004840
Richard Smith5bdaac52012-04-02 20:59:25 +00004841 // Do access control from the special member function
4842 ContextRAII MethodContext(*this, MD);
4843
Richard Smith9a561d52012-02-26 09:11:52 +00004844 // C++11 [class.dtor]p5:
4845 // -- for a virtual destructor, lookup of the non-array deallocation function
4846 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004847 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004848 FunctionDecl *OperatorDelete = 0;
4849 DeclarationName Name =
4850 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4851 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004852 OperatorDelete, false)) {
4853 if (Diagnose)
4854 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004855 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004856 }
Richard Smith9a561d52012-02-26 09:11:52 +00004857 }
4858
Richard Smith6c4c36c2012-03-30 20:53:28 +00004859 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004860
Sean Huntcdee3fe2011-05-11 22:34:38 +00004861 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004862 BE = RD->bases_end(); BI != BE; ++BI)
4863 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004864 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004865 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004866
4867 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004868 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004869 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004870 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004871
4872 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004873 FE = RD->field_end(); FI != FE; ++FI)
4874 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004875 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004876 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004877
Richard Smith7d5088a2012-02-18 02:02:13 +00004878 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004879 return true;
4880
4881 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004882}
4883
Richard Smithac713512012-12-08 02:53:02 +00004884/// Perform lookup for a special member of the specified kind, and determine
4885/// whether it is trivial. If the triviality can be determined without the
4886/// lookup, skip it. This is intended for use when determining whether a
4887/// special member of a containing object is trivial, and thus does not ever
4888/// perform overload resolution for default constructors.
4889///
4890/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4891/// member that was most likely to be intended to be trivial, if any.
4892static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4893 Sema::CXXSpecialMember CSM, unsigned Quals,
4894 CXXMethodDecl **Selected) {
4895 if (Selected)
4896 *Selected = 0;
4897
4898 switch (CSM) {
4899 case Sema::CXXInvalid:
4900 llvm_unreachable("not a special member");
4901
4902 case Sema::CXXDefaultConstructor:
4903 // C++11 [class.ctor]p5:
4904 // A default constructor is trivial if:
4905 // - all the [direct subobjects] have trivial default constructors
4906 //
4907 // Note, no overload resolution is performed in this case.
4908 if (RD->hasTrivialDefaultConstructor())
4909 return true;
4910
4911 if (Selected) {
4912 // If there's a default constructor which could have been trivial, dig it
4913 // out. Otherwise, if there's any user-provided default constructor, point
4914 // to that as an example of why there's not a trivial one.
4915 CXXConstructorDecl *DefCtor = 0;
4916 if (RD->needsImplicitDefaultConstructor())
4917 S.DeclareImplicitDefaultConstructor(RD);
4918 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4919 CE = RD->ctor_end(); CI != CE; ++CI) {
4920 if (!CI->isDefaultConstructor())
4921 continue;
4922 DefCtor = *CI;
4923 if (!DefCtor->isUserProvided())
4924 break;
4925 }
4926
4927 *Selected = DefCtor;
4928 }
4929
4930 return false;
4931
4932 case Sema::CXXDestructor:
4933 // C++11 [class.dtor]p5:
4934 // A destructor is trivial if:
4935 // - all the direct [subobjects] have trivial destructors
4936 if (RD->hasTrivialDestructor())
4937 return true;
4938
4939 if (Selected) {
4940 if (RD->needsImplicitDestructor())
4941 S.DeclareImplicitDestructor(RD);
4942 *Selected = RD->getDestructor();
4943 }
4944
4945 return false;
4946
4947 case Sema::CXXCopyConstructor:
4948 // C++11 [class.copy]p12:
4949 // A copy constructor is trivial if:
4950 // - the constructor selected to copy each direct [subobject] is trivial
4951 if (RD->hasTrivialCopyConstructor()) {
4952 if (Quals == Qualifiers::Const)
4953 // We must either select the trivial copy constructor or reach an
4954 // ambiguity; no need to actually perform overload resolution.
4955 return true;
4956 } else if (!Selected) {
4957 return false;
4958 }
4959 // In C++98, we are not supposed to perform overload resolution here, but we
4960 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4961 // cases like B as having a non-trivial copy constructor:
4962 // struct A { template<typename T> A(T&); };
4963 // struct B { mutable A a; };
4964 goto NeedOverloadResolution;
4965
4966 case Sema::CXXCopyAssignment:
4967 // C++11 [class.copy]p25:
4968 // A copy assignment operator is trivial if:
4969 // - the assignment operator selected to copy each direct [subobject] is
4970 // trivial
4971 if (RD->hasTrivialCopyAssignment()) {
4972 if (Quals == Qualifiers::Const)
4973 return true;
4974 } else if (!Selected) {
4975 return false;
4976 }
4977 // In C++98, we are not supposed to perform overload resolution here, but we
4978 // treat that as a language defect.
4979 goto NeedOverloadResolution;
4980
4981 case Sema::CXXMoveConstructor:
4982 case Sema::CXXMoveAssignment:
4983 NeedOverloadResolution:
4984 Sema::SpecialMemberOverloadResult *SMOR =
4985 S.LookupSpecialMember(RD, CSM,
4986 Quals & Qualifiers::Const,
4987 Quals & Qualifiers::Volatile,
4988 /*RValueThis*/false, /*ConstThis*/false,
4989 /*VolatileThis*/false);
4990
4991 // The standard doesn't describe how to behave if the lookup is ambiguous.
4992 // We treat it as not making the member non-trivial, just like the standard
4993 // mandates for the default constructor. This should rarely matter, because
4994 // the member will also be deleted.
4995 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4996 return true;
4997
4998 if (!SMOR->getMethod()) {
4999 assert(SMOR->getKind() ==
5000 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5001 return false;
5002 }
5003
5004 // We deliberately don't check if we found a deleted special member. We're
5005 // not supposed to!
5006 if (Selected)
5007 *Selected = SMOR->getMethod();
5008 return SMOR->getMethod()->isTrivial();
5009 }
5010
5011 llvm_unreachable("unknown special method kind");
5012}
5013
Benjamin Kramera574c892013-02-15 12:30:38 +00005014static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005015 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5016 CI != CE; ++CI)
5017 if (!CI->isImplicit())
5018 return *CI;
5019
5020 // Look for constructor templates.
5021 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5022 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5023 if (CXXConstructorDecl *CD =
5024 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5025 return CD;
5026 }
5027
5028 return 0;
5029}
5030
5031/// The kind of subobject we are checking for triviality. The values of this
5032/// enumeration are used in diagnostics.
5033enum TrivialSubobjectKind {
5034 /// The subobject is a base class.
5035 TSK_BaseClass,
5036 /// The subobject is a non-static data member.
5037 TSK_Field,
5038 /// The object is actually the complete object.
5039 TSK_CompleteObject
5040};
5041
5042/// Check whether the special member selected for a given type would be trivial.
5043static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5044 QualType SubType,
5045 Sema::CXXSpecialMember CSM,
5046 TrivialSubobjectKind Kind,
5047 bool Diagnose) {
5048 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5049 if (!SubRD)
5050 return true;
5051
5052 CXXMethodDecl *Selected;
5053 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5054 Diagnose ? &Selected : 0))
5055 return true;
5056
5057 if (Diagnose) {
5058 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5059 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5060 << Kind << SubType.getUnqualifiedType();
5061 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5062 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5063 } else if (!Selected)
5064 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5065 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5066 else if (Selected->isUserProvided()) {
5067 if (Kind == TSK_CompleteObject)
5068 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5069 << Kind << SubType.getUnqualifiedType() << CSM;
5070 else {
5071 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5072 << Kind << SubType.getUnqualifiedType() << CSM;
5073 S.Diag(Selected->getLocation(), diag::note_declared_at);
5074 }
5075 } else {
5076 if (Kind != TSK_CompleteObject)
5077 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5078 << Kind << SubType.getUnqualifiedType() << CSM;
5079
5080 // Explain why the defaulted or deleted special member isn't trivial.
5081 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5082 }
5083 }
5084
5085 return false;
5086}
5087
5088/// Check whether the members of a class type allow a special member to be
5089/// trivial.
5090static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5091 Sema::CXXSpecialMember CSM,
5092 bool ConstArg, bool Diagnose) {
5093 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5094 FE = RD->field_end(); FI != FE; ++FI) {
5095 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5096 continue;
5097
5098 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5099
5100 // Pretend anonymous struct or union members are members of this class.
5101 if (FI->isAnonymousStructOrUnion()) {
5102 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5103 CSM, ConstArg, Diagnose))
5104 return false;
5105 continue;
5106 }
5107
5108 // C++11 [class.ctor]p5:
5109 // A default constructor is trivial if [...]
5110 // -- no non-static data member of its class has a
5111 // brace-or-equal-initializer
5112 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5113 if (Diagnose)
5114 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5115 return false;
5116 }
5117
5118 // Objective C ARC 4.3.5:
5119 // [...] nontrivally ownership-qualified types are [...] not trivially
5120 // default constructible, copy constructible, move constructible, copy
5121 // assignable, move assignable, or destructible [...]
5122 if (S.getLangOpts().ObjCAutoRefCount &&
5123 FieldType.hasNonTrivialObjCLifetime()) {
5124 if (Diagnose)
5125 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5126 << RD << FieldType.getObjCLifetime();
5127 return false;
5128 }
5129
5130 if (ConstArg && !FI->isMutable())
5131 FieldType.addConst();
5132 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5133 TSK_Field, Diagnose))
5134 return false;
5135 }
5136
5137 return true;
5138}
5139
5140/// Diagnose why the specified class does not have a trivial special member of
5141/// the given kind.
5142void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5143 QualType Ty = Context.getRecordType(RD);
5144 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5145 Ty.addConst();
5146
5147 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5148 TSK_CompleteObject, /*Diagnose*/true);
5149}
5150
5151/// Determine whether a defaulted or deleted special member function is trivial,
5152/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5153/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5154bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5155 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005156 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5157
5158 CXXRecordDecl *RD = MD->getParent();
5159
5160 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005161
5162 // C++11 [class.copy]p12, p25:
5163 // A [special member] is trivial if its declared parameter type is the same
5164 // as if it had been implicitly declared [...]
5165 switch (CSM) {
5166 case CXXDefaultConstructor:
5167 case CXXDestructor:
5168 // Trivial default constructors and destructors cannot have parameters.
5169 break;
5170
5171 case CXXCopyConstructor:
5172 case CXXCopyAssignment: {
5173 // Trivial copy operations always have const, non-volatile parameter types.
5174 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005175 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005176 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5177 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5178 if (Diagnose)
5179 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5180 << Param0->getSourceRange() << Param0->getType()
5181 << Context.getLValueReferenceType(
5182 Context.getRecordType(RD).withConst());
5183 return false;
5184 }
5185 break;
5186 }
5187
5188 case CXXMoveConstructor:
5189 case CXXMoveAssignment: {
5190 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005191 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005192 const RValueReferenceType *RT =
5193 Param0->getType()->getAs<RValueReferenceType>();
5194 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5195 if (Diagnose)
5196 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5197 << Param0->getSourceRange() << Param0->getType()
5198 << Context.getRValueReferenceType(Context.getRecordType(RD));
5199 return false;
5200 }
5201 break;
5202 }
5203
5204 case CXXInvalid:
5205 llvm_unreachable("not a special member");
5206 }
5207
5208 // FIXME: We require that the parameter-declaration-clause is equivalent to
5209 // that of an implicit declaration, not just that the declared parameter type
5210 // matches, in order to prevent absuridities like a function simultaneously
5211 // being a trivial copy constructor and a non-trivial default constructor.
5212 // This issue has not yet been assigned a core issue number.
5213 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5214 if (Diagnose)
5215 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5216 diag::note_nontrivial_default_arg)
5217 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5218 return false;
5219 }
5220 if (MD->isVariadic()) {
5221 if (Diagnose)
5222 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5223 return false;
5224 }
5225
5226 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5227 // A copy/move [constructor or assignment operator] is trivial if
5228 // -- the [member] selected to copy/move each direct base class subobject
5229 // is trivial
5230 //
5231 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5232 // A [default constructor or destructor] is trivial if
5233 // -- all the direct base classes have trivial [default constructors or
5234 // destructors]
5235 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5236 BE = RD->bases_end(); BI != BE; ++BI)
5237 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5238 ConstArg ? BI->getType().withConst()
5239 : BI->getType(),
5240 CSM, TSK_BaseClass, Diagnose))
5241 return false;
5242
5243 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5244 // A copy/move [constructor or assignment operator] for a class X is
5245 // trivial if
5246 // -- for each non-static data member of X that is of class type (or array
5247 // thereof), the constructor selected to copy/move that member is
5248 // trivial
5249 //
5250 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5251 // A [default constructor or destructor] is trivial if
5252 // -- for all of the non-static data members of its class that are of class
5253 // type (or array thereof), each such class has a trivial [default
5254 // constructor or destructor]
5255 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5256 return false;
5257
5258 // C++11 [class.dtor]p5:
5259 // A destructor is trivial if [...]
5260 // -- the destructor is not virtual
5261 if (CSM == CXXDestructor && MD->isVirtual()) {
5262 if (Diagnose)
5263 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5264 return false;
5265 }
5266
5267 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5268 // A [special member] for class X is trivial if [...]
5269 // -- class X has no virtual functions and no virtual base classes
5270 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5271 if (!Diagnose)
5272 return false;
5273
5274 if (RD->getNumVBases()) {
5275 // Check for virtual bases. We already know that the corresponding
5276 // member in all bases is trivial, so vbases must all be direct.
5277 CXXBaseSpecifier &BS = *RD->vbases_begin();
5278 assert(BS.isVirtual());
5279 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5280 return false;
5281 }
5282
5283 // Must have a virtual method.
5284 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5285 ME = RD->method_end(); MI != ME; ++MI) {
5286 if (MI->isVirtual()) {
5287 SourceLocation MLoc = MI->getLocStart();
5288 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5289 return false;
5290 }
5291 }
5292
5293 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5294 }
5295
5296 // Looks like it's trivial!
5297 return true;
5298}
5299
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005300/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005301namespace {
5302 struct FindHiddenVirtualMethodData {
5303 Sema *S;
5304 CXXMethodDecl *Method;
5305 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005306 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005307 };
5308}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005309
David Blaikie5f750682012-10-19 00:53:08 +00005310/// \brief Check whether any most overriden method from MD in Methods
5311static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5312 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5313 if (MD->size_overridden_methods() == 0)
5314 return Methods.count(MD->getCanonicalDecl());
5315 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5316 E = MD->end_overridden_methods();
5317 I != E; ++I)
5318 if (CheckMostOverridenMethods(*I, Methods))
5319 return true;
5320 return false;
5321}
5322
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005323/// \brief Member lookup function that determines whether a given C++
5324/// method overloads virtual methods in a base class without overriding any,
5325/// to be used with CXXRecordDecl::lookupInBases().
5326static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5327 CXXBasePath &Path,
5328 void *UserData) {
5329 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5330
5331 FindHiddenVirtualMethodData &Data
5332 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5333
5334 DeclarationName Name = Data.Method->getDeclName();
5335 assert(Name.getNameKind() == DeclarationName::Identifier);
5336
5337 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005338 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005339 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005340 !Path.Decls.empty();
5341 Path.Decls = Path.Decls.slice(1)) {
5342 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005343 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005344 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005345 foundSameNameMethod = true;
5346 // Interested only in hidden virtual methods.
5347 if (!MD->isVirtual())
5348 continue;
5349 // If the method we are checking overrides a method from its base
5350 // don't warn about the other overloaded methods.
5351 if (!Data.S->IsOverload(Data.Method, MD, false))
5352 return true;
5353 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005354 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005355 overloadedMethods.push_back(MD);
5356 }
5357 }
5358
5359 if (foundSameNameMethod)
5360 Data.OverloadedMethods.append(overloadedMethods.begin(),
5361 overloadedMethods.end());
5362 return foundSameNameMethod;
5363}
5364
David Blaikie5f750682012-10-19 00:53:08 +00005365/// \brief Add the most overriden methods from MD to Methods
5366static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5367 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5368 if (MD->size_overridden_methods() == 0)
5369 Methods.insert(MD->getCanonicalDecl());
5370 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5371 E = MD->end_overridden_methods();
5372 I != E; ++I)
5373 AddMostOverridenMethods(*I, Methods);
5374}
5375
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005376/// \brief See if a method overloads virtual methods in a base class without
5377/// overriding any.
5378void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5379 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005380 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005381 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005382 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005383 return;
5384
5385 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5386 /*bool RecordPaths=*/false,
5387 /*bool DetectVirtual=*/false);
5388 FindHiddenVirtualMethodData Data;
5389 Data.Method = MD;
5390 Data.S = this;
5391
5392 // Keep the base methods that were overriden or introduced in the subclass
5393 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005394 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5395 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5396 NamedDecl *ND = *I;
5397 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005398 ND = shad->getTargetDecl();
5399 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5400 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005401 }
5402
5403 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5404 !Data.OverloadedMethods.empty()) {
5405 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5406 << MD << (Data.OverloadedMethods.size() > 1);
5407
5408 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5409 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5410 Diag(overloadedMD->getLocation(),
5411 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5412 }
5413 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005414}
5415
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005416void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005417 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005418 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005419 SourceLocation RBrac,
5420 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005421 if (!TagDecl)
5422 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005423
Douglas Gregor42af25f2009-05-11 19:58:34 +00005424 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005425
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005426 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5427 if (l->getKind() != AttributeList::AT_Visibility)
5428 continue;
5429 l->setInvalid();
5430 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5431 l->getName();
5432 }
5433
David Blaikie77b6de02011-09-22 02:58:26 +00005434 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005435 // strict aliasing violation!
5436 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005437 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005438
Douglas Gregor23c94db2010-07-02 17:43:08 +00005439 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005440 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005441}
5442
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005443/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5444/// special functions, such as the default constructor, copy
5445/// constructor, or destructor, to the given C++ class (C++
5446/// [special]p1). This routine can only be executed just before the
5447/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005448void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005449 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005450 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005451
Richard Smithbc2a35d2012-12-08 08:32:28 +00005452 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005453 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005454
Richard Smithbc2a35d2012-12-08 08:32:28 +00005455 // If the properties or semantics of the copy constructor couldn't be
5456 // determined while the class was being declared, force a declaration
5457 // of it now.
5458 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5459 DeclareImplicitCopyConstructor(ClassDecl);
5460 }
5461
Richard Smith80ad52f2013-01-02 11:42:31 +00005462 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005463 ++ASTContext::NumImplicitMoveConstructors;
5464
Richard Smithbc2a35d2012-12-08 08:32:28 +00005465 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5466 DeclareImplicitMoveConstructor(ClassDecl);
5467 }
5468
Douglas Gregora376d102010-07-02 21:50:04 +00005469 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5470 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005471
5472 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005473 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005474 // it shows up in the right place in the vtable and that we diagnose
5475 // problems with the implicit exception specification.
5476 if (ClassDecl->isDynamicClass() ||
5477 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005478 DeclareImplicitCopyAssignment(ClassDecl);
5479 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005480
Richard Smith80ad52f2013-01-02 11:42:31 +00005481 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005482 ++ASTContext::NumImplicitMoveAssignmentOperators;
5483
5484 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005485 if (ClassDecl->isDynamicClass() ||
5486 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005487 DeclareImplicitMoveAssignment(ClassDecl);
5488 }
5489
Douglas Gregor4923aa22010-07-02 20:37:36 +00005490 if (!ClassDecl->hasUserDeclaredDestructor()) {
5491 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005492
5493 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005494 // have to declare the destructor immediately. This ensures that, e.g., it
5495 // shows up in the right place in the vtable and that we diagnose problems
5496 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005497 if (ClassDecl->isDynamicClass() ||
5498 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005499 DeclareImplicitDestructor(ClassDecl);
5500 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005501}
5502
Francois Pichet8387e2a2011-04-22 22:18:13 +00005503void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5504 if (!D)
5505 return;
5506
5507 int NumParamList = D->getNumTemplateParameterLists();
5508 for (int i = 0; i < NumParamList; i++) {
5509 TemplateParameterList* Params = D->getTemplateParameterList(i);
5510 for (TemplateParameterList::iterator Param = Params->begin(),
5511 ParamEnd = Params->end();
5512 Param != ParamEnd; ++Param) {
5513 NamedDecl *Named = cast<NamedDecl>(*Param);
5514 if (Named->getDeclName()) {
5515 S->AddDecl(Named);
5516 IdResolver.AddDecl(Named);
5517 }
5518 }
5519 }
5520}
5521
John McCalld226f652010-08-21 09:40:31 +00005522void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005523 if (!D)
5524 return;
5525
5526 TemplateParameterList *Params = 0;
5527 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5528 Params = Template->getTemplateParameters();
5529 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5530 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5531 Params = PartialSpec->getTemplateParameters();
5532 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005533 return;
5534
Douglas Gregor6569d682009-05-27 23:11:45 +00005535 for (TemplateParameterList::iterator Param = Params->begin(),
5536 ParamEnd = Params->end();
5537 Param != ParamEnd; ++Param) {
5538 NamedDecl *Named = cast<NamedDecl>(*Param);
5539 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005540 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005541 IdResolver.AddDecl(Named);
5542 }
5543 }
5544}
5545
John McCalld226f652010-08-21 09:40:31 +00005546void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005547 if (!RecordD) return;
5548 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005549 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005550 PushDeclContext(S, Record);
5551}
5552
John McCalld226f652010-08-21 09:40:31 +00005553void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005554 if (!RecordD) return;
5555 PopDeclContext();
5556}
5557
Douglas Gregor72b505b2008-12-16 21:30:33 +00005558/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5559/// parsing a top-level (non-nested) C++ class, and we are now
5560/// parsing those parts of the given Method declaration that could
5561/// not be parsed earlier (C++ [class.mem]p2), such as default
5562/// arguments. This action should enter the scope of the given
5563/// Method declaration as if we had just parsed the qualified method
5564/// name. However, it should not bring the parameters into scope;
5565/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005566void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005567}
5568
5569/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5570/// C++ method declaration. We're (re-)introducing the given
5571/// function parameter into scope for use in parsing later parts of
5572/// the method declaration. For example, we could see an
5573/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005574void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005575 if (!ParamD)
5576 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005577
John McCalld226f652010-08-21 09:40:31 +00005578 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005579
5580 // If this parameter has an unparsed default argument, clear it out
5581 // to make way for the parsed default argument.
5582 if (Param->hasUnparsedDefaultArg())
5583 Param->setDefaultArg(0);
5584
John McCalld226f652010-08-21 09:40:31 +00005585 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005586 if (Param->getDeclName())
5587 IdResolver.AddDecl(Param);
5588}
5589
5590/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5591/// processing the delayed method declaration for Method. The method
5592/// declaration is now considered finished. There may be a separate
5593/// ActOnStartOfFunctionDef action later (not necessarily
5594/// immediately!) for this method, if it was also defined inside the
5595/// class body.
John McCalld226f652010-08-21 09:40:31 +00005596void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005597 if (!MethodD)
5598 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005599
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005600 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005601
John McCalld226f652010-08-21 09:40:31 +00005602 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005603
5604 // Now that we have our default arguments, check the constructor
5605 // again. It could produce additional diagnostics or affect whether
5606 // the class has implicitly-declared destructors, among other
5607 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005608 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5609 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005610
5611 // Check the default arguments, which we may have added.
5612 if (!Method->isInvalidDecl())
5613 CheckCXXDefaultArguments(Method);
5614}
5615
Douglas Gregor42a552f2008-11-05 20:51:48 +00005616/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005617/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005618/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005619/// emit diagnostics and set the invalid bit to true. In any case, the type
5620/// will be updated to reflect a well-formed type for the constructor and
5621/// returned.
5622QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005623 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005624 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005625
5626 // C++ [class.ctor]p3:
5627 // A constructor shall not be virtual (10.3) or static (9.4). A
5628 // constructor can be invoked for a const, volatile or const
5629 // volatile object. A constructor shall not be declared const,
5630 // volatile, or const volatile (9.3.2).
5631 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005632 if (!D.isInvalidType())
5633 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5634 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5635 << SourceRange(D.getIdentifierLoc());
5636 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005637 }
John McCalld931b082010-08-26 03:08:43 +00005638 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005639 if (!D.isInvalidType())
5640 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5641 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5642 << SourceRange(D.getIdentifierLoc());
5643 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005644 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005645 }
Mike Stump1eb44332009-09-09 15:08:12 +00005646
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005647 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005648 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005649 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005650 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5651 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005652 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005653 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5654 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005655 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005656 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5657 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005658 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005659 }
Mike Stump1eb44332009-09-09 15:08:12 +00005660
Douglas Gregorc938c162011-01-26 05:01:58 +00005661 // C++0x [class.ctor]p4:
5662 // A constructor shall not be declared with a ref-qualifier.
5663 if (FTI.hasRefQualifier()) {
5664 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5665 << FTI.RefQualifierIsLValueRef
5666 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5667 D.setInvalidType();
5668 }
5669
Douglas Gregor42a552f2008-11-05 20:51:48 +00005670 // Rebuild the function type "R" without any type qualifiers (in
5671 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005672 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005673 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005674 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5675 return R;
5676
5677 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5678 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005679 EPI.RefQualifier = RQ_None;
5680
Richard Smith07b0fdc2013-03-18 21:12:30 +00005681 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005682}
5683
Douglas Gregor72b505b2008-12-16 21:30:33 +00005684/// CheckConstructor - Checks a fully-formed constructor for
5685/// well-formedness, issuing any diagnostics required. Returns true if
5686/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005687void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005688 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005689 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5690 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005691 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005692
5693 // C++ [class.copy]p3:
5694 // A declaration of a constructor for a class X is ill-formed if
5695 // its first parameter is of type (optionally cv-qualified) X and
5696 // either there are no other parameters or else all other
5697 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005698 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005699 ((Constructor->getNumParams() == 1) ||
5700 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005701 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5702 Constructor->getTemplateSpecializationKind()
5703 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005704 QualType ParamType = Constructor->getParamDecl(0)->getType();
5705 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5706 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005707 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005708 const char *ConstRef
5709 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5710 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005711 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005712 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005713
5714 // FIXME: Rather that making the constructor invalid, we should endeavor
5715 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005716 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005717 }
5718 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005719}
5720
John McCall15442822010-08-04 01:04:25 +00005721/// CheckDestructor - Checks a fully-formed destructor definition for
5722/// well-formedness, issuing any diagnostics required. Returns true
5723/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005724bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005725 CXXRecordDecl *RD = Destructor->getParent();
5726
5727 if (Destructor->isVirtual()) {
5728 SourceLocation Loc;
5729
5730 if (!Destructor->isImplicit())
5731 Loc = Destructor->getLocation();
5732 else
5733 Loc = RD->getLocation();
5734
5735 // If we have a virtual destructor, look up the deallocation function
5736 FunctionDecl *OperatorDelete = 0;
5737 DeclarationName Name =
5738 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005739 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005740 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005741
Eli Friedman5f2987c2012-02-02 03:46:19 +00005742 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005743
5744 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005745 }
Anders Carlsson37909802009-11-30 21:24:50 +00005746
5747 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005748}
5749
Mike Stump1eb44332009-09-09 15:08:12 +00005750static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005751FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5752 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5753 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005754 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005755}
5756
Douglas Gregor42a552f2008-11-05 20:51:48 +00005757/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5758/// the well-formednes of the destructor declarator @p D with type @p
5759/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005760/// emit diagnostics and set the declarator to invalid. Even if this happens,
5761/// will be updated to reflect a well-formed type for the destructor and
5762/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005763QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005764 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005765 // C++ [class.dtor]p1:
5766 // [...] A typedef-name that names a class is a class-name
5767 // (7.1.3); however, a typedef-name that names a class shall not
5768 // be used as the identifier in the declarator for a destructor
5769 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005770 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005771 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005772 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005773 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005774 else if (const TemplateSpecializationType *TST =
5775 DeclaratorType->getAs<TemplateSpecializationType>())
5776 if (TST->isTypeAlias())
5777 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5778 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005779
5780 // C++ [class.dtor]p2:
5781 // A destructor is used to destroy objects of its class type. A
5782 // destructor takes no parameters, and no return type can be
5783 // specified for it (not even void). The address of a destructor
5784 // shall not be taken. A destructor shall not be static. A
5785 // destructor can be invoked for a const, volatile or const
5786 // volatile object. A destructor shall not be declared const,
5787 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005788 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005789 if (!D.isInvalidType())
5790 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5791 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005792 << SourceRange(D.getIdentifierLoc())
5793 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5794
John McCalld931b082010-08-26 03:08:43 +00005795 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005796 }
Chris Lattner65401802009-04-25 08:28:21 +00005797 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005798 // Destructors don't have return types, but the parser will
5799 // happily parse something like:
5800 //
5801 // class X {
5802 // float ~X();
5803 // };
5804 //
5805 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005806 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5807 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5808 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005809 }
Mike Stump1eb44332009-09-09 15:08:12 +00005810
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005811 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005812 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005813 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005814 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5815 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005816 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005817 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5818 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005819 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005820 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5821 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005822 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005823 }
5824
Douglas Gregorc938c162011-01-26 05:01:58 +00005825 // C++0x [class.dtor]p2:
5826 // A destructor shall not be declared with a ref-qualifier.
5827 if (FTI.hasRefQualifier()) {
5828 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5829 << FTI.RefQualifierIsLValueRef
5830 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5831 D.setInvalidType();
5832 }
5833
Douglas Gregor42a552f2008-11-05 20:51:48 +00005834 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005835 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005836 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5837
5838 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005839 FTI.freeArgs();
5840 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005841 }
5842
Mike Stump1eb44332009-09-09 15:08:12 +00005843 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005844 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005845 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005846 D.setInvalidType();
5847 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005848
5849 // Rebuild the function type "R" without any type qualifiers or
5850 // parameters (in case any of the errors above fired) and with
5851 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005852 // types.
John McCalle23cf432010-12-14 08:05:40 +00005853 if (!D.isInvalidType())
5854 return R;
5855
Douglas Gregord92ec472010-07-01 05:10:53 +00005856 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005857 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5858 EPI.Variadic = false;
5859 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005860 EPI.RefQualifier = RQ_None;
Jordan Rosebea522f2013-03-08 21:51:21 +00005861 return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005862}
5863
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005864/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5865/// well-formednes of the conversion function declarator @p D with
5866/// type @p R. If there are any errors in the declarator, this routine
5867/// will emit diagnostics and return true. Otherwise, it will return
5868/// false. Either way, the type @p R will be updated to reflect a
5869/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005870void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005871 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005872 // C++ [class.conv.fct]p1:
5873 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005874 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005875 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005876 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005877 if (!D.isInvalidType())
5878 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5879 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5880 << SourceRange(D.getIdentifierLoc());
5881 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005882 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005883 }
John McCalla3f81372010-04-13 00:04:31 +00005884
5885 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5886
Chris Lattner6e475012009-04-25 08:35:12 +00005887 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005888 // Conversion functions don't have return types, but the parser will
5889 // happily parse something like:
5890 //
5891 // class X {
5892 // float operator bool();
5893 // };
5894 //
5895 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005896 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5897 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5898 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005899 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005900 }
5901
John McCalla3f81372010-04-13 00:04:31 +00005902 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5903
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005904 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005905 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005906 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5907
5908 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005909 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005910 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005911 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005912 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005913 D.setInvalidType();
5914 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005915
John McCalla3f81372010-04-13 00:04:31 +00005916 // Diagnose "&operator bool()" and other such nonsense. This
5917 // is actually a gcc extension which we don't support.
5918 if (Proto->getResultType() != ConvType) {
5919 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5920 << Proto->getResultType();
5921 D.setInvalidType();
5922 ConvType = Proto->getResultType();
5923 }
5924
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005925 // C++ [class.conv.fct]p4:
5926 // The conversion-type-id shall not represent a function type nor
5927 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005928 if (ConvType->isArrayType()) {
5929 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5930 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005931 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005932 } else if (ConvType->isFunctionType()) {
5933 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5934 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005935 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005936 }
5937
5938 // Rebuild the function type "R" without any parameters (in case any
5939 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005940 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005941 if (D.isInvalidType())
Jordan Rosebea522f2013-03-08 21:51:21 +00005942 R = Context.getFunctionType(ConvType, ArrayRef<QualType>(),
5943 Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005944
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005945 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005946 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005947 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005948 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005949 diag::warn_cxx98_compat_explicit_conversion_functions :
5950 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005951 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005952}
5953
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005954/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5955/// the declaration of the given C++ conversion function. This routine
5956/// is responsible for recording the conversion function in the C++
5957/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005958Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005959 assert(Conversion && "Expected to receive a conversion function declaration");
5960
Douglas Gregor9d350972008-12-12 08:25:50 +00005961 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005962
5963 // Make sure we aren't redeclaring the conversion function.
5964 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005965
5966 // C++ [class.conv.fct]p1:
5967 // [...] A conversion function is never used to convert a
5968 // (possibly cv-qualified) object to the (possibly cv-qualified)
5969 // same object type (or a reference to it), to a (possibly
5970 // cv-qualified) base class of that type (or a reference to it),
5971 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005972 // FIXME: Suppress this warning if the conversion function ends up being a
5973 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005974 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005975 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005976 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005977 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005978 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5979 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005980 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005981 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005982 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5983 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005984 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005985 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005986 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005987 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005988 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005989 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005990 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005991 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005992 }
5993
Douglas Gregore80622f2010-09-29 04:25:11 +00005994 if (FunctionTemplateDecl *ConversionTemplate
5995 = Conversion->getDescribedFunctionTemplate())
5996 return ConversionTemplate;
5997
John McCalld226f652010-08-21 09:40:31 +00005998 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005999}
6000
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006001//===----------------------------------------------------------------------===//
6002// Namespace Handling
6003//===----------------------------------------------------------------------===//
6004
Richard Smithd1a55a62012-10-04 22:13:39 +00006005/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6006/// reopened.
6007static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6008 SourceLocation Loc,
6009 IdentifierInfo *II, bool *IsInline,
6010 NamespaceDecl *PrevNS) {
6011 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006012
Richard Smithc969e6a2012-10-05 01:46:25 +00006013 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6014 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6015 // inline namespaces, with the intention of bringing names into namespace std.
6016 //
6017 // We support this just well enough to get that case working; this is not
6018 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006019 if (*IsInline && II && II->getName().startswith("__atomic") &&
6020 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006021 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006022 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6023 NS = NS->getPreviousDecl())
6024 NS->setInline(*IsInline);
6025 // Patch up the lookup table for the containing namespace. This isn't really
6026 // correct, but it's good enough for this particular case.
6027 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6028 E = PrevNS->decls_end(); I != E; ++I)
6029 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6030 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6031 return;
6032 }
6033
6034 if (PrevNS->isInline())
6035 // The user probably just forgot the 'inline', so suggest that it
6036 // be added back.
6037 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6038 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6039 else
6040 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6041 << IsInline;
6042
6043 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6044 *IsInline = PrevNS->isInline();
6045}
John McCallea318642010-08-26 09:15:37 +00006046
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006047/// ActOnStartNamespaceDef - This is called at the start of a namespace
6048/// definition.
John McCalld226f652010-08-21 09:40:31 +00006049Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006050 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006051 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006052 SourceLocation IdentLoc,
6053 IdentifierInfo *II,
6054 SourceLocation LBrace,
6055 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006056 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6057 // For anonymous namespace, take the location of the left brace.
6058 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006059 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006060 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006061 bool IsStd = false;
6062 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006063 Scope *DeclRegionScope = NamespcScope->getParent();
6064
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006065 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006066 if (II) {
6067 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006068 // The identifier in an original-namespace-definition shall not
6069 // have been previously defined in the declarative region in
6070 // which the original-namespace-definition appears. The
6071 // identifier in an original-namespace-definition is the name of
6072 // the namespace. Subsequently in that declarative region, it is
6073 // treated as an original-namespace-name.
6074 //
6075 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006076 // look through using directives, just look for any ordinary names.
6077
6078 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006079 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6080 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006081 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006082 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6083 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6084 ++I) {
6085 if ((*I)->getIdentifierNamespace() & IDNS) {
6086 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006087 break;
6088 }
6089 }
6090
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006091 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6092
6093 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006094 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006095 if (IsInline != PrevNS->isInline())
6096 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6097 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006098 } else if (PrevDecl) {
6099 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006100 Diag(Loc, diag::err_redefinition_different_kind)
6101 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006102 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006103 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006104 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006105 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006106 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006107 // This is the first "real" definition of the namespace "std", so update
6108 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006109 PrevNS = getStdNamespace();
6110 IsStd = true;
6111 AddToKnown = !IsInline;
6112 } else {
6113 // We've seen this namespace for the first time.
6114 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006115 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006116 } else {
John McCall9aeed322009-10-01 00:25:31 +00006117 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006118
6119 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006120 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006121 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006122 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006123 } else {
6124 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006125 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006126 }
6127
Richard Smithd1a55a62012-10-04 22:13:39 +00006128 if (PrevNS && IsInline != PrevNS->isInline())
6129 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6130 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006131 }
6132
6133 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6134 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006135 if (IsInvalid)
6136 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006137
6138 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006139
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006140 // FIXME: Should we be merging attributes?
6141 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006142 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006143
6144 if (IsStd)
6145 StdNamespace = Namespc;
6146 if (AddToKnown)
6147 KnownNamespaces[Namespc] = false;
6148
6149 if (II) {
6150 PushOnScopeChains(Namespc, DeclRegionScope);
6151 } else {
6152 // Link the anonymous namespace into its parent.
6153 DeclContext *Parent = CurContext->getRedeclContext();
6154 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6155 TU->setAnonymousNamespace(Namespc);
6156 } else {
6157 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006158 }
John McCall9aeed322009-10-01 00:25:31 +00006159
Douglas Gregora4181472010-03-24 00:46:35 +00006160 CurContext->addDecl(Namespc);
6161
John McCall9aeed322009-10-01 00:25:31 +00006162 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6163 // behaves as if it were replaced by
6164 // namespace unique { /* empty body */ }
6165 // using namespace unique;
6166 // namespace unique { namespace-body }
6167 // where all occurrences of 'unique' in a translation unit are
6168 // replaced by the same identifier and this identifier differs
6169 // from all other identifiers in the entire program.
6170
6171 // We just create the namespace with an empty name and then add an
6172 // implicit using declaration, just like the standard suggests.
6173 //
6174 // CodeGen enforces the "universally unique" aspect by giving all
6175 // declarations semantically contained within an anonymous
6176 // namespace internal linkage.
6177
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006178 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006179 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006180 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006181 /* 'using' */ LBrace,
6182 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006183 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006184 /* identifier */ SourceLocation(),
6185 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006186 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006187 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006188 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006189 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006190 }
6191
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006192 ActOnDocumentableDecl(Namespc);
6193
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006194 // Although we could have an invalid decl (i.e. the namespace name is a
6195 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006196 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6197 // for the namespace has the declarations that showed up in that particular
6198 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006199 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006200 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006201}
6202
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006203/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6204/// is a namespace alias, returns the namespace it points to.
6205static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6206 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6207 return AD->getNamespace();
6208 return dyn_cast_or_null<NamespaceDecl>(D);
6209}
6210
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006211/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6212/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006213void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006214 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6215 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006216 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006217 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006218 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006219 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006220}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006221
John McCall384aff82010-08-25 07:42:41 +00006222CXXRecordDecl *Sema::getStdBadAlloc() const {
6223 return cast_or_null<CXXRecordDecl>(
6224 StdBadAlloc.get(Context.getExternalSource()));
6225}
6226
6227NamespaceDecl *Sema::getStdNamespace() const {
6228 return cast_or_null<NamespaceDecl>(
6229 StdNamespace.get(Context.getExternalSource()));
6230}
6231
Douglas Gregor66992202010-06-29 17:53:46 +00006232/// \brief Retrieve the special "std" namespace, which may require us to
6233/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006234NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006235 if (!StdNamespace) {
6236 // The "std" namespace has not yet been defined, so build one implicitly.
6237 StdNamespace = NamespaceDecl::Create(Context,
6238 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006239 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006240 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006241 &PP.getIdentifierTable().get("std"),
6242 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006243 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006244 }
6245
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006246 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006247}
6248
Sebastian Redl395e04d2012-01-17 22:49:33 +00006249bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006250 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006251 "Looking for std::initializer_list outside of C++.");
6252
6253 // We're looking for implicit instantiations of
6254 // template <typename E> class std::initializer_list.
6255
6256 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6257 return false;
6258
Sebastian Redl84760e32012-01-17 22:49:58 +00006259 ClassTemplateDecl *Template = 0;
6260 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006261
Sebastian Redl84760e32012-01-17 22:49:58 +00006262 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006263
Sebastian Redl84760e32012-01-17 22:49:58 +00006264 ClassTemplateSpecializationDecl *Specialization =
6265 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6266 if (!Specialization)
6267 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006268
Sebastian Redl84760e32012-01-17 22:49:58 +00006269 Template = Specialization->getSpecializedTemplate();
6270 Arguments = Specialization->getTemplateArgs().data();
6271 } else if (const TemplateSpecializationType *TST =
6272 Ty->getAs<TemplateSpecializationType>()) {
6273 Template = dyn_cast_or_null<ClassTemplateDecl>(
6274 TST->getTemplateName().getAsTemplateDecl());
6275 Arguments = TST->getArgs();
6276 }
6277 if (!Template)
6278 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006279
6280 if (!StdInitializerList) {
6281 // Haven't recognized std::initializer_list yet, maybe this is it.
6282 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6283 if (TemplateClass->getIdentifier() !=
6284 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006285 !getStdNamespace()->InEnclosingNamespaceSetOf(
6286 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006287 return false;
6288 // This is a template called std::initializer_list, but is it the right
6289 // template?
6290 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006291 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006292 return false;
6293 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6294 return false;
6295
6296 // It's the right template.
6297 StdInitializerList = Template;
6298 }
6299
6300 if (Template != StdInitializerList)
6301 return false;
6302
6303 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006304 if (Element)
6305 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006306 return true;
6307}
6308
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006309static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6310 NamespaceDecl *Std = S.getStdNamespace();
6311 if (!Std) {
6312 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6313 return 0;
6314 }
6315
6316 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6317 Loc, Sema::LookupOrdinaryName);
6318 if (!S.LookupQualifiedName(Result, Std)) {
6319 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6320 return 0;
6321 }
6322 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6323 if (!Template) {
6324 Result.suppressDiagnostics();
6325 // We found something weird. Complain about the first thing we found.
6326 NamedDecl *Found = *Result.begin();
6327 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6328 return 0;
6329 }
6330
6331 // We found some template called std::initializer_list. Now verify that it's
6332 // correct.
6333 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006334 if (Params->getMinRequiredArguments() != 1 ||
6335 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006336 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6337 return 0;
6338 }
6339
6340 return Template;
6341}
6342
6343QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6344 if (!StdInitializerList) {
6345 StdInitializerList = LookupStdInitializerList(*this, Loc);
6346 if (!StdInitializerList)
6347 return QualType();
6348 }
6349
6350 TemplateArgumentListInfo Args(Loc, Loc);
6351 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6352 Context.getTrivialTypeSourceInfo(Element,
6353 Loc)));
6354 return Context.getCanonicalType(
6355 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6356}
6357
Sebastian Redl98d36062012-01-17 22:50:14 +00006358bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6359 // C++ [dcl.init.list]p2:
6360 // A constructor is an initializer-list constructor if its first parameter
6361 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6362 // std::initializer_list<E> for some type E, and either there are no other
6363 // parameters or else all other parameters have default arguments.
6364 if (Ctor->getNumParams() < 1 ||
6365 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6366 return false;
6367
6368 QualType ArgType = Ctor->getParamDecl(0)->getType();
6369 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6370 ArgType = RT->getPointeeType().getUnqualifiedType();
6371
6372 return isStdInitializerList(ArgType, 0);
6373}
6374
Douglas Gregor9172aa62011-03-26 22:25:30 +00006375/// \brief Determine whether a using statement is in a context where it will be
6376/// apply in all contexts.
6377static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6378 switch (CurContext->getDeclKind()) {
6379 case Decl::TranslationUnit:
6380 return true;
6381 case Decl::LinkageSpec:
6382 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6383 default:
6384 return false;
6385 }
6386}
6387
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006388namespace {
6389
6390// Callback to only accept typo corrections that are namespaces.
6391class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6392 public:
6393 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6394 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6395 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6396 }
6397 return false;
6398 }
6399};
6400
6401}
6402
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006403static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6404 CXXScopeSpec &SS,
6405 SourceLocation IdentLoc,
6406 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006407 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006408 R.clear();
6409 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006410 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006411 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006412 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6413 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006414 if (DeclContext *DC = S.computeDeclContext(SS, false))
6415 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6416 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006417 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6418 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006419 else
6420 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6421 << Ident << CorrectedQuotedStr
6422 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006423
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006424 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6425 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006426
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006427 R.addDecl(Corrected.getCorrectionDecl());
6428 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006429 }
6430 return false;
6431}
6432
John McCalld226f652010-08-21 09:40:31 +00006433Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006434 SourceLocation UsingLoc,
6435 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006436 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006437 SourceLocation IdentLoc,
6438 IdentifierInfo *NamespcName,
6439 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006440 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6441 assert(NamespcName && "Invalid NamespcName.");
6442 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006443
6444 // This can only happen along a recovery path.
6445 while (S->getFlags() & Scope::TemplateParamScope)
6446 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006447 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006448
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006449 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006450 NestedNameSpecifier *Qualifier = 0;
6451 if (SS.isSet())
6452 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6453
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006454 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006455 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6456 LookupParsedName(R, S, &SS);
6457 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006458 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006459
Douglas Gregor66992202010-06-29 17:53:46 +00006460 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006461 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006462 // Allow "using namespace std;" or "using namespace ::std;" even if
6463 // "std" hasn't been defined yet, for GCC compatibility.
6464 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6465 NamespcName->isStr("std")) {
6466 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006467 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006468 R.resolveKind();
6469 }
6470 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006471 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006472 }
6473
John McCallf36e02d2009-10-09 21:13:30 +00006474 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006475 NamedDecl *Named = R.getFoundDecl();
6476 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6477 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006478 // C++ [namespace.udir]p1:
6479 // A using-directive specifies that the names in the nominated
6480 // namespace can be used in the scope in which the
6481 // using-directive appears after the using-directive. During
6482 // unqualified name lookup (3.4.1), the names appear as if they
6483 // were declared in the nearest enclosing namespace which
6484 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006485 // namespace. [Note: in this context, "contains" means "contains
6486 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006487
6488 // Find enclosing context containing both using-directive and
6489 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006490 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006491 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6492 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6493 CommonAncestor = CommonAncestor->getParent();
6494
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006495 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006496 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006497 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006498
Douglas Gregor9172aa62011-03-26 22:25:30 +00006499 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006500 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006501 Diag(IdentLoc, diag::warn_using_directive_in_header);
6502 }
6503
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006504 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006505 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006506 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006507 }
6508
Richard Smith6b3d3e52013-02-20 19:22:51 +00006509 if (UDir)
6510 ProcessDeclAttributeList(S, UDir, AttrList);
6511
John McCalld226f652010-08-21 09:40:31 +00006512 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006513}
6514
6515void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006516 // If the scope has an associated entity and the using directive is at
6517 // namespace or translation unit scope, add the UsingDirectiveDecl into
6518 // its lookup structure so qualified name lookup can find it.
6519 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6520 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006521 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006522 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006523 // Otherwise, it is at block sope. The using-directives will affect lookup
6524 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006525 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006526}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006527
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006528
John McCalld226f652010-08-21 09:40:31 +00006529Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006530 AccessSpecifier AS,
6531 bool HasUsingKeyword,
6532 SourceLocation UsingLoc,
6533 CXXScopeSpec &SS,
6534 UnqualifiedId &Name,
6535 AttributeList *AttrList,
6536 bool IsTypeName,
6537 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006538 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006539
Douglas Gregor12c118a2009-11-04 16:30:06 +00006540 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006541 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006542 case UnqualifiedId::IK_Identifier:
6543 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006544 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006545 case UnqualifiedId::IK_ConversionFunctionId:
6546 break;
6547
6548 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006549 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006550 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006551 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006552 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006553 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006554 diag::err_using_decl_constructor)
6555 << SS.getRange();
6556
Richard Smith80ad52f2013-01-02 11:42:31 +00006557 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006558
John McCalld226f652010-08-21 09:40:31 +00006559 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006560
6561 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006562 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006563 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006564 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006565
6566 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006567 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006568 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006569 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006570 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006571
6572 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6573 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006574 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006575 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006576
Richard Smith07b0fdc2013-03-18 21:12:30 +00006577 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006578 // TODO: store that the declaration was written without 'using' and
6579 // talk about access decls instead of using decls in the
6580 // diagnostics.
6581 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006582 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006583
6584 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006585 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006586 }
6587
Douglas Gregor56c04582010-12-16 00:46:58 +00006588 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6589 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6590 return 0;
6591
John McCall9488ea12009-11-17 05:59:44 +00006592 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006593 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006594 /* IsInstantiation */ false,
6595 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006596 if (UD)
6597 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006598
John McCalld226f652010-08-21 09:40:31 +00006599 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006600}
6601
Douglas Gregor09acc982010-07-07 23:08:52 +00006602/// \brief Determine whether a using declaration considers the given
6603/// declarations as "equivalent", e.g., if they are redeclarations of
6604/// the same entity or are both typedefs of the same type.
6605static bool
6606IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6607 bool &SuppressRedeclaration) {
6608 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6609 SuppressRedeclaration = false;
6610 return true;
6611 }
6612
Richard Smith162e1c12011-04-15 14:24:37 +00006613 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6614 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006615 SuppressRedeclaration = true;
6616 return Context.hasSameType(TD1->getUnderlyingType(),
6617 TD2->getUnderlyingType());
6618 }
6619
6620 return false;
6621}
6622
6623
John McCall9f54ad42009-12-10 09:41:52 +00006624/// Determines whether to create a using shadow decl for a particular
6625/// decl, given the set of decls existing prior to this using lookup.
6626bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6627 const LookupResult &Previous) {
6628 // Diagnose finding a decl which is not from a base class of the
6629 // current class. We do this now because there are cases where this
6630 // function will silently decide not to build a shadow decl, which
6631 // will pre-empt further diagnostics.
6632 //
6633 // We don't need to do this in C++0x because we do the check once on
6634 // the qualifier.
6635 //
6636 // FIXME: diagnose the following if we care enough:
6637 // struct A { int foo; };
6638 // struct B : A { using A::foo; };
6639 // template <class T> struct C : A {};
6640 // template <class T> struct D : C<T> { using B::foo; } // <---
6641 // This is invalid (during instantiation) in C++03 because B::foo
6642 // resolves to the using decl in B, which is not a base class of D<T>.
6643 // We can't diagnose it immediately because C<T> is an unknown
6644 // specialization. The UsingShadowDecl in D<T> then points directly
6645 // to A::foo, which will look well-formed when we instantiate.
6646 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006647 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006648 DeclContext *OrigDC = Orig->getDeclContext();
6649
6650 // Handle enums and anonymous structs.
6651 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6652 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6653 while (OrigRec->isAnonymousStructOrUnion())
6654 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6655
6656 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6657 if (OrigDC == CurContext) {
6658 Diag(Using->getLocation(),
6659 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006660 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006661 Diag(Orig->getLocation(), diag::note_using_decl_target);
6662 return true;
6663 }
6664
Douglas Gregordc355712011-02-25 00:36:19 +00006665 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006666 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006667 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006668 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006669 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006670 Diag(Orig->getLocation(), diag::note_using_decl_target);
6671 return true;
6672 }
6673 }
6674
6675 if (Previous.empty()) return false;
6676
6677 NamedDecl *Target = Orig;
6678 if (isa<UsingShadowDecl>(Target))
6679 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6680
John McCalld7533ec2009-12-11 02:33:26 +00006681 // If the target happens to be one of the previous declarations, we
6682 // don't have a conflict.
6683 //
6684 // FIXME: but we might be increasing its access, in which case we
6685 // should redeclare it.
6686 NamedDecl *NonTag = 0, *Tag = 0;
6687 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6688 I != E; ++I) {
6689 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006690 bool Result;
6691 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6692 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006693
6694 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6695 }
6696
John McCall9f54ad42009-12-10 09:41:52 +00006697 if (Target->isFunctionOrFunctionTemplate()) {
6698 FunctionDecl *FD;
6699 if (isa<FunctionTemplateDecl>(Target))
6700 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6701 else
6702 FD = cast<FunctionDecl>(Target);
6703
6704 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006705 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006706 case Ovl_Overload:
6707 return false;
6708
6709 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006710 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006711 break;
6712
6713 // We found a decl with the exact signature.
6714 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006715 // If we're in a record, we want to hide the target, so we
6716 // return true (without a diagnostic) to tell the caller not to
6717 // build a shadow decl.
6718 if (CurContext->isRecord())
6719 return true;
6720
6721 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006722 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006723 break;
6724 }
6725
6726 Diag(Target->getLocation(), diag::note_using_decl_target);
6727 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6728 return true;
6729 }
6730
6731 // Target is not a function.
6732
John McCall9f54ad42009-12-10 09:41:52 +00006733 if (isa<TagDecl>(Target)) {
6734 // No conflict between a tag and a non-tag.
6735 if (!Tag) return false;
6736
John McCall41ce66f2009-12-10 19:51:03 +00006737 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006738 Diag(Target->getLocation(), diag::note_using_decl_target);
6739 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6740 return true;
6741 }
6742
6743 // No conflict between a tag and a non-tag.
6744 if (!NonTag) return false;
6745
John McCall41ce66f2009-12-10 19:51:03 +00006746 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006747 Diag(Target->getLocation(), diag::note_using_decl_target);
6748 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6749 return true;
6750}
6751
John McCall9488ea12009-11-17 05:59:44 +00006752/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006753UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006754 UsingDecl *UD,
6755 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006756
6757 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006758 NamedDecl *Target = Orig;
6759 if (isa<UsingShadowDecl>(Target)) {
6760 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6761 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006762 }
6763
6764 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006765 = UsingShadowDecl::Create(Context, CurContext,
6766 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006767 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006768
6769 Shadow->setAccess(UD->getAccess());
6770 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6771 Shadow->setInvalidDecl();
6772
John McCall9488ea12009-11-17 05:59:44 +00006773 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006774 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006775 else
John McCall604e7f12009-12-08 07:46:18 +00006776 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006777
John McCall604e7f12009-12-08 07:46:18 +00006778
John McCall9f54ad42009-12-10 09:41:52 +00006779 return Shadow;
6780}
John McCall604e7f12009-12-08 07:46:18 +00006781
John McCall9f54ad42009-12-10 09:41:52 +00006782/// Hides a using shadow declaration. This is required by the current
6783/// using-decl implementation when a resolvable using declaration in a
6784/// class is followed by a declaration which would hide or override
6785/// one or more of the using decl's targets; for example:
6786///
6787/// struct Base { void foo(int); };
6788/// struct Derived : Base {
6789/// using Base::foo;
6790/// void foo(int);
6791/// };
6792///
6793/// The governing language is C++03 [namespace.udecl]p12:
6794///
6795/// When a using-declaration brings names from a base class into a
6796/// derived class scope, member functions in the derived class
6797/// override and/or hide member functions with the same name and
6798/// parameter types in a base class (rather than conflicting).
6799///
6800/// There are two ways to implement this:
6801/// (1) optimistically create shadow decls when they're not hidden
6802/// by existing declarations, or
6803/// (2) don't create any shadow decls (or at least don't make them
6804/// visible) until we've fully parsed/instantiated the class.
6805/// The problem with (1) is that we might have to retroactively remove
6806/// a shadow decl, which requires several O(n) operations because the
6807/// decl structures are (very reasonably) not designed for removal.
6808/// (2) avoids this but is very fiddly and phase-dependent.
6809void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006810 if (Shadow->getDeclName().getNameKind() ==
6811 DeclarationName::CXXConversionFunctionName)
6812 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6813
John McCall9f54ad42009-12-10 09:41:52 +00006814 // Remove it from the DeclContext...
6815 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006816
John McCall9f54ad42009-12-10 09:41:52 +00006817 // ...and the scope, if applicable...
6818 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006819 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006820 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006821 }
6822
John McCall9f54ad42009-12-10 09:41:52 +00006823 // ...and the using decl.
6824 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6825
6826 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006827 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006828}
6829
John McCall7ba107a2009-11-18 02:36:19 +00006830/// Builds a using declaration.
6831///
6832/// \param IsInstantiation - Whether this call arises from an
6833/// instantiation of an unresolved using declaration. We treat
6834/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006835NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6836 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006837 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006838 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006839 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006840 bool IsInstantiation,
6841 bool IsTypeName,
6842 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006843 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006844 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006845 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006846
Anders Carlsson550b14b2009-08-28 05:49:21 +00006847 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006848
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006849 if (SS.isEmpty()) {
6850 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006851 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006852 }
Mike Stump1eb44332009-09-09 15:08:12 +00006853
John McCall9f54ad42009-12-10 09:41:52 +00006854 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006855 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006856 ForRedeclaration);
6857 Previous.setHideTags(false);
6858 if (S) {
6859 LookupName(Previous, S);
6860
6861 // It is really dumb that we have to do this.
6862 LookupResult::Filter F = Previous.makeFilter();
6863 while (F.hasNext()) {
6864 NamedDecl *D = F.next();
6865 if (!isDeclInScope(D, CurContext, S))
6866 F.erase();
6867 }
6868 F.done();
6869 } else {
6870 assert(IsInstantiation && "no scope in non-instantiation");
6871 assert(CurContext->isRecord() && "scope not record in instantiation");
6872 LookupQualifiedName(Previous, CurContext);
6873 }
6874
John McCall9f54ad42009-12-10 09:41:52 +00006875 // Check for invalid redeclarations.
6876 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6877 return 0;
6878
6879 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006880 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6881 return 0;
6882
John McCallaf8e6ed2009-11-12 03:15:40 +00006883 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006884 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006885 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006886 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006887 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006888 // FIXME: not all declaration name kinds are legal here
6889 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6890 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006891 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006892 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006893 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006894 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6895 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006896 }
John McCalled976492009-12-04 22:46:56 +00006897 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006898 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6899 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006900 }
John McCalled976492009-12-04 22:46:56 +00006901 D->setAccess(AS);
6902 CurContext->addDecl(D);
6903
6904 if (!LookupContext) return D;
6905 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006906
John McCall77bb1aa2010-05-01 00:40:08 +00006907 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006908 UD->setInvalidDecl();
6909 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006910 }
6911
Richard Smithc5a89a12012-04-02 01:30:27 +00006912 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006913 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006914 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006915 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006916 return UD;
6917 }
6918
6919 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006920
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006921 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006922
John McCall604e7f12009-12-08 07:46:18 +00006923 // Unlike most lookups, we don't always want to hide tag
6924 // declarations: tag names are visible through the using declaration
6925 // even if hidden by ordinary names, *except* in a dependent context
6926 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006927 if (!IsInstantiation)
6928 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006929
John McCallb9abd8722012-04-07 03:04:20 +00006930 // For the purposes of this lookup, we have a base object type
6931 // equal to that of the current context.
6932 if (CurContext->isRecord()) {
6933 R.setBaseObjectType(
6934 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6935 }
6936
John McCalla24dc2e2009-11-17 02:14:36 +00006937 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006938
John McCallf36e02d2009-10-09 21:13:30 +00006939 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006940 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006941 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006942 UD->setInvalidDecl();
6943 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006944 }
6945
John McCalled976492009-12-04 22:46:56 +00006946 if (R.isAmbiguous()) {
6947 UD->setInvalidDecl();
6948 return UD;
6949 }
Mike Stump1eb44332009-09-09 15:08:12 +00006950
John McCall7ba107a2009-11-18 02:36:19 +00006951 if (IsTypeName) {
6952 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006953 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006954 Diag(IdentLoc, diag::err_using_typename_non_type);
6955 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6956 Diag((*I)->getUnderlyingDecl()->getLocation(),
6957 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006958 UD->setInvalidDecl();
6959 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006960 }
6961 } else {
6962 // If we asked for a non-typename and we got a type, error out,
6963 // but only if this is an instantiation of an unresolved using
6964 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006965 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006966 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6967 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006968 UD->setInvalidDecl();
6969 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006970 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006971 }
6972
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006973 // C++0x N2914 [namespace.udecl]p6:
6974 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006975 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006976 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6977 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006978 UD->setInvalidDecl();
6979 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006980 }
Mike Stump1eb44332009-09-09 15:08:12 +00006981
John McCall9f54ad42009-12-10 09:41:52 +00006982 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6983 if (!CheckUsingShadowDecl(UD, *I, Previous))
6984 BuildUsingShadowDecl(S, UD, *I);
6985 }
John McCall9488ea12009-11-17 05:59:44 +00006986
6987 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006988}
6989
Sebastian Redlf677ea32011-02-05 19:23:19 +00006990/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006991bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6992 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006993
Douglas Gregordc355712011-02-25 00:36:19 +00006994 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006995 assert(SourceType &&
6996 "Using decl naming constructor doesn't have type in scope spec.");
6997 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6998
6999 // Check whether the named type is a direct base class.
7000 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7001 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7002 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7003 BaseIt != BaseE; ++BaseIt) {
7004 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7005 if (CanonicalSourceType == BaseType)
7006 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007007 if (BaseIt->getType()->isDependentType())
7008 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007009 }
7010
7011 if (BaseIt == BaseE) {
7012 // Did not find SourceType in the bases.
7013 Diag(UD->getUsingLocation(),
7014 diag::err_using_decl_constructor_not_in_direct_base)
7015 << UD->getNameInfo().getSourceRange()
7016 << QualType(SourceType, 0) << TargetClass;
7017 return true;
7018 }
7019
Richard Smithc5a89a12012-04-02 01:30:27 +00007020 if (!CurContext->isDependentContext())
7021 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007022
7023 return false;
7024}
7025
John McCall9f54ad42009-12-10 09:41:52 +00007026/// Checks that the given using declaration is not an invalid
7027/// redeclaration. Note that this is checking only for the using decl
7028/// itself, not for any ill-formedness among the UsingShadowDecls.
7029bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7030 bool isTypeName,
7031 const CXXScopeSpec &SS,
7032 SourceLocation NameLoc,
7033 const LookupResult &Prev) {
7034 // C++03 [namespace.udecl]p8:
7035 // C++0x [namespace.udecl]p10:
7036 // A using-declaration is a declaration and can therefore be used
7037 // repeatedly where (and only where) multiple declarations are
7038 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007039 //
John McCall8a726212010-11-29 18:01:58 +00007040 // That's in non-member contexts.
7041 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007042 return false;
7043
7044 NestedNameSpecifier *Qual
7045 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7046
7047 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7048 NamedDecl *D = *I;
7049
7050 bool DTypename;
7051 NestedNameSpecifier *DQual;
7052 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7053 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007054 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007055 } else if (UnresolvedUsingValueDecl *UD
7056 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7057 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007058 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007059 } else if (UnresolvedUsingTypenameDecl *UD
7060 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7061 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007062 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007063 } else continue;
7064
7065 // using decls differ if one says 'typename' and the other doesn't.
7066 // FIXME: non-dependent using decls?
7067 if (isTypeName != DTypename) continue;
7068
7069 // using decls differ if they name different scopes (but note that
7070 // template instantiation can cause this check to trigger when it
7071 // didn't before instantiation).
7072 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7073 Context.getCanonicalNestedNameSpecifier(DQual))
7074 continue;
7075
7076 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007077 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007078 return true;
7079 }
7080
7081 return false;
7082}
7083
John McCall604e7f12009-12-08 07:46:18 +00007084
John McCalled976492009-12-04 22:46:56 +00007085/// Checks that the given nested-name qualifier used in a using decl
7086/// in the current context is appropriately related to the current
7087/// scope. If an error is found, diagnoses it and returns true.
7088bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7089 const CXXScopeSpec &SS,
7090 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007091 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007092
John McCall604e7f12009-12-08 07:46:18 +00007093 if (!CurContext->isRecord()) {
7094 // C++03 [namespace.udecl]p3:
7095 // C++0x [namespace.udecl]p8:
7096 // A using-declaration for a class member shall be a member-declaration.
7097
7098 // If we weren't able to compute a valid scope, it must be a
7099 // dependent class scope.
7100 if (!NamedContext || NamedContext->isRecord()) {
7101 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7102 << SS.getRange();
7103 return true;
7104 }
7105
7106 // Otherwise, everything is known to be fine.
7107 return false;
7108 }
7109
7110 // The current scope is a record.
7111
7112 // If the named context is dependent, we can't decide much.
7113 if (!NamedContext) {
7114 // FIXME: in C++0x, we can diagnose if we can prove that the
7115 // nested-name-specifier does not refer to a base class, which is
7116 // still possible in some cases.
7117
7118 // Otherwise we have to conservatively report that things might be
7119 // okay.
7120 return false;
7121 }
7122
7123 if (!NamedContext->isRecord()) {
7124 // Ideally this would point at the last name in the specifier,
7125 // but we don't have that level of source info.
7126 Diag(SS.getRange().getBegin(),
7127 diag::err_using_decl_nested_name_specifier_is_not_class)
7128 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7129 return true;
7130 }
7131
Douglas Gregor6fb07292010-12-21 07:41:49 +00007132 if (!NamedContext->isDependentContext() &&
7133 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7134 return true;
7135
Richard Smith80ad52f2013-01-02 11:42:31 +00007136 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007137 // C++0x [namespace.udecl]p3:
7138 // In a using-declaration used as a member-declaration, the
7139 // nested-name-specifier shall name a base class of the class
7140 // being defined.
7141
7142 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7143 cast<CXXRecordDecl>(NamedContext))) {
7144 if (CurContext == NamedContext) {
7145 Diag(NameLoc,
7146 diag::err_using_decl_nested_name_specifier_is_current_class)
7147 << SS.getRange();
7148 return true;
7149 }
7150
7151 Diag(SS.getRange().getBegin(),
7152 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7153 << (NestedNameSpecifier*) SS.getScopeRep()
7154 << cast<CXXRecordDecl>(CurContext)
7155 << SS.getRange();
7156 return true;
7157 }
7158
7159 return false;
7160 }
7161
7162 // C++03 [namespace.udecl]p4:
7163 // A using-declaration used as a member-declaration shall refer
7164 // to a member of a base class of the class being defined [etc.].
7165
7166 // Salient point: SS doesn't have to name a base class as long as
7167 // lookup only finds members from base classes. Therefore we can
7168 // diagnose here only if we can prove that that can't happen,
7169 // i.e. if the class hierarchies provably don't intersect.
7170
7171 // TODO: it would be nice if "definitely valid" results were cached
7172 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7173 // need to be repeated.
7174
7175 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007176 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007177
7178 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7179 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7180 Data->Bases.insert(Base);
7181 return true;
7182 }
7183
7184 bool hasDependentBases(const CXXRecordDecl *Class) {
7185 return !Class->forallBases(collect, this);
7186 }
7187
7188 /// Returns true if the base is dependent or is one of the
7189 /// accumulated base classes.
7190 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7191 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7192 return !Data->Bases.count(Base);
7193 }
7194
7195 bool mightShareBases(const CXXRecordDecl *Class) {
7196 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7197 }
7198 };
7199
7200 UserData Data;
7201
7202 // Returns false if we find a dependent base.
7203 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7204 return false;
7205
7206 // Returns false if the class has a dependent base or if it or one
7207 // of its bases is present in the base set of the current context.
7208 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7209 return false;
7210
7211 Diag(SS.getRange().getBegin(),
7212 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7213 << (NestedNameSpecifier*) SS.getScopeRep()
7214 << cast<CXXRecordDecl>(CurContext)
7215 << SS.getRange();
7216
7217 return true;
John McCalled976492009-12-04 22:46:56 +00007218}
7219
Richard Smith162e1c12011-04-15 14:24:37 +00007220Decl *Sema::ActOnAliasDeclaration(Scope *S,
7221 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007222 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007223 SourceLocation UsingLoc,
7224 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007225 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007226 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007227 // Skip up to the relevant declaration scope.
7228 while (S->getFlags() & Scope::TemplateParamScope)
7229 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007230 assert((S->getFlags() & Scope::DeclScope) &&
7231 "got alias-declaration outside of declaration scope");
7232
7233 if (Type.isInvalid())
7234 return 0;
7235
7236 bool Invalid = false;
7237 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7238 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007239 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007240
7241 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7242 return 0;
7243
7244 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007245 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007246 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007247 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7248 TInfo->getTypeLoc().getBeginLoc());
7249 }
Richard Smith162e1c12011-04-15 14:24:37 +00007250
7251 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7252 LookupName(Previous, S);
7253
7254 // Warn about shadowing the name of a template parameter.
7255 if (Previous.isSingleResult() &&
7256 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007257 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007258 Previous.clear();
7259 }
7260
7261 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7262 "name in alias declaration must be an identifier");
7263 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7264 Name.StartLocation,
7265 Name.Identifier, TInfo);
7266
7267 NewTD->setAccess(AS);
7268
7269 if (Invalid)
7270 NewTD->setInvalidDecl();
7271
Richard Smith6b3d3e52013-02-20 19:22:51 +00007272 ProcessDeclAttributeList(S, NewTD, AttrList);
7273
Richard Smith3e4c6c42011-05-05 21:57:07 +00007274 CheckTypedefForVariablyModifiedType(S, NewTD);
7275 Invalid |= NewTD->isInvalidDecl();
7276
Richard Smith162e1c12011-04-15 14:24:37 +00007277 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007278
7279 NamedDecl *NewND;
7280 if (TemplateParamLists.size()) {
7281 TypeAliasTemplateDecl *OldDecl = 0;
7282 TemplateParameterList *OldTemplateParams = 0;
7283
7284 if (TemplateParamLists.size() != 1) {
7285 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007286 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7287 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007288 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007289 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007290
7291 // Only consider previous declarations in the same scope.
7292 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7293 /*ExplicitInstantiationOrSpecialization*/false);
7294 if (!Previous.empty()) {
7295 Redeclaration = true;
7296
7297 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7298 if (!OldDecl && !Invalid) {
7299 Diag(UsingLoc, diag::err_redefinition_different_kind)
7300 << Name.Identifier;
7301
7302 NamedDecl *OldD = Previous.getRepresentativeDecl();
7303 if (OldD->getLocation().isValid())
7304 Diag(OldD->getLocation(), diag::note_previous_definition);
7305
7306 Invalid = true;
7307 }
7308
7309 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7310 if (TemplateParameterListsAreEqual(TemplateParams,
7311 OldDecl->getTemplateParameters(),
7312 /*Complain=*/true,
7313 TPL_TemplateMatch))
7314 OldTemplateParams = OldDecl->getTemplateParameters();
7315 else
7316 Invalid = true;
7317
7318 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7319 if (!Invalid &&
7320 !Context.hasSameType(OldTD->getUnderlyingType(),
7321 NewTD->getUnderlyingType())) {
7322 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7323 // but we can't reasonably accept it.
7324 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7325 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7326 if (OldTD->getLocation().isValid())
7327 Diag(OldTD->getLocation(), diag::note_previous_definition);
7328 Invalid = true;
7329 }
7330 }
7331 }
7332
7333 // Merge any previous default template arguments into our parameters,
7334 // and check the parameter list.
7335 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7336 TPC_TypeAliasTemplate))
7337 return 0;
7338
7339 TypeAliasTemplateDecl *NewDecl =
7340 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7341 Name.Identifier, TemplateParams,
7342 NewTD);
7343
7344 NewDecl->setAccess(AS);
7345
7346 if (Invalid)
7347 NewDecl->setInvalidDecl();
7348 else if (OldDecl)
7349 NewDecl->setPreviousDeclaration(OldDecl);
7350
7351 NewND = NewDecl;
7352 } else {
7353 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7354 NewND = NewTD;
7355 }
Richard Smith162e1c12011-04-15 14:24:37 +00007356
7357 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007358 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007359
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007360 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007361 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007362}
7363
John McCalld226f652010-08-21 09:40:31 +00007364Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007365 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007366 SourceLocation AliasLoc,
7367 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007368 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007369 SourceLocation IdentLoc,
7370 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007371
Anders Carlsson81c85c42009-03-28 23:53:49 +00007372 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007373 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7374 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007375
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007376 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007377 NamedDecl *PrevDecl
7378 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7379 ForRedeclaration);
7380 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7381 PrevDecl = 0;
7382
7383 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007384 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007385 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007386 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007387 // FIXME: At some point, we'll want to create the (redundant)
7388 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007389 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007390 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007391 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007392 }
Mike Stump1eb44332009-09-09 15:08:12 +00007393
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007394 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7395 diag::err_redefinition_different_kind;
7396 Diag(AliasLoc, DiagID) << Alias;
7397 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007398 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007399 }
7400
John McCalla24dc2e2009-11-17 02:14:36 +00007401 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007402 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007403
John McCallf36e02d2009-10-09 21:13:30 +00007404 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007405 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007406 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007407 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007408 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007409 }
Mike Stump1eb44332009-09-09 15:08:12 +00007410
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007411 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007412 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007413 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007414 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007415
John McCall3dbd3d52010-02-16 06:53:13 +00007416 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007417 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007418}
7419
Sean Hunt001cad92011-05-10 00:49:42 +00007420Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007421Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7422 CXXMethodDecl *MD) {
7423 CXXRecordDecl *ClassDecl = MD->getParent();
7424
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007425 // C++ [except.spec]p14:
7426 // An implicitly declared special member function (Clause 12) shall have an
7427 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007428 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007429 if (ClassDecl->isInvalidDecl())
7430 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007431
Sebastian Redl60618fa2011-03-12 11:50:43 +00007432 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007433 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7434 BEnd = ClassDecl->bases_end();
7435 B != BEnd; ++B) {
7436 if (B->isVirtual()) // Handled below.
7437 continue;
7438
Douglas Gregor18274032010-07-03 00:47:00 +00007439 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7440 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007441 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7442 // If this is a deleted function, add it anyway. This might be conformant
7443 // with the standard. This might not. I'm not sure. It might not matter.
7444 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007445 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007446 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007447 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007448
7449 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007450 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7451 BEnd = ClassDecl->vbases_end();
7452 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007453 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7454 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007455 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7456 // If this is a deleted function, add it anyway. This might be conformant
7457 // with the standard. This might not. I'm not sure. It might not matter.
7458 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007459 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007460 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007461 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007462
7463 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007464 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7465 FEnd = ClassDecl->field_end();
7466 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007467 if (F->hasInClassInitializer()) {
7468 if (Expr *E = F->getInClassInitializer())
7469 ExceptSpec.CalledExpr(E);
7470 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007471 // DR1351:
7472 // If the brace-or-equal-initializer of a non-static data member
7473 // invokes a defaulted default constructor of its class or of an
7474 // enclosing class in a potentially evaluated subexpression, the
7475 // program is ill-formed.
7476 //
7477 // This resolution is unworkable: the exception specification of the
7478 // default constructor can be needed in an unevaluated context, in
7479 // particular, in the operand of a noexcept-expression, and we can be
7480 // unable to compute an exception specification for an enclosed class.
7481 //
7482 // We do not allow an in-class initializer to require the evaluation
7483 // of the exception specification for any in-class initializer whose
7484 // definition is not lexically complete.
7485 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007486 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007487 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007488 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7489 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7490 // If this is a deleted function, add it anyway. This might be conformant
7491 // with the standard. This might not. I'm not sure. It might not matter.
7492 // In particular, the problem is that this function never gets called. It
7493 // might just be ill-formed because this function attempts to refer to
7494 // a deleted function here.
7495 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007496 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007497 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007498 }
John McCalle23cf432010-12-14 08:05:40 +00007499
Sean Hunt001cad92011-05-10 00:49:42 +00007500 return ExceptSpec;
7501}
7502
Richard Smith07b0fdc2013-03-18 21:12:30 +00007503Sema::ImplicitExceptionSpecification
7504Sema::ComputeInheritingCtorExceptionSpec(CXXMethodDecl *MD) {
7505 ImplicitExceptionSpecification ExceptSpec(*this);
7506 // FIXME: Compute the exception spec.
7507 return ExceptSpec;
7508}
7509
Richard Smithafb49182012-11-29 01:34:07 +00007510namespace {
7511/// RAII object to register a special member as being currently declared.
7512struct DeclaringSpecialMember {
7513 Sema &S;
7514 Sema::SpecialMemberDecl D;
7515 bool WasAlreadyBeingDeclared;
7516
7517 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7518 : S(S), D(RD, CSM) {
7519 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7520 if (WasAlreadyBeingDeclared)
7521 // This almost never happens, but if it does, ensure that our cache
7522 // doesn't contain a stale result.
7523 S.SpecialMemberCache.clear();
7524
7525 // FIXME: Register a note to be produced if we encounter an error while
7526 // declaring the special member.
7527 }
7528 ~DeclaringSpecialMember() {
7529 if (!WasAlreadyBeingDeclared)
7530 S.SpecialMembersBeingDeclared.erase(D);
7531 }
7532
7533 /// \brief Are we already trying to declare this special member?
7534 bool isAlreadyBeingDeclared() const {
7535 return WasAlreadyBeingDeclared;
7536 }
7537};
7538}
7539
Sean Hunt001cad92011-05-10 00:49:42 +00007540CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7541 CXXRecordDecl *ClassDecl) {
7542 // C++ [class.ctor]p5:
7543 // A default constructor for a class X is a constructor of class X
7544 // that can be called without an argument. If there is no
7545 // user-declared constructor for class X, a default constructor is
7546 // implicitly declared. An implicitly-declared default constructor
7547 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007548 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007549 "Should not build implicit default constructor!");
7550
Richard Smithafb49182012-11-29 01:34:07 +00007551 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7552 if (DSM.isAlreadyBeingDeclared())
7553 return 0;
7554
Richard Smith7756afa2012-06-10 05:43:50 +00007555 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7556 CXXDefaultConstructor,
7557 false);
7558
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007559 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007560 CanQualType ClassType
7561 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007562 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007563 DeclarationName Name
7564 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007565 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007566 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007567 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007568 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007569 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007570 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007571 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007572 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007573
7574 // Build an exception specification pointing back at this constructor.
7575 FunctionProtoType::ExtProtoInfo EPI;
7576 EPI.ExceptionSpecType = EST_Unevaluated;
7577 EPI.ExceptionSpecDecl = DefaultCon;
Jordan Rosebea522f2013-03-08 21:51:21 +00007578 DefaultCon->setType(Context.getFunctionType(Context.VoidTy,
7579 ArrayRef<QualType>(),
7580 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007581
Richard Smithbc2a35d2012-12-08 08:32:28 +00007582 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7583 // constructors is easy to compute.
7584 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7585
7586 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7587 DefaultCon->setDeletedAsWritten();
7588
Douglas Gregor18274032010-07-03 00:47:00 +00007589 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007590 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007591
Douglas Gregor23c94db2010-07-02 17:43:08 +00007592 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007593 PushOnScopeChains(DefaultCon, S, false);
7594 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007595
Douglas Gregor32df23e2010-07-01 22:02:46 +00007596 return DefaultCon;
7597}
7598
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007599void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7600 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007601 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007602 !Constructor->doesThisDeclarationHaveABody() &&
7603 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007604 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007605
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007606 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007607 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007608
Eli Friedman9a14db32012-10-18 20:14:08 +00007609 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007610 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007611 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007612 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007613 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007614 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007615 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007616 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007617 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007618
7619 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007620 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007621
7622 Constructor->setUsed();
7623 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007624
7625 if (ASTMutationListener *L = getASTMutationListener()) {
7626 L->CompletedImplicitDefinition(Constructor);
7627 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007628}
7629
Richard Smith7a614d82011-06-11 17:19:42 +00007630void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007631 // Check that any explicitly-defaulted methods have exception specifications
7632 // compatible with their implicit exception specifications.
7633 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007634}
7635
Richard Smith07b0fdc2013-03-18 21:12:30 +00007636void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
Sebastian Redlf677ea32011-02-05 19:23:19 +00007637 // We start with an initial pass over the base classes to collect those that
7638 // inherit constructors from. If there are none, we can forgo all further
7639 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007640 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007641 BasesVector BasesToInheritFrom;
7642 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7643 BaseE = ClassDecl->bases_end();
7644 BaseIt != BaseE; ++BaseIt) {
7645 if (BaseIt->getInheritConstructors()) {
7646 QualType Base = BaseIt->getType();
7647 if (Base->isDependentType()) {
7648 // If we inherit constructors from anything that is dependent, just
7649 // abort processing altogether. We'll get another chance for the
7650 // instantiations.
Richard Smith07b0fdc2013-03-18 21:12:30 +00007651 // FIXME: We need to ensure that any call to a constructor of this class
7652 // is considered instantiation-dependent in this case.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007653 return;
7654 }
7655 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7656 }
7657 }
7658 if (BasesToInheritFrom.empty())
7659 return;
7660
Richard Smith07b0fdc2013-03-18 21:12:30 +00007661 // FIXME: Constructor templates.
7662
Sebastian Redlf677ea32011-02-05 19:23:19 +00007663 // Now collect the constructors that we already have in the current class.
7664 // Those take precedence over inherited constructors.
Richard Smith07b0fdc2013-03-18 21:12:30 +00007665 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007666 // unless there is a user-declared constructor with the same signature in
7667 // the class where the using-declaration appears.
7668 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7669 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7670 CtorE = ClassDecl->ctor_end();
Richard Smith07b0fdc2013-03-18 21:12:30 +00007671 CtorIt != CtorE; ++CtorIt)
Sebastian Redlf677ea32011-02-05 19:23:19 +00007672 ExistingConstructors.insert(
7673 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007674
Sebastian Redlf677ea32011-02-05 19:23:19 +00007675 DeclarationName CreatedCtorName =
7676 Context.DeclarationNames.getCXXConstructorName(
7677 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7678
7679 // Now comes the true work.
7680 // First, we keep a map from constructor types to the base that introduced
7681 // them. Needed for finding conflicting constructors. We also keep the
7682 // actually inserted declarations in there, for pretty diagnostics.
7683 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7684 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7685 ConstructorToSourceMap InheritedConstructors;
7686 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7687 BaseE = BasesToInheritFrom.end();
7688 BaseIt != BaseE; ++BaseIt) {
7689 const RecordType *Base = *BaseIt;
7690 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7691 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7692 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7693 CtorE = BaseDecl->ctor_end();
7694 CtorIt != CtorE; ++CtorIt) {
7695 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00007696 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00007697 DeclarationName Name =
7698 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00007699 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7700 LookupQualifiedName(Result, CurContext);
7701 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007702 SourceLocation UsingLoc = UD ? UD->getLocation() :
7703 ClassDecl->getLocation();
7704
Richard Smith07b0fdc2013-03-18 21:12:30 +00007705 // C++11 [class.inhctor]p1:
7706 // The candidate set of inherited constructors from the class X named in
7707 // the using-declaration consists of actual constructors and notional
7708 // constructors that result from the transformation of defaulted
7709 // parameters as follows:
7710 // - all non-template constructors of X, and
Sebastian Redlf677ea32011-02-05 19:23:19 +00007711 // - for each non-template constructor of X that has at least one
7712 // parameter with a default argument, the set of constructors that
7713 // results from omitting any ellipsis parameter specification and
7714 // successively omitting parameters with a default argument from the
Richard Smith07b0fdc2013-03-18 21:12:30 +00007715 // end of the parameter-type-list, and
7716 // FIXME: ...also constructor templates.
David Blaikie581deb32012-06-06 20:45:41 +00007717 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007718 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7719 const FunctionProtoType *BaseCtorType =
7720 BaseCtor->getType()->getAs<FunctionProtoType>();
7721
Richard Smith07b0fdc2013-03-18 21:12:30 +00007722 // Determine whether this would be a copy or move constructor for the
7723 // derived class.
7724 if (BaseCtorType->getNumArgs() >= 1 &&
7725 BaseCtorType->getArgType(0)->isReferenceType() &&
7726 Context.hasSameUnqualifiedType(
7727 BaseCtorType->getArgType(0)->getPointeeType(),
7728 Context.getTagDeclType(ClassDecl)))
7729 CanBeCopyOrMove = true;
7730
7731 ArrayRef<QualType> ArgTypes(BaseCtorType->getArgTypes());
7732 FunctionProtoType::ExtProtoInfo EPI = BaseCtorType->getExtProtoInfo();
7733 // Core issue (no number yet): the ellipsis is always discarded.
7734 if (EPI.Variadic) {
7735 Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7736 Diag(BaseCtor->getLocation(),
7737 diag::note_using_decl_constructor_ellipsis);
7738 EPI.Variadic = false;
7739 }
7740
7741 for (unsigned Params = BaseCtor->getMinRequiredArguments(),
7742 MaxParams = BaseCtor->getNumParams();
7743 Params <= MaxParams; ++Params) {
Sebastian Redlf677ea32011-02-05 19:23:19 +00007744 // Skip default constructors. They're never inherited.
Richard Smith07b0fdc2013-03-18 21:12:30 +00007745 if (Params == 0)
Sebastian Redlf677ea32011-02-05 19:23:19 +00007746 continue;
Richard Smith07b0fdc2013-03-18 21:12:30 +00007747
7748 // Skip copy and move constructors for both base and derived class
7749 // for the same reason.
7750 if (CanBeCopyOrMove && Params == 1)
Sebastian Redlf677ea32011-02-05 19:23:19 +00007751 continue;
7752
7753 // Build up a function type for this particular constructor.
Richard Smith07b0fdc2013-03-18 21:12:30 +00007754 QualType NewCtorType =
7755 Context.getFunctionType(Context.VoidTy, ArgTypes.slice(0, Params),
7756 EPI);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007757 const Type *CanonicalNewCtorType =
Richard Smith07b0fdc2013-03-18 21:12:30 +00007758 Context.getCanonicalType(NewCtorType).getTypePtr();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007759
Richard Smith07b0fdc2013-03-18 21:12:30 +00007760 // C++11 [class.inhctor]p3:
7761 // ... a constructor is implicitly declared with the same constructor
7762 // characteristics unless there is a user-declared constructor with
7763 // the same signature in the class where the using-declaration appears
Sebastian Redlf677ea32011-02-05 19:23:19 +00007764 if (ExistingConstructors.count(CanonicalNewCtorType))
7765 continue;
7766
Richard Smith07b0fdc2013-03-18 21:12:30 +00007767 // C++11 [class.inhctor]p7:
7768 // If two using-declarations declare inheriting constructors with the
7769 // same signature, the program is ill-formed
Sebastian Redlf677ea32011-02-05 19:23:19 +00007770 std::pair<ConstructorToSourceMap::iterator, bool> result =
7771 InheritedConstructors.insert(std::make_pair(
7772 CanonicalNewCtorType,
7773 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7774 if (!result.second) {
7775 // Already in the map. If it came from a different class, that's an
7776 // error. Not if it's from the same.
7777 CanQualType PreviousBase = result.first->second.first;
7778 if (CanonicalBase != PreviousBase) {
7779 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7780 const CXXConstructorDecl *PrevBaseCtor =
7781 PrevCtor->getInheritedConstructor();
7782 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7783
7784 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7785 Diag(BaseCtor->getLocation(),
7786 diag::note_using_decl_constructor_conflict_current_ctor);
7787 Diag(PrevBaseCtor->getLocation(),
7788 diag::note_using_decl_constructor_conflict_previous_ctor);
7789 Diag(PrevCtor->getLocation(),
7790 diag::note_using_decl_constructor_conflict_previous_using);
Richard Smith07b0fdc2013-03-18 21:12:30 +00007791 } else {
7792 // Core issue (no number): if the same inheriting constructor is
7793 // produced by multiple base class constructors from the same base
7794 // class, the inheriting constructor is defined as deleted.
7795 result.first->second.second->setDeletedAsWritten();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007796 }
7797 continue;
7798 }
7799
7800 // OK, we're there, now add the constructor.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007801 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7802 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Richard Smith07b0fdc2013-03-18 21:12:30 +00007803 Context, ClassDecl, UsingLoc, DNI, NewCtorType,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007804 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smith07b0fdc2013-03-18 21:12:30 +00007805 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007806 NewCtor->setAccess(BaseCtor->getAccess());
7807
Richard Smith07b0fdc2013-03-18 21:12:30 +00007808 // Build an unevaluated exception specification for this constructor.
7809 EPI.ExceptionSpecType = EST_Unevaluated;
7810 EPI.ExceptionSpecDecl = NewCtor;
7811 NewCtor->setType(Context.getFunctionType(Context.VoidTy,
7812 ArgTypes.slice(0, Params),
7813 EPI));
7814
Sebastian Redlf677ea32011-02-05 19:23:19 +00007815 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007816 SmallVector<ParmVarDecl *, 16> ParamDecls;
Richard Smith07b0fdc2013-03-18 21:12:30 +00007817 for (unsigned i = 0; i < Params; ++i) {
7818 ParmVarDecl *PD = ParmVarDecl::Create(Context, NewCtor,
7819 UsingLoc, UsingLoc,
7820 /*IdentifierInfo=*/0,
7821 BaseCtorType->getArgType(i),
7822 /*TInfo=*/0, SC_None,
7823 SC_None, /*DefaultArg=*/0);
7824 PD->setScopeInfo(0, i);
7825 PD->setImplicit();
7826 ParamDecls.push_back(PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007827 }
David Blaikie4278c652011-09-21 18:16:56 +00007828 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007829 NewCtor->setInheritedConstructor(BaseCtor);
Richard Smith07b0fdc2013-03-18 21:12:30 +00007830 if (BaseCtor->isDeleted())
7831 NewCtor->setDeletedAsWritten();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007832
Sebastian Redlf677ea32011-02-05 19:23:19 +00007833 ClassDecl->addDecl(NewCtor);
7834 result.first->second.second = NewCtor;
7835 }
7836 }
7837 }
7838}
7839
Richard Smith07b0fdc2013-03-18 21:12:30 +00007840void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
7841 CXXConstructorDecl *Constructor) {
7842 CXXRecordDecl *ClassDecl = Constructor->getParent();
7843 assert(Constructor->getInheritedConstructor() &&
7844 !Constructor->doesThisDeclarationHaveABody() &&
7845 !Constructor->isDeleted());
7846
7847 SynthesizedFunctionScope Scope(*this, Constructor);
7848 DiagnosticErrorTrap Trap(Diags);
7849 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
7850 Trap.hasErrorOccurred()) {
7851 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
7852 << Context.getTagDeclType(ClassDecl);
7853 Constructor->setInvalidDecl();
7854 return;
7855 }
7856
7857 SourceLocation Loc = Constructor->getLocation();
7858 Constructor->setBody(new (Context) CompoundStmt(Loc));
7859
7860 Constructor->setUsed();
7861 MarkVTableUsed(CurrentLocation, ClassDecl);
7862
7863 if (ASTMutationListener *L = getASTMutationListener()) {
7864 L->CompletedImplicitDefinition(Constructor);
7865 }
7866}
7867
7868
Sean Huntcb45a0f2011-05-12 22:46:25 +00007869Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007870Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7871 CXXRecordDecl *ClassDecl = MD->getParent();
7872
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007873 // C++ [except.spec]p14:
7874 // An implicitly declared special member function (Clause 12) shall have
7875 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007876 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007877 if (ClassDecl->isInvalidDecl())
7878 return ExceptSpec;
7879
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007880 // Direct base-class destructors.
7881 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7882 BEnd = ClassDecl->bases_end();
7883 B != BEnd; ++B) {
7884 if (B->isVirtual()) // Handled below.
7885 continue;
7886
7887 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007888 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007889 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007890 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007891
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007892 // Virtual base-class destructors.
7893 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7894 BEnd = ClassDecl->vbases_end();
7895 B != BEnd; ++B) {
7896 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007897 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007898 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007899 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007900
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007901 // Field destructors.
7902 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7903 FEnd = ClassDecl->field_end();
7904 F != FEnd; ++F) {
7905 if (const RecordType *RecordTy
7906 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007907 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007908 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007909 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007910
Sean Huntcb45a0f2011-05-12 22:46:25 +00007911 return ExceptSpec;
7912}
7913
7914CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7915 // C++ [class.dtor]p2:
7916 // If a class has no user-declared destructor, a destructor is
7917 // declared implicitly. An implicitly-declared destructor is an
7918 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00007919 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00007920
Richard Smithafb49182012-11-29 01:34:07 +00007921 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7922 if (DSM.isAlreadyBeingDeclared())
7923 return 0;
7924
Douglas Gregor4923aa22010-07-02 20:37:36 +00007925 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007926 CanQualType ClassType
7927 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007928 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007929 DeclarationName Name
7930 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007931 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007932 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007933 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7934 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007935 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007936 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007937 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007938 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007939
7940 // Build an exception specification pointing back at this destructor.
7941 FunctionProtoType::ExtProtoInfo EPI;
7942 EPI.ExceptionSpecType = EST_Unevaluated;
7943 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00007944 Destructor->setType(Context.getFunctionType(Context.VoidTy,
7945 ArrayRef<QualType>(),
7946 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007947
Richard Smithbc2a35d2012-12-08 08:32:28 +00007948 AddOverriddenMethods(ClassDecl, Destructor);
7949
7950 // We don't need to use SpecialMemberIsTrivial here; triviality for
7951 // destructors is easy to compute.
7952 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7953
7954 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7955 Destructor->setDeletedAsWritten();
7956
Douglas Gregor4923aa22010-07-02 20:37:36 +00007957 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007958 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007959
Douglas Gregor4923aa22010-07-02 20:37:36 +00007960 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007961 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007962 PushOnScopeChains(Destructor, S, false);
7963 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007964
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007965 return Destructor;
7966}
7967
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007968void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007969 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007970 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007971 !Destructor->doesThisDeclarationHaveABody() &&
7972 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007973 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007974 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007975 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007976
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007977 if (Destructor->isInvalidDecl())
7978 return;
7979
Eli Friedman9a14db32012-10-18 20:14:08 +00007980 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007981
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007982 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007983 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7984 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007985
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007986 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007987 Diag(CurrentLocation, diag::note_member_synthesized_at)
7988 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7989
7990 Destructor->setInvalidDecl();
7991 return;
7992 }
7993
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007994 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007995 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007996 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007997 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007998 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007999
8000 if (ASTMutationListener *L = getASTMutationListener()) {
8001 L->CompletedImplicitDefinition(Destructor);
8002 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008003}
8004
Richard Smitha4156b82012-04-21 18:42:51 +00008005/// \brief Perform any semantic analysis which needs to be delayed until all
8006/// pending class member declarations have been parsed.
8007void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008008 // If the context is an invalid C++ class, just suppress these checks.
8009 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8010 if (Record->isInvalidDecl()) {
8011 DelayedDestructorExceptionSpecChecks.clear();
8012 return;
8013 }
8014 }
8015
Richard Smitha4156b82012-04-21 18:42:51 +00008016 // Perform any deferred checking of exception specifications for virtual
8017 // destructors.
8018 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8019 i != e; ++i) {
8020 const CXXDestructorDecl *Dtor =
8021 DelayedDestructorExceptionSpecChecks[i].first;
8022 assert(!Dtor->getParent()->isDependentType() &&
8023 "Should not ever add destructors of templates into the list.");
8024 CheckOverridingFunctionExceptionSpec(Dtor,
8025 DelayedDestructorExceptionSpecChecks[i].second);
8026 }
8027 DelayedDestructorExceptionSpecChecks.clear();
8028}
8029
Richard Smithb9d0b762012-07-27 04:22:15 +00008030void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8031 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008032 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008033 "adjusting dtor exception specs was introduced in c++11");
8034
Sebastian Redl0ee33912011-05-19 05:13:44 +00008035 // C++11 [class.dtor]p3:
8036 // A declaration of a destructor that does not have an exception-
8037 // specification is implicitly considered to have the same exception-
8038 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008039 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008040 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008041 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008042 return;
8043
Chandler Carruth3f224b22011-09-20 04:55:26 +00008044 // Replace the destructor's type, building off the existing one. Fortunately,
8045 // the only thing of interest in the destructor type is its extended info.
8046 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008047 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8048 EPI.ExceptionSpecType = EST_Unevaluated;
8049 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00008050 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8051 ArrayRef<QualType>(),
8052 EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008053
Sebastian Redl0ee33912011-05-19 05:13:44 +00008054 // FIXME: If the destructor has a body that could throw, and the newly created
8055 // spec doesn't allow exceptions, we should emit a warning, because this
8056 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008057 // However, we don't have a body or an exception specification yet, so it
8058 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008059}
8060
Richard Smith8c889532012-11-14 00:50:40 +00008061/// When generating a defaulted copy or move assignment operator, if a field
8062/// should be copied with __builtin_memcpy rather than via explicit assignments,
8063/// do so. This optimization only applies for arrays of scalars, and for arrays
8064/// of class type where the selected copy/move-assignment operator is trivial.
8065static StmtResult
8066buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8067 Expr *To, Expr *From) {
8068 // Compute the size of the memory buffer to be copied.
8069 QualType SizeType = S.Context.getSizeType();
8070 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8071 S.Context.getTypeSizeInChars(T).getQuantity());
8072
8073 // Take the address of the field references for "from" and "to". We
8074 // directly construct UnaryOperators here because semantic analysis
8075 // does not permit us to take the address of an xvalue.
8076 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8077 S.Context.getPointerType(From->getType()),
8078 VK_RValue, OK_Ordinary, Loc);
8079 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8080 S.Context.getPointerType(To->getType()),
8081 VK_RValue, OK_Ordinary, Loc);
8082
8083 const Type *E = T->getBaseElementTypeUnsafe();
8084 bool NeedsCollectableMemCpy =
8085 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8086
8087 // Create a reference to the __builtin_objc_memmove_collectable function
8088 StringRef MemCpyName = NeedsCollectableMemCpy ?
8089 "__builtin_objc_memmove_collectable" :
8090 "__builtin_memcpy";
8091 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8092 Sema::LookupOrdinaryName);
8093 S.LookupName(R, S.TUScope, true);
8094
8095 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8096 if (!MemCpy)
8097 // Something went horribly wrong earlier, and we will have complained
8098 // about it.
8099 return StmtError();
8100
8101 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8102 VK_RValue, Loc, 0);
8103 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8104
8105 Expr *CallArgs[] = {
8106 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8107 };
8108 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8109 Loc, CallArgs, Loc);
8110
8111 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8112 return S.Owned(Call.takeAs<Stmt>());
8113}
8114
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008115/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008116/// \c To.
8117///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008118/// This routine is used to copy/move the members of a class with an
8119/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008120/// copied are arrays, this routine builds for loops to copy them.
8121///
8122/// \param S The Sema object used for type-checking.
8123///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008124/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008125///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008126/// \param T The type of the expressions being copied/moved. Both expressions
8127/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008128///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008129/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008130///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008131/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008132///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008133/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008134/// Otherwise, it's a non-static member subobject.
8135///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008136/// \param Copying Whether we're copying or moving.
8137///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008138/// \param Depth Internal parameter recording the depth of the recursion.
8139///
Richard Smith8c889532012-11-14 00:50:40 +00008140/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8141/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008142static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008143buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8144 Expr *To, Expr *From,
8145 bool CopyingBaseSubobject, bool Copying,
8146 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008147 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008148 // Each subobject is assigned in the manner appropriate to its type:
8149 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008150 // - if the subobject is of class type, as if by a call to operator= with
8151 // the subobject as the object expression and the corresponding
8152 // subobject of x as a single function argument (as if by explicit
8153 // qualification; that is, ignoring any possible virtual overriding
8154 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008155 //
8156 // C++03 [class.copy]p13:
8157 // - if the subobject is of class type, the copy assignment operator for
8158 // the class is used (as if by explicit qualification; that is,
8159 // ignoring any possible virtual overriding functions in more derived
8160 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008161 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8162 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008163
Douglas Gregor06a9f362010-05-01 20:49:11 +00008164 // Look for operator=.
8165 DeclarationName Name
8166 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8167 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8168 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008169
Richard Smith044c8aa2012-11-13 00:54:12 +00008170 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8171 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008172 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008173 LookupResult::Filter F = OpLookup.makeFilter();
8174 while (F.hasNext()) {
8175 NamedDecl *D = F.next();
8176 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8177 if (Method->isCopyAssignmentOperator() ||
8178 (!Copying && Method->isMoveAssignmentOperator()))
8179 continue;
8180
8181 F.erase();
8182 }
8183 F.done();
John McCallb0207482010-03-16 06:11:48 +00008184 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008185
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008186 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008187 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008188 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008189 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008190 // ambiguities), we need to cast "this" to that subobject type; to
8191 // ensure that we don't go through the virtual call mechanism, we need
8192 // to qualify the operator= name with the base class (see below). However,
8193 // this means that if the base class has a protected copy assignment
8194 // operator, the protected member access check will fail. So, we
8195 // rewrite "protected" access to "public" access in this case, since we
8196 // know by construction that we're calling from a derived class.
8197 if (CopyingBaseSubobject) {
8198 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8199 L != LEnd; ++L) {
8200 if (L.getAccess() == AS_protected)
8201 L.setAccess(AS_public);
8202 }
8203 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008204
Douglas Gregor06a9f362010-05-01 20:49:11 +00008205 // Create the nested-name-specifier that will be used to qualify the
8206 // reference to operator=; this is required to suppress the virtual
8207 // call mechanism.
8208 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008209 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008210 SS.MakeTrivial(S.Context,
8211 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008212 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008213 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008214
Douglas Gregor06a9f362010-05-01 20:49:11 +00008215 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008216 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008217 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008218 /*TemplateKWLoc=*/SourceLocation(),
8219 /*FirstQualifierInScope=*/0,
8220 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008221 /*TemplateArgs=*/0,
8222 /*SuppressQualifierCheck=*/true);
8223 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008224 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008225
Douglas Gregor06a9f362010-05-01 20:49:11 +00008226 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008227
Richard Smith044c8aa2012-11-13 00:54:12 +00008228 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008229 OpEqualRef.takeAs<Expr>(),
8230 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008231 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008232 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008233
Richard Smith8c889532012-11-14 00:50:40 +00008234 // If we built a call to a trivial 'operator=' while copying an array,
8235 // bail out. We'll replace the whole shebang with a memcpy.
8236 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8237 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8238 return StmtResult((Stmt*)0);
8239
Richard Smith044c8aa2012-11-13 00:54:12 +00008240 // Convert to an expression-statement, and clean up any produced
8241 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008242 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008243 }
John McCallb0207482010-03-16 06:11:48 +00008244
Richard Smith044c8aa2012-11-13 00:54:12 +00008245 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008246 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008247 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008248 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008249 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008250 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008251 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008252 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008253 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008254
8255 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008256 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008257
Douglas Gregor06a9f362010-05-01 20:49:11 +00008258 // Construct a loop over the array bounds, e.g.,
8259 //
8260 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8261 //
8262 // that will copy each of the array elements.
8263 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008264
Douglas Gregor06a9f362010-05-01 20:49:11 +00008265 // Create the iteration variable.
8266 IdentifierInfo *IterationVarName = 0;
8267 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008268 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008269 llvm::raw_svector_ostream OS(Str);
8270 OS << "__i" << Depth;
8271 IterationVarName = &S.Context.Idents.get(OS.str());
8272 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008273 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008274 IterationVarName, SizeType,
8275 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00008276 SC_None, SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008277
Douglas Gregor06a9f362010-05-01 20:49:11 +00008278 // Initialize the iteration variable to zero.
8279 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008280 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008281
8282 // Create a reference to the iteration variable; we'll use this several
8283 // times throughout.
8284 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008285 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008286 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008287 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8288 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8289
Douglas Gregor06a9f362010-05-01 20:49:11 +00008290 // Create the DeclStmt that holds the iteration variable.
8291 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008292
Douglas Gregor06a9f362010-05-01 20:49:11 +00008293 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008294 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008295 IterationVarRefRVal,
8296 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008297 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008298 IterationVarRefRVal,
8299 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008300 if (!Copying) // Cast to rvalue
8301 From = CastForMoving(S, From);
8302
8303 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008304 StmtResult Copy =
8305 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8306 To, From, CopyingBaseSubobject,
8307 Copying, Depth + 1);
8308 // Bail out if copying fails or if we determined that we should use memcpy.
8309 if (Copy.isInvalid() || !Copy.get())
8310 return Copy;
8311
8312 // Create the comparison against the array bound.
8313 llvm::APInt Upper
8314 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8315 Expr *Comparison
8316 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8317 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8318 BO_NE, S.Context.BoolTy,
8319 VK_RValue, OK_Ordinary, Loc, false);
8320
8321 // Create the pre-increment of the iteration variable.
8322 Expr *Increment
8323 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8324 VK_LValue, OK_Ordinary, Loc);
8325
Douglas Gregor06a9f362010-05-01 20:49:11 +00008326 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008327 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008328 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008329 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008330 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008331}
8332
Richard Smith8c889532012-11-14 00:50:40 +00008333static StmtResult
8334buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8335 Expr *To, Expr *From,
8336 bool CopyingBaseSubobject, bool Copying) {
8337 // Maybe we should use a memcpy?
8338 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8339 T.isTriviallyCopyableType(S.Context))
8340 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8341
8342 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8343 CopyingBaseSubobject,
8344 Copying, 0));
8345
8346 // If we ended up picking a trivial assignment operator for an array of a
8347 // non-trivially-copyable class type, just emit a memcpy.
8348 if (!Result.isInvalid() && !Result.get())
8349 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8350
8351 return Result;
8352}
8353
Richard Smithb9d0b762012-07-27 04:22:15 +00008354Sema::ImplicitExceptionSpecification
8355Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8356 CXXRecordDecl *ClassDecl = MD->getParent();
8357
8358 ImplicitExceptionSpecification ExceptSpec(*this);
8359 if (ClassDecl->isInvalidDecl())
8360 return ExceptSpec;
8361
8362 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8363 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8364 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8365
Douglas Gregorb87786f2010-07-01 17:48:08 +00008366 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008367 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008368 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008369
8370 // It is unspecified whether or not an implicit copy assignment operator
8371 // attempts to deduplicate calls to assignment operators of virtual bases are
8372 // made. As such, this exception specification is effectively unspecified.
8373 // Based on a similar decision made for constness in C++0x, we're erring on
8374 // the side of assuming such calls to be made regardless of whether they
8375 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008376 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8377 BaseEnd = ClassDecl->bases_end();
8378 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008379 if (Base->isVirtual())
8380 continue;
8381
Douglas Gregora376d102010-07-02 21:50:04 +00008382 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008383 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008384 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8385 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008386 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008387 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008388
8389 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8390 BaseEnd = ClassDecl->vbases_end();
8391 Base != BaseEnd; ++Base) {
8392 CXXRecordDecl *BaseClassDecl
8393 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8394 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8395 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008396 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008397 }
8398
Douglas Gregorb87786f2010-07-01 17:48:08 +00008399 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8400 FieldEnd = ClassDecl->field_end();
8401 Field != FieldEnd;
8402 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008403 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008404 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8405 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008406 LookupCopyingAssignment(FieldClassDecl,
8407 ArgQuals | FieldType.getCVRQualifiers(),
8408 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008409 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008410 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008411 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008412
Richard Smithb9d0b762012-07-27 04:22:15 +00008413 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008414}
8415
8416CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8417 // Note: The following rules are largely analoguous to the copy
8418 // constructor rules. Note that virtual bases are not taken into account
8419 // for determining the argument type of the operator. Note also that
8420 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008421 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008422
Richard Smithafb49182012-11-29 01:34:07 +00008423 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8424 if (DSM.isAlreadyBeingDeclared())
8425 return 0;
8426
Sean Hunt30de05c2011-05-14 05:23:20 +00008427 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8428 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008429 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008430 ArgType = ArgType.withConst();
8431 ArgType = Context.getLValueReferenceType(ArgType);
8432
Douglas Gregord3c35902010-07-01 16:36:15 +00008433 // An implicitly-declared copy assignment operator is an inline public
8434 // member of its class.
8435 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008436 SourceLocation ClassLoc = ClassDecl->getLocation();
8437 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008438 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008439 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00008440 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00008441 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008442 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008443 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008444 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008445 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008446 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008447
8448 // Build an exception specification pointing back at this member.
8449 FunctionProtoType::ExtProtoInfo EPI;
8450 EPI.ExceptionSpecType = EST_Unevaluated;
8451 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008452 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008453
Douglas Gregord3c35902010-07-01 16:36:15 +00008454 // Add the parameter to the operator.
8455 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008456 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008457 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008458 SC_None,
8459 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008460 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008461
Richard Smithbc2a35d2012-12-08 08:32:28 +00008462 AddOverriddenMethods(ClassDecl, CopyAssignment);
8463
8464 CopyAssignment->setTrivial(
8465 ClassDecl->needsOverloadResolutionForCopyAssignment()
8466 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8467 : ClassDecl->hasTrivialCopyAssignment());
8468
Nico Weberafcc96a2012-01-23 03:19:29 +00008469 // C++0x [class.copy]p19:
8470 // .... If the class definition does not explicitly declare a copy
8471 // assignment operator, there is no user-declared move constructor, and
8472 // there is no user-declared move assignment operator, a copy assignment
8473 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008474 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00008475 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008476
Richard Smithbc2a35d2012-12-08 08:32:28 +00008477 // Note that we have added this copy-assignment operator.
8478 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8479
8480 if (Scope *S = getScopeForContext(ClassDecl))
8481 PushOnScopeChains(CopyAssignment, S, false);
8482 ClassDecl->addDecl(CopyAssignment);
8483
Douglas Gregord3c35902010-07-01 16:36:15 +00008484 return CopyAssignment;
8485}
8486
Douglas Gregor06a9f362010-05-01 20:49:11 +00008487void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8488 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008489 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008490 CopyAssignOperator->isOverloadedOperator() &&
8491 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008492 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8493 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008494 "DefineImplicitCopyAssignment called for wrong function");
8495
8496 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8497
8498 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8499 CopyAssignOperator->setInvalidDecl();
8500 return;
8501 }
8502
8503 CopyAssignOperator->setUsed();
8504
Eli Friedman9a14db32012-10-18 20:14:08 +00008505 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008506 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008507
8508 // C++0x [class.copy]p30:
8509 // The implicitly-defined or explicitly-defaulted copy assignment operator
8510 // for a non-union class X performs memberwise copy assignment of its
8511 // subobjects. The direct base classes of X are assigned first, in the
8512 // order of their declaration in the base-specifier-list, and then the
8513 // immediate non-static data members of X are assigned, in the order in
8514 // which they were declared in the class definition.
8515
8516 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008517 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008518
8519 // The parameter for the "other" object, which we are copying from.
8520 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8521 Qualifiers OtherQuals = Other->getType().getQualifiers();
8522 QualType OtherRefType = Other->getType();
8523 if (const LValueReferenceType *OtherRef
8524 = OtherRefType->getAs<LValueReferenceType>()) {
8525 OtherRefType = OtherRef->getPointeeType();
8526 OtherQuals = OtherRefType.getQualifiers();
8527 }
8528
8529 // Our location for everything implicitly-generated.
8530 SourceLocation Loc = CopyAssignOperator->getLocation();
8531
8532 // Construct a reference to the "other" object. We'll be using this
8533 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008534 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008535 assert(OtherRef && "Reference to parameter cannot fail!");
8536
8537 // Construct the "this" pointer. We'll be using this throughout the generated
8538 // ASTs.
8539 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8540 assert(This && "Reference to this cannot fail!");
8541
8542 // Assign base classes.
8543 bool Invalid = false;
8544 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8545 E = ClassDecl->bases_end(); Base != E; ++Base) {
8546 // Form the assignment:
8547 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8548 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008549 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008550 Invalid = true;
8551 continue;
8552 }
8553
John McCallf871d0c2010-08-07 06:22:56 +00008554 CXXCastPath BasePath;
8555 BasePath.push_back(Base);
8556
Douglas Gregor06a9f362010-05-01 20:49:11 +00008557 // Construct the "from" expression, which is an implicit cast to the
8558 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008559 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008560 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8561 CK_UncheckedDerivedToBase,
8562 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008563
8564 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008565 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008566
8567 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008568 To = ImpCastExprToType(To.take(),
8569 Context.getCVRQualifiedType(BaseType,
8570 CopyAssignOperator->getTypeQualifiers()),
8571 CK_UncheckedDerivedToBase,
8572 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008573
8574 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008575 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008576 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008577 /*CopyingBaseSubobject=*/true,
8578 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008579 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008580 Diag(CurrentLocation, diag::note_member_synthesized_at)
8581 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8582 CopyAssignOperator->setInvalidDecl();
8583 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008584 }
8585
8586 // Success! Record the copy.
8587 Statements.push_back(Copy.takeAs<Expr>());
8588 }
8589
Douglas Gregor06a9f362010-05-01 20:49:11 +00008590 // Assign non-static members.
8591 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8592 FieldEnd = ClassDecl->field_end();
8593 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008594 if (Field->isUnnamedBitfield())
8595 continue;
8596
Douglas Gregor06a9f362010-05-01 20:49:11 +00008597 // Check for members of reference type; we can't copy those.
8598 if (Field->getType()->isReferenceType()) {
8599 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8600 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8601 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008602 Diag(CurrentLocation, diag::note_member_synthesized_at)
8603 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008604 Invalid = true;
8605 continue;
8606 }
8607
8608 // Check for members of const-qualified, non-class type.
8609 QualType BaseType = Context.getBaseElementType(Field->getType());
8610 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8611 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8612 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8613 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008614 Diag(CurrentLocation, diag::note_member_synthesized_at)
8615 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008616 Invalid = true;
8617 continue;
8618 }
John McCallb77115d2011-06-17 00:18:42 +00008619
8620 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008621 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8622 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008623
8624 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008625 if (FieldType->isIncompleteArrayType()) {
8626 assert(ClassDecl->hasFlexibleArrayMember() &&
8627 "Incomplete array type is not valid");
8628 continue;
8629 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008630
8631 // Build references to the field in the object we're copying from and to.
8632 CXXScopeSpec SS; // Intentionally empty
8633 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8634 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008635 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008636 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008637 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008638 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008639 SS, SourceLocation(), 0,
8640 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008641 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008642 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008643 SS, SourceLocation(), 0,
8644 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008645 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8646 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008647
Douglas Gregor06a9f362010-05-01 20:49:11 +00008648 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008649 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008650 To.get(), From.get(),
8651 /*CopyingBaseSubobject=*/false,
8652 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008653 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008654 Diag(CurrentLocation, diag::note_member_synthesized_at)
8655 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8656 CopyAssignOperator->setInvalidDecl();
8657 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008658 }
8659
8660 // Success! Record the copy.
8661 Statements.push_back(Copy.takeAs<Stmt>());
8662 }
8663
8664 if (!Invalid) {
8665 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008666 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008667
John McCall60d7b3a2010-08-24 06:29:42 +00008668 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008669 if (Return.isInvalid())
8670 Invalid = true;
8671 else {
8672 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008673
8674 if (Trap.hasErrorOccurred()) {
8675 Diag(CurrentLocation, diag::note_member_synthesized_at)
8676 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8677 Invalid = true;
8678 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008679 }
8680 }
8681
8682 if (Invalid) {
8683 CopyAssignOperator->setInvalidDecl();
8684 return;
8685 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008686
8687 StmtResult Body;
8688 {
8689 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008690 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008691 /*isStmtExpr=*/false);
8692 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8693 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008694 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008695
8696 if (ASTMutationListener *L = getASTMutationListener()) {
8697 L->CompletedImplicitDefinition(CopyAssignOperator);
8698 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008699}
8700
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008701Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008702Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8703 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008704
Richard Smithb9d0b762012-07-27 04:22:15 +00008705 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008706 if (ClassDecl->isInvalidDecl())
8707 return ExceptSpec;
8708
8709 // C++0x [except.spec]p14:
8710 // An implicitly declared special member function (Clause 12) shall have an
8711 // exception-specification. [...]
8712
8713 // It is unspecified whether or not an implicit move assignment operator
8714 // attempts to deduplicate calls to assignment operators of virtual bases are
8715 // made. As such, this exception specification is effectively unspecified.
8716 // Based on a similar decision made for constness in C++0x, we're erring on
8717 // the side of assuming such calls to be made regardless of whether they
8718 // actually happen.
8719 // Note that a move constructor is not implicitly declared when there are
8720 // virtual bases, but it can still be user-declared and explicitly defaulted.
8721 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8722 BaseEnd = ClassDecl->bases_end();
8723 Base != BaseEnd; ++Base) {
8724 if (Base->isVirtual())
8725 continue;
8726
8727 CXXRecordDecl *BaseClassDecl
8728 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8729 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008730 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008731 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008732 }
8733
8734 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8735 BaseEnd = ClassDecl->vbases_end();
8736 Base != BaseEnd; ++Base) {
8737 CXXRecordDecl *BaseClassDecl
8738 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8739 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008740 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008741 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008742 }
8743
8744 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8745 FieldEnd = ClassDecl->field_end();
8746 Field != FieldEnd;
8747 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008748 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008749 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008750 if (CXXMethodDecl *MoveAssign =
8751 LookupMovingAssignment(FieldClassDecl,
8752 FieldType.getCVRQualifiers(),
8753 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008754 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008755 }
8756 }
8757
8758 return ExceptSpec;
8759}
8760
Richard Smith1c931be2012-04-02 18:40:40 +00008761/// Determine whether the class type has any direct or indirect virtual base
8762/// classes which have a non-trivial move assignment operator.
8763static bool
8764hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8765 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8766 BaseEnd = ClassDecl->vbases_end();
8767 Base != BaseEnd; ++Base) {
8768 CXXRecordDecl *BaseClass =
8769 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8770
8771 // Try to declare the move assignment. If it would be deleted, then the
8772 // class does not have a non-trivial move assignment.
8773 if (BaseClass->needsImplicitMoveAssignment())
8774 S.DeclareImplicitMoveAssignment(BaseClass);
8775
Richard Smith426391c2012-11-16 00:53:38 +00008776 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008777 return true;
8778 }
8779
8780 return false;
8781}
8782
8783/// Determine whether the given type either has a move constructor or is
8784/// trivially copyable.
8785static bool
8786hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8787 Type = S.Context.getBaseElementType(Type);
8788
8789 // FIXME: Technically, non-trivially-copyable non-class types, such as
8790 // reference types, are supposed to return false here, but that appears
8791 // to be a standard defect.
8792 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008793 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008794 return true;
8795
8796 if (Type.isTriviallyCopyableType(S.Context))
8797 return true;
8798
8799 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008800 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8801 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008802 if (ClassDecl->needsImplicitMoveConstructor())
8803 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008804 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008805 }
8806
Richard Smithe5411b72012-12-01 02:35:44 +00008807 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8808 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008809 if (ClassDecl->needsImplicitMoveAssignment())
8810 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008811 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008812}
8813
8814/// Determine whether all non-static data members and direct or virtual bases
8815/// of class \p ClassDecl have either a move operation, or are trivially
8816/// copyable.
8817static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8818 bool IsConstructor) {
8819 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8820 BaseEnd = ClassDecl->bases_end();
8821 Base != BaseEnd; ++Base) {
8822 if (Base->isVirtual())
8823 continue;
8824
8825 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8826 return false;
8827 }
8828
8829 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8830 BaseEnd = ClassDecl->vbases_end();
8831 Base != BaseEnd; ++Base) {
8832 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8833 return false;
8834 }
8835
8836 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8837 FieldEnd = ClassDecl->field_end();
8838 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008839 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008840 return false;
8841 }
8842
8843 return true;
8844}
8845
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008846CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008847 // C++11 [class.copy]p20:
8848 // If the definition of a class X does not explicitly declare a move
8849 // assignment operator, one will be implicitly declared as defaulted
8850 // if and only if:
8851 //
8852 // - [first 4 bullets]
8853 assert(ClassDecl->needsImplicitMoveAssignment());
8854
Richard Smithafb49182012-11-29 01:34:07 +00008855 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8856 if (DSM.isAlreadyBeingDeclared())
8857 return 0;
8858
Richard Smith1c931be2012-04-02 18:40:40 +00008859 // [Checked after we build the declaration]
8860 // - the move assignment operator would not be implicitly defined as
8861 // deleted,
8862
8863 // [DR1402]:
8864 // - X has no direct or indirect virtual base class with a non-trivial
8865 // move assignment operator, and
8866 // - each of X's non-static data members and direct or virtual base classes
8867 // has a type that either has a move assignment operator or is trivially
8868 // copyable.
8869 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8870 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8871 ClassDecl->setFailedImplicitMoveAssignment();
8872 return 0;
8873 }
8874
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008875 // Note: The following rules are largely analoguous to the move
8876 // constructor rules.
8877
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008878 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8879 QualType RetType = Context.getLValueReferenceType(ArgType);
8880 ArgType = Context.getRValueReferenceType(ArgType);
8881
8882 // An implicitly-declared move assignment operator is an inline public
8883 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008884 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8885 SourceLocation ClassLoc = ClassDecl->getLocation();
8886 DeclarationNameInfo NameInfo(Name, ClassLoc);
8887 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008888 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008889 /*TInfo=*/0, /*isStatic=*/false,
8890 /*StorageClassAsWritten=*/SC_None,
8891 /*isInline=*/true,
8892 /*isConstexpr=*/false,
8893 SourceLocation());
8894 MoveAssignment->setAccess(AS_public);
8895 MoveAssignment->setDefaulted();
8896 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008897
Richard Smithb9d0b762012-07-27 04:22:15 +00008898 // Build an exception specification pointing back at this member.
8899 FunctionProtoType::ExtProtoInfo EPI;
8900 EPI.ExceptionSpecType = EST_Unevaluated;
8901 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008902 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008903
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008904 // Add the parameter to the operator.
8905 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8906 ClassLoc, ClassLoc, /*Id=*/0,
8907 ArgType, /*TInfo=*/0,
8908 SC_None,
8909 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008910 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008911
Richard Smithbc2a35d2012-12-08 08:32:28 +00008912 AddOverriddenMethods(ClassDecl, MoveAssignment);
8913
8914 MoveAssignment->setTrivial(
8915 ClassDecl->needsOverloadResolutionForMoveAssignment()
8916 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8917 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008918
8919 // C++0x [class.copy]p9:
8920 // If the definition of a class X does not explicitly declare a move
8921 // assignment operator, one will be implicitly declared as defaulted if and
8922 // only if:
8923 // [...]
8924 // - the move assignment operator would not be implicitly defined as
8925 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008926 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008927 // Cache this result so that we don't try to generate this over and over
8928 // on every lookup, leaking memory and wasting time.
8929 ClassDecl->setFailedImplicitMoveAssignment();
8930 return 0;
8931 }
8932
Richard Smithbc2a35d2012-12-08 08:32:28 +00008933 // Note that we have added this copy-assignment operator.
8934 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8935
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008936 if (Scope *S = getScopeForContext(ClassDecl))
8937 PushOnScopeChains(MoveAssignment, S, false);
8938 ClassDecl->addDecl(MoveAssignment);
8939
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008940 return MoveAssignment;
8941}
8942
8943void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8944 CXXMethodDecl *MoveAssignOperator) {
8945 assert((MoveAssignOperator->isDefaulted() &&
8946 MoveAssignOperator->isOverloadedOperator() &&
8947 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008948 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8949 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008950 "DefineImplicitMoveAssignment called for wrong function");
8951
8952 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8953
8954 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8955 MoveAssignOperator->setInvalidDecl();
8956 return;
8957 }
8958
8959 MoveAssignOperator->setUsed();
8960
Eli Friedman9a14db32012-10-18 20:14:08 +00008961 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008962 DiagnosticErrorTrap Trap(Diags);
8963
8964 // C++0x [class.copy]p28:
8965 // The implicitly-defined or move assignment operator for a non-union class
8966 // X performs memberwise move assignment of its subobjects. The direct base
8967 // classes of X are assigned first, in the order of their declaration in the
8968 // base-specifier-list, and then the immediate non-static data members of X
8969 // are assigned, in the order in which they were declared in the class
8970 // definition.
8971
8972 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008973 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008974
8975 // The parameter for the "other" object, which we are move from.
8976 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8977 QualType OtherRefType = Other->getType()->
8978 getAs<RValueReferenceType>()->getPointeeType();
8979 assert(OtherRefType.getQualifiers() == 0 &&
8980 "Bad argument type of defaulted move assignment");
8981
8982 // Our location for everything implicitly-generated.
8983 SourceLocation Loc = MoveAssignOperator->getLocation();
8984
8985 // Construct a reference to the "other" object. We'll be using this
8986 // throughout the generated ASTs.
8987 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8988 assert(OtherRef && "Reference to parameter cannot fail!");
8989 // Cast to rvalue.
8990 OtherRef = CastForMoving(*this, OtherRef);
8991
8992 // Construct the "this" pointer. We'll be using this throughout the generated
8993 // ASTs.
8994 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8995 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008996
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008997 // Assign base classes.
8998 bool Invalid = false;
8999 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9000 E = ClassDecl->bases_end(); Base != E; ++Base) {
9001 // Form the assignment:
9002 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9003 QualType BaseType = Base->getType().getUnqualifiedType();
9004 if (!BaseType->isRecordType()) {
9005 Invalid = true;
9006 continue;
9007 }
9008
9009 CXXCastPath BasePath;
9010 BasePath.push_back(Base);
9011
9012 // Construct the "from" expression, which is an implicit cast to the
9013 // appropriately-qualified base type.
9014 Expr *From = OtherRef;
9015 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009016 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009017
9018 // Dereference "this".
9019 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9020
9021 // Implicitly cast "this" to the appropriately-qualified base type.
9022 To = ImpCastExprToType(To.take(),
9023 Context.getCVRQualifiedType(BaseType,
9024 MoveAssignOperator->getTypeQualifiers()),
9025 CK_UncheckedDerivedToBase,
9026 VK_LValue, &BasePath);
9027
9028 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009029 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009030 To.get(), From,
9031 /*CopyingBaseSubobject=*/true,
9032 /*Copying=*/false);
9033 if (Move.isInvalid()) {
9034 Diag(CurrentLocation, diag::note_member_synthesized_at)
9035 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9036 MoveAssignOperator->setInvalidDecl();
9037 return;
9038 }
9039
9040 // Success! Record the move.
9041 Statements.push_back(Move.takeAs<Expr>());
9042 }
9043
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009044 // Assign non-static members.
9045 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9046 FieldEnd = ClassDecl->field_end();
9047 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009048 if (Field->isUnnamedBitfield())
9049 continue;
9050
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009051 // Check for members of reference type; we can't move those.
9052 if (Field->getType()->isReferenceType()) {
9053 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9054 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9055 Diag(Field->getLocation(), diag::note_declared_at);
9056 Diag(CurrentLocation, diag::note_member_synthesized_at)
9057 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9058 Invalid = true;
9059 continue;
9060 }
9061
9062 // Check for members of const-qualified, non-class type.
9063 QualType BaseType = Context.getBaseElementType(Field->getType());
9064 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9065 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9066 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9067 Diag(Field->getLocation(), diag::note_declared_at);
9068 Diag(CurrentLocation, diag::note_member_synthesized_at)
9069 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9070 Invalid = true;
9071 continue;
9072 }
9073
9074 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009075 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9076 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009077
9078 QualType FieldType = Field->getType().getNonReferenceType();
9079 if (FieldType->isIncompleteArrayType()) {
9080 assert(ClassDecl->hasFlexibleArrayMember() &&
9081 "Incomplete array type is not valid");
9082 continue;
9083 }
9084
9085 // Build references to the field in the object we're copying from and to.
9086 CXXScopeSpec SS; // Intentionally empty
9087 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9088 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009089 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009090 MemberLookup.resolveKind();
9091 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9092 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009093 SS, SourceLocation(), 0,
9094 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009095 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9096 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009097 SS, SourceLocation(), 0,
9098 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009099 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9100 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9101
9102 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9103 "Member reference with rvalue base must be rvalue except for reference "
9104 "members, which aren't allowed for move assignment.");
9105
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009106 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009107 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009108 To.get(), From.get(),
9109 /*CopyingBaseSubobject=*/false,
9110 /*Copying=*/false);
9111 if (Move.isInvalid()) {
9112 Diag(CurrentLocation, diag::note_member_synthesized_at)
9113 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9114 MoveAssignOperator->setInvalidDecl();
9115 return;
9116 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009117
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009118 // Success! Record the copy.
9119 Statements.push_back(Move.takeAs<Stmt>());
9120 }
9121
9122 if (!Invalid) {
9123 // Add a "return *this;"
9124 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9125
9126 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9127 if (Return.isInvalid())
9128 Invalid = true;
9129 else {
9130 Statements.push_back(Return.takeAs<Stmt>());
9131
9132 if (Trap.hasErrorOccurred()) {
9133 Diag(CurrentLocation, diag::note_member_synthesized_at)
9134 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9135 Invalid = true;
9136 }
9137 }
9138 }
9139
9140 if (Invalid) {
9141 MoveAssignOperator->setInvalidDecl();
9142 return;
9143 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009144
9145 StmtResult Body;
9146 {
9147 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009148 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009149 /*isStmtExpr=*/false);
9150 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9151 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009152 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9153
9154 if (ASTMutationListener *L = getASTMutationListener()) {
9155 L->CompletedImplicitDefinition(MoveAssignOperator);
9156 }
9157}
9158
Richard Smithb9d0b762012-07-27 04:22:15 +00009159Sema::ImplicitExceptionSpecification
9160Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9161 CXXRecordDecl *ClassDecl = MD->getParent();
9162
9163 ImplicitExceptionSpecification ExceptSpec(*this);
9164 if (ClassDecl->isInvalidDecl())
9165 return ExceptSpec;
9166
9167 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9168 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9169 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9170
Douglas Gregor0d405db2010-07-01 20:59:04 +00009171 // C++ [except.spec]p14:
9172 // An implicitly declared special member function (Clause 12) shall have an
9173 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009174 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9175 BaseEnd = ClassDecl->bases_end();
9176 Base != BaseEnd;
9177 ++Base) {
9178 // Virtual bases are handled below.
9179 if (Base->isVirtual())
9180 continue;
9181
Douglas Gregor22584312010-07-02 23:41:54 +00009182 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009183 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009184 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009185 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009186 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009187 }
9188 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9189 BaseEnd = ClassDecl->vbases_end();
9190 Base != BaseEnd;
9191 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009192 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009193 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009194 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009195 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009196 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009197 }
9198 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9199 FieldEnd = ClassDecl->field_end();
9200 Field != FieldEnd;
9201 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009202 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009203 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9204 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009205 LookupCopyingConstructor(FieldClassDecl,
9206 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009207 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009208 }
9209 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009210
Richard Smithb9d0b762012-07-27 04:22:15 +00009211 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009212}
9213
9214CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9215 CXXRecordDecl *ClassDecl) {
9216 // C++ [class.copy]p4:
9217 // If the class definition does not explicitly declare a copy
9218 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009219 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009220
Richard Smithafb49182012-11-29 01:34:07 +00009221 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9222 if (DSM.isAlreadyBeingDeclared())
9223 return 0;
9224
Sean Hunt49634cf2011-05-13 06:10:58 +00009225 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9226 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009227 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009228 if (Const)
9229 ArgType = ArgType.withConst();
9230 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009231
Richard Smith7756afa2012-06-10 05:43:50 +00009232 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9233 CXXCopyConstructor,
9234 Const);
9235
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009236 DeclarationName Name
9237 = Context.DeclarationNames.getCXXConstructorName(
9238 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009239 SourceLocation ClassLoc = ClassDecl->getLocation();
9240 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009241
9242 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009243 // member of its class.
9244 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009245 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009246 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009247 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009248 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009249 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009250
Richard Smithb9d0b762012-07-27 04:22:15 +00009251 // Build an exception specification pointing back at this member.
9252 FunctionProtoType::ExtProtoInfo EPI;
9253 EPI.ExceptionSpecType = EST_Unevaluated;
9254 EPI.ExceptionSpecDecl = CopyConstructor;
9255 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009256 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009257
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009258 // Add the parameter to the constructor.
9259 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009260 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009261 /*IdentifierInfo=*/0,
9262 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009263 SC_None,
9264 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009265 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009266
Richard Smithbc2a35d2012-12-08 08:32:28 +00009267 CopyConstructor->setTrivial(
9268 ClassDecl->needsOverloadResolutionForCopyConstructor()
9269 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9270 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009271
Nico Weberafcc96a2012-01-23 03:19:29 +00009272 // C++11 [class.copy]p8:
9273 // ... If the class definition does not explicitly declare a copy
9274 // constructor, there is no user-declared move constructor, and there is no
9275 // user-declared move assignment operator, a copy constructor is implicitly
9276 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009277 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00009278 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00009279
Richard Smithbc2a35d2012-12-08 08:32:28 +00009280 // Note that we have declared this constructor.
9281 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9282
9283 if (Scope *S = getScopeForContext(ClassDecl))
9284 PushOnScopeChains(CopyConstructor, S, false);
9285 ClassDecl->addDecl(CopyConstructor);
9286
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009287 return CopyConstructor;
9288}
9289
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009290void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009291 CXXConstructorDecl *CopyConstructor) {
9292 assert((CopyConstructor->isDefaulted() &&
9293 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009294 !CopyConstructor->doesThisDeclarationHaveABody() &&
9295 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009296 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009297
Anders Carlsson63010a72010-04-23 16:24:12 +00009298 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009299 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009300
Eli Friedman9a14db32012-10-18 20:14:08 +00009301 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009302 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009303
David Blaikie93c86172013-01-17 05:26:25 +00009304 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009305 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009306 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009307 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009308 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009309 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009310 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009311 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9312 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009313 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009314 /*isStmtExpr=*/false)
9315 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009316 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009317 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009318
9319 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009320 if (ASTMutationListener *L = getASTMutationListener()) {
9321 L->CompletedImplicitDefinition(CopyConstructor);
9322 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009323}
9324
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009325Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009326Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9327 CXXRecordDecl *ClassDecl = MD->getParent();
9328
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009329 // C++ [except.spec]p14:
9330 // An implicitly declared special member function (Clause 12) shall have an
9331 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009332 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009333 if (ClassDecl->isInvalidDecl())
9334 return ExceptSpec;
9335
9336 // Direct base-class constructors.
9337 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9338 BEnd = ClassDecl->bases_end();
9339 B != BEnd; ++B) {
9340 if (B->isVirtual()) // Handled below.
9341 continue;
9342
9343 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9344 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009345 CXXConstructorDecl *Constructor =
9346 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009347 // If this is a deleted function, add it anyway. This might be conformant
9348 // with the standard. This might not. I'm not sure. It might not matter.
9349 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009350 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009351 }
9352 }
9353
9354 // Virtual base-class constructors.
9355 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9356 BEnd = ClassDecl->vbases_end();
9357 B != BEnd; ++B) {
9358 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9359 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009360 CXXConstructorDecl *Constructor =
9361 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009362 // If this is a deleted function, add it anyway. This might be conformant
9363 // with the standard. This might not. I'm not sure. It might not matter.
9364 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009365 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009366 }
9367 }
9368
9369 // Field constructors.
9370 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9371 FEnd = ClassDecl->field_end();
9372 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009373 QualType FieldType = Context.getBaseElementType(F->getType());
9374 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9375 CXXConstructorDecl *Constructor =
9376 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009377 // If this is a deleted function, add it anyway. This might be conformant
9378 // with the standard. This might not. I'm not sure. It might not matter.
9379 // In particular, the problem is that this function never gets called. It
9380 // might just be ill-formed because this function attempts to refer to
9381 // a deleted function here.
9382 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009383 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009384 }
9385 }
9386
9387 return ExceptSpec;
9388}
9389
9390CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9391 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009392 // C++11 [class.copy]p9:
9393 // If the definition of a class X does not explicitly declare a move
9394 // constructor, one will be implicitly declared as defaulted if and only if:
9395 //
9396 // - [first 4 bullets]
9397 assert(ClassDecl->needsImplicitMoveConstructor());
9398
Richard Smithafb49182012-11-29 01:34:07 +00009399 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9400 if (DSM.isAlreadyBeingDeclared())
9401 return 0;
9402
Richard Smith1c931be2012-04-02 18:40:40 +00009403 // [Checked after we build the declaration]
9404 // - the move assignment operator would not be implicitly defined as
9405 // deleted,
9406
9407 // [DR1402]:
9408 // - each of X's non-static data members and direct or virtual base classes
9409 // has a type that either has a move constructor or is trivially copyable.
9410 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9411 ClassDecl->setFailedImplicitMoveConstructor();
9412 return 0;
9413 }
9414
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009415 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9416 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009417
Richard Smith7756afa2012-06-10 05:43:50 +00009418 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9419 CXXMoveConstructor,
9420 false);
9421
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009422 DeclarationName Name
9423 = Context.DeclarationNames.getCXXConstructorName(
9424 Context.getCanonicalType(ClassType));
9425 SourceLocation ClassLoc = ClassDecl->getLocation();
9426 DeclarationNameInfo NameInfo(Name, ClassLoc);
9427
9428 // C++0x [class.copy]p11:
9429 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009430 // member of its class.
9431 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009432 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009433 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009434 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009435 MoveConstructor->setAccess(AS_public);
9436 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009437
Richard Smithb9d0b762012-07-27 04:22:15 +00009438 // Build an exception specification pointing back at this member.
9439 FunctionProtoType::ExtProtoInfo EPI;
9440 EPI.ExceptionSpecType = EST_Unevaluated;
9441 EPI.ExceptionSpecDecl = MoveConstructor;
9442 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009443 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009444
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009445 // Add the parameter to the constructor.
9446 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9447 ClassLoc, ClassLoc,
9448 /*IdentifierInfo=*/0,
9449 ArgType, /*TInfo=*/0,
9450 SC_None,
9451 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009452 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009453
Richard Smithbc2a35d2012-12-08 08:32:28 +00009454 MoveConstructor->setTrivial(
9455 ClassDecl->needsOverloadResolutionForMoveConstructor()
9456 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9457 : ClassDecl->hasTrivialMoveConstructor());
9458
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009459 // C++0x [class.copy]p9:
9460 // If the definition of a class X does not explicitly declare a move
9461 // constructor, one will be implicitly declared as defaulted if and only if:
9462 // [...]
9463 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009464 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009465 // Cache this result so that we don't try to generate this over and over
9466 // on every lookup, leaking memory and wasting time.
9467 ClassDecl->setFailedImplicitMoveConstructor();
9468 return 0;
9469 }
9470
9471 // Note that we have declared this constructor.
9472 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9473
9474 if (Scope *S = getScopeForContext(ClassDecl))
9475 PushOnScopeChains(MoveConstructor, S, false);
9476 ClassDecl->addDecl(MoveConstructor);
9477
9478 return MoveConstructor;
9479}
9480
9481void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9482 CXXConstructorDecl *MoveConstructor) {
9483 assert((MoveConstructor->isDefaulted() &&
9484 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009485 !MoveConstructor->doesThisDeclarationHaveABody() &&
9486 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009487 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9488
9489 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9490 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9491
Eli Friedman9a14db32012-10-18 20:14:08 +00009492 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009493 DiagnosticErrorTrap Trap(Diags);
9494
David Blaikie93c86172013-01-17 05:26:25 +00009495 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009496 Trap.hasErrorOccurred()) {
9497 Diag(CurrentLocation, diag::note_member_synthesized_at)
9498 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9499 MoveConstructor->setInvalidDecl();
9500 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009501 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009502 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9503 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009504 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009505 /*isStmtExpr=*/false)
9506 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009507 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009508 }
9509
9510 MoveConstructor->setUsed();
9511
9512 if (ASTMutationListener *L = getASTMutationListener()) {
9513 L->CompletedImplicitDefinition(MoveConstructor);
9514 }
9515}
9516
Douglas Gregore4e68d42012-02-15 19:33:52 +00009517bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9518 return FD->isDeleted() &&
9519 (FD->isDefaulted() || FD->isImplicit()) &&
9520 isa<CXXMethodDecl>(FD);
9521}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009522
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009523/// \brief Mark the call operator of the given lambda closure type as "used".
9524static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9525 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009526 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009527 Lambda->lookup(
9528 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009529 CallOperator->setReferenced();
9530 CallOperator->setUsed();
9531}
9532
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009533void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9534 SourceLocation CurrentLocation,
9535 CXXConversionDecl *Conv)
9536{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009537 CXXRecordDecl *Lambda = Conv->getParent();
9538
9539 // Make sure that the lambda call operator is marked used.
9540 markLambdaCallOperatorUsed(*this, Lambda);
9541
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009542 Conv->setUsed();
9543
Eli Friedman9a14db32012-10-18 20:14:08 +00009544 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009545 DiagnosticErrorTrap Trap(Diags);
9546
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009547 // Return the address of the __invoke function.
9548 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9549 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009550 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009551 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9552 VK_LValue, Conv->getLocation()).take();
9553 assert(FunctionRef && "Can't refer to __invoke function?");
9554 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009555 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009556 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009557 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009558
9559 // Fill in the __invoke function with a dummy implementation. IR generation
9560 // will fill in the actual details.
9561 Invoke->setUsed();
9562 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009563 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009564
9565 if (ASTMutationListener *L = getASTMutationListener()) {
9566 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009567 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009568 }
9569}
9570
9571void Sema::DefineImplicitLambdaToBlockPointerConversion(
9572 SourceLocation CurrentLocation,
9573 CXXConversionDecl *Conv)
9574{
9575 Conv->setUsed();
9576
Eli Friedman9a14db32012-10-18 20:14:08 +00009577 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009578 DiagnosticErrorTrap Trap(Diags);
9579
Douglas Gregorac1303e2012-02-22 05:02:47 +00009580 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009581 Expr *This = ActOnCXXThis(CurrentLocation).take();
9582 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009583
Eli Friedman23f02672012-03-01 04:01:32 +00009584 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9585 Conv->getLocation(),
9586 Conv, DerefThis);
9587
9588 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9589 // behavior. Note that only the general conversion function does this
9590 // (since it's unusable otherwise); in the case where we inline the
9591 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009592 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009593 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9594 CK_CopyAndAutoreleaseBlockObject,
9595 BuildBlock.get(), 0, VK_RValue);
9596
9597 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009598 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009599 Conv->setInvalidDecl();
9600 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009601 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009602
Douglas Gregorac1303e2012-02-22 05:02:47 +00009603 // Create the return statement that returns the block from the conversion
9604 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009605 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009606 if (Return.isInvalid()) {
9607 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9608 Conv->setInvalidDecl();
9609 return;
9610 }
9611
9612 // Set the body of the conversion function.
9613 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009614 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009615 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009616 Conv->getLocation()));
9617
Douglas Gregorac1303e2012-02-22 05:02:47 +00009618 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009619 if (ASTMutationListener *L = getASTMutationListener()) {
9620 L->CompletedImplicitDefinition(Conv);
9621 }
9622}
9623
Douglas Gregorf52757d2012-03-10 06:53:13 +00009624/// \brief Determine whether the given list arguments contains exactly one
9625/// "real" (non-default) argument.
9626static bool hasOneRealArgument(MultiExprArg Args) {
9627 switch (Args.size()) {
9628 case 0:
9629 return false;
9630
9631 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009632 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009633 return false;
9634
9635 // fall through
9636 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009637 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009638 }
9639
9640 return false;
9641}
9642
John McCall60d7b3a2010-08-24 06:29:42 +00009643ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009644Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009645 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009646 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009647 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009648 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009649 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009650 unsigned ConstructKind,
9651 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009652 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009653
Douglas Gregor2f599792010-04-02 18:24:57 +00009654 // C++0x [class.copy]p34:
9655 // When certain criteria are met, an implementation is allowed to
9656 // omit the copy/move construction of a class object, even if the
9657 // copy/move constructor and/or destructor for the object have
9658 // side effects. [...]
9659 // - when a temporary class object that has not been bound to a
9660 // reference (12.2) would be copied/moved to a class object
9661 // with the same cv-unqualified type, the copy/move operation
9662 // can be omitted by constructing the temporary object
9663 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009664 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009665 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009666 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009667 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009668 }
Mike Stump1eb44332009-09-09 15:08:12 +00009669
9670 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009671 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009672 IsListInitialization, RequiresZeroInit,
9673 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009674}
9675
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009676/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9677/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009678ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009679Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9680 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009681 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009682 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009683 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009684 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009685 unsigned ConstructKind,
9686 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009687 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009688 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009689 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +00009690 HadMultipleCandidates,
9691 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009692 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9693 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009694}
9695
John McCall68c6c9a2010-02-02 09:10:11 +00009696void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009697 if (VD->isInvalidDecl()) return;
9698
John McCall68c6c9a2010-02-02 09:10:11 +00009699 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009700 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009701 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009702 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009703
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009704 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009705 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009706 CheckDestructorAccess(VD->getLocation(), Destructor,
9707 PDiag(diag::err_access_dtor_var)
9708 << VD->getDeclName()
9709 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009710 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009711
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009712 if (!VD->hasGlobalStorage()) return;
9713
9714 // Emit warning for non-trivial dtor in global scope (a real global,
9715 // class-static, function-static).
9716 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9717
9718 // TODO: this should be re-enabled for static locals by !CXAAtExit
9719 if (!VD->isStaticLocal())
9720 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009721}
9722
Douglas Gregor39da0b82009-09-09 23:08:42 +00009723/// \brief Given a constructor and the set of arguments provided for the
9724/// constructor, convert the arguments and add any required default arguments
9725/// to form a proper call to this constructor.
9726///
9727/// \returns true if an error occurred, false otherwise.
9728bool
9729Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9730 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009731 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009732 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009733 bool AllowExplicit,
9734 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009735 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9736 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009737 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009738
9739 const FunctionProtoType *Proto
9740 = Constructor->getType()->getAs<FunctionProtoType>();
9741 assert(Proto && "Constructor without a prototype?");
9742 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009743
9744 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009745 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009746 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009747 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009748 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009749
9750 VariadicCallType CallType =
9751 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009752 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009753 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9754 Proto, 0, Args, NumArgs, AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009755 CallType, AllowExplicit,
9756 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009757 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009758
9759 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9760
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00009761 CheckConstructorCall(Constructor,
9762 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9763 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +00009764 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009765
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009766 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009767}
9768
Anders Carlsson20d45d22009-12-12 00:32:00 +00009769static inline bool
9770CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9771 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009772 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009773 if (isa<NamespaceDecl>(DC)) {
9774 return SemaRef.Diag(FnDecl->getLocation(),
9775 diag::err_operator_new_delete_declared_in_namespace)
9776 << FnDecl->getDeclName();
9777 }
9778
9779 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009780 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009781 return SemaRef.Diag(FnDecl->getLocation(),
9782 diag::err_operator_new_delete_declared_static)
9783 << FnDecl->getDeclName();
9784 }
9785
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009786 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009787}
9788
Anders Carlsson156c78e2009-12-13 17:53:43 +00009789static inline bool
9790CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9791 CanQualType ExpectedResultType,
9792 CanQualType ExpectedFirstParamType,
9793 unsigned DependentParamTypeDiag,
9794 unsigned InvalidParamTypeDiag) {
9795 QualType ResultType =
9796 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9797
9798 // Check that the result type is not dependent.
9799 if (ResultType->isDependentType())
9800 return SemaRef.Diag(FnDecl->getLocation(),
9801 diag::err_operator_new_delete_dependent_result_type)
9802 << FnDecl->getDeclName() << ExpectedResultType;
9803
9804 // Check that the result type is what we expect.
9805 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9806 return SemaRef.Diag(FnDecl->getLocation(),
9807 diag::err_operator_new_delete_invalid_result_type)
9808 << FnDecl->getDeclName() << ExpectedResultType;
9809
9810 // A function template must have at least 2 parameters.
9811 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9812 return SemaRef.Diag(FnDecl->getLocation(),
9813 diag::err_operator_new_delete_template_too_few_parameters)
9814 << FnDecl->getDeclName();
9815
9816 // The function decl must have at least 1 parameter.
9817 if (FnDecl->getNumParams() == 0)
9818 return SemaRef.Diag(FnDecl->getLocation(),
9819 diag::err_operator_new_delete_too_few_parameters)
9820 << FnDecl->getDeclName();
9821
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009822 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009823 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9824 if (FirstParamType->isDependentType())
9825 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9826 << FnDecl->getDeclName() << ExpectedFirstParamType;
9827
9828 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009829 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009830 ExpectedFirstParamType)
9831 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9832 << FnDecl->getDeclName() << ExpectedFirstParamType;
9833
9834 return false;
9835}
9836
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009837static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009838CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009839 // C++ [basic.stc.dynamic.allocation]p1:
9840 // A program is ill-formed if an allocation function is declared in a
9841 // namespace scope other than global scope or declared static in global
9842 // scope.
9843 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9844 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009845
9846 CanQualType SizeTy =
9847 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9848
9849 // C++ [basic.stc.dynamic.allocation]p1:
9850 // The return type shall be void*. The first parameter shall have type
9851 // std::size_t.
9852 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9853 SizeTy,
9854 diag::err_operator_new_dependent_param_type,
9855 diag::err_operator_new_param_type))
9856 return true;
9857
9858 // C++ [basic.stc.dynamic.allocation]p1:
9859 // The first parameter shall not have an associated default argument.
9860 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009861 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009862 diag::err_operator_new_default_arg)
9863 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9864
9865 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009866}
9867
9868static bool
Richard Smith444d3842012-10-20 08:26:51 +00009869CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009870 // C++ [basic.stc.dynamic.deallocation]p1:
9871 // A program is ill-formed if deallocation functions are declared in a
9872 // namespace scope other than global scope or declared static in global
9873 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009874 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9875 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009876
9877 // C++ [basic.stc.dynamic.deallocation]p2:
9878 // Each deallocation function shall return void and its first parameter
9879 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009880 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9881 SemaRef.Context.VoidPtrTy,
9882 diag::err_operator_delete_dependent_param_type,
9883 diag::err_operator_delete_param_type))
9884 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009885
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009886 return false;
9887}
9888
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009889/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9890/// of this overloaded operator is well-formed. If so, returns false;
9891/// otherwise, emits appropriate diagnostics and returns true.
9892bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009893 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009894 "Expected an overloaded operator declaration");
9895
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009896 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9897
Mike Stump1eb44332009-09-09 15:08:12 +00009898 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009899 // The allocation and deallocation functions, operator new,
9900 // operator new[], operator delete and operator delete[], are
9901 // described completely in 3.7.3. The attributes and restrictions
9902 // found in the rest of this subclause do not apply to them unless
9903 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009904 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009905 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009906
Anders Carlssona3ccda52009-12-12 00:26:23 +00009907 if (Op == OO_New || Op == OO_Array_New)
9908 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009909
9910 // C++ [over.oper]p6:
9911 // An operator function shall either be a non-static member
9912 // function or be a non-member function and have at least one
9913 // parameter whose type is a class, a reference to a class, an
9914 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009915 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9916 if (MethodDecl->isStatic())
9917 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009918 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009919 } else {
9920 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009921 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9922 ParamEnd = FnDecl->param_end();
9923 Param != ParamEnd; ++Param) {
9924 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009925 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9926 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009927 ClassOrEnumParam = true;
9928 break;
9929 }
9930 }
9931
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009932 if (!ClassOrEnumParam)
9933 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009934 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009935 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009936 }
9937
9938 // C++ [over.oper]p8:
9939 // An operator function cannot have default arguments (8.3.6),
9940 // except where explicitly stated below.
9941 //
Mike Stump1eb44332009-09-09 15:08:12 +00009942 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009943 // (C++ [over.call]p1).
9944 if (Op != OO_Call) {
9945 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9946 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009947 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009948 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009949 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009950 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009951 }
9952 }
9953
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009954 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9955 { false, false, false }
9956#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9957 , { Unary, Binary, MemberOnly }
9958#include "clang/Basic/OperatorKinds.def"
9959 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009960
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009961 bool CanBeUnaryOperator = OperatorUses[Op][0];
9962 bool CanBeBinaryOperator = OperatorUses[Op][1];
9963 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009964
9965 // C++ [over.oper]p8:
9966 // [...] Operator functions cannot have more or fewer parameters
9967 // than the number required for the corresponding operator, as
9968 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009969 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009970 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009971 if (Op != OO_Call &&
9972 ((NumParams == 1 && !CanBeUnaryOperator) ||
9973 (NumParams == 2 && !CanBeBinaryOperator) ||
9974 (NumParams < 1) || (NumParams > 2))) {
9975 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009976 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009977 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009978 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009979 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009980 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009981 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009982 assert(CanBeBinaryOperator &&
9983 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009984 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009985 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009986
Chris Lattner416e46f2008-11-21 07:57:12 +00009987 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009988 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009989 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009990
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009991 // Overloaded operators other than operator() cannot be variadic.
9992 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009993 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009994 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009995 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009996 }
9997
9998 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009999 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10000 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010001 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010002 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010003 }
10004
10005 // C++ [over.inc]p1:
10006 // The user-defined function called operator++ implements the
10007 // prefix and postfix ++ operator. If this function is a member
10008 // function with no parameters, or a non-member function with one
10009 // parameter of class or enumeration type, it defines the prefix
10010 // increment operator ++ for objects of that type. If the function
10011 // is a member function with one parameter (which shall be of type
10012 // int) or a non-member function with two parameters (the second
10013 // of which shall be of type int), it defines the postfix
10014 // increment operator ++ for objects of that type.
10015 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10016 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10017 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010018 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010019 ParamIsInt = BT->getKind() == BuiltinType::Int;
10020
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010021 if (!ParamIsInt)
10022 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010023 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010024 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010025 }
10026
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010027 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010028}
Chris Lattner5a003a42008-12-17 07:09:26 +000010029
Sean Hunta6c058d2010-01-13 09:01:02 +000010030/// CheckLiteralOperatorDeclaration - Check whether the declaration
10031/// of this literal operator function is well-formed. If so, returns
10032/// false; otherwise, emits appropriate diagnostics and returns true.
10033bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010034 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010035 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10036 << FnDecl->getDeclName();
10037 return true;
10038 }
10039
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010040 if (FnDecl->isExternC()) {
10041 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10042 return true;
10043 }
10044
Sean Hunta6c058d2010-01-13 09:01:02 +000010045 bool Valid = false;
10046
Richard Smith36f5cfe2012-03-09 08:00:36 +000010047 // This might be the definition of a literal operator template.
10048 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10049 // This might be a specialization of a literal operator template.
10050 if (!TpDecl)
10051 TpDecl = FnDecl->getPrimaryTemplate();
10052
Sean Hunt216c2782010-04-07 23:11:06 +000010053 // template <char...> type operator "" name() is the only valid template
10054 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010055 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010056 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010057 // Must have only one template parameter
10058 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10059 if (Params->size() == 1) {
10060 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010061 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010062
Sean Hunt216c2782010-04-07 23:11:06 +000010063 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010064 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10065 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10066 Valid = true;
10067 }
10068 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010069 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010070 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010071 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10072
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010073 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010074
Sean Hunt30019c02010-04-07 22:57:35 +000010075 // unsigned long long int, long double, and any character type are allowed
10076 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010077 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10078 Context.hasSameType(T, Context.LongDoubleTy) ||
10079 Context.hasSameType(T, Context.CharTy) ||
10080 Context.hasSameType(T, Context.WCharTy) ||
10081 Context.hasSameType(T, Context.Char16Ty) ||
10082 Context.hasSameType(T, Context.Char32Ty)) {
10083 if (++Param == FnDecl->param_end())
10084 Valid = true;
10085 goto FinishedParams;
10086 }
10087
Sean Hunt30019c02010-04-07 22:57:35 +000010088 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010089 const PointerType *PT = T->getAs<PointerType>();
10090 if (!PT)
10091 goto FinishedParams;
10092 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010093 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010094 goto FinishedParams;
10095 T = T.getUnqualifiedType();
10096
10097 // Move on to the second parameter;
10098 ++Param;
10099
10100 // If there is no second parameter, the first must be a const char *
10101 if (Param == FnDecl->param_end()) {
10102 if (Context.hasSameType(T, Context.CharTy))
10103 Valid = true;
10104 goto FinishedParams;
10105 }
10106
10107 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10108 // are allowed as the first parameter to a two-parameter function
10109 if (!(Context.hasSameType(T, Context.CharTy) ||
10110 Context.hasSameType(T, Context.WCharTy) ||
10111 Context.hasSameType(T, Context.Char16Ty) ||
10112 Context.hasSameType(T, Context.Char32Ty)))
10113 goto FinishedParams;
10114
10115 // The second and final parameter must be an std::size_t
10116 T = (*Param)->getType().getUnqualifiedType();
10117 if (Context.hasSameType(T, Context.getSizeType()) &&
10118 ++Param == FnDecl->param_end())
10119 Valid = true;
10120 }
10121
10122 // FIXME: This diagnostic is absolutely terrible.
10123FinishedParams:
10124 if (!Valid) {
10125 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10126 << FnDecl->getDeclName();
10127 return true;
10128 }
10129
Richard Smitha9e88b22012-03-09 08:16:22 +000010130 // A parameter-declaration-clause containing a default argument is not
10131 // equivalent to any of the permitted forms.
10132 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10133 ParamEnd = FnDecl->param_end();
10134 Param != ParamEnd; ++Param) {
10135 if ((*Param)->hasDefaultArg()) {
10136 Diag((*Param)->getDefaultArgRange().getBegin(),
10137 diag::err_literal_operator_default_argument)
10138 << (*Param)->getDefaultArgRange();
10139 break;
10140 }
10141 }
10142
Richard Smith2fb4ae32012-03-08 02:39:21 +000010143 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010144 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10145 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010146 // C++11 [usrlit.suffix]p1:
10147 // Literal suffix identifiers that do not start with an underscore
10148 // are reserved for future standardization.
10149 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010150 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010151
Sean Hunta6c058d2010-01-13 09:01:02 +000010152 return false;
10153}
10154
Douglas Gregor074149e2009-01-05 19:45:36 +000010155/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10156/// linkage specification, including the language and (if present)
10157/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10158/// the location of the language string literal, which is provided
10159/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10160/// the '{' brace. Otherwise, this linkage specification does not
10161/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010162Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10163 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010164 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010165 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010166 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010167 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010168 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010169 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010170 Language = LinkageSpecDecl::lang_cxx;
10171 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010172 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010173 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010174 }
Mike Stump1eb44332009-09-09 15:08:12 +000010175
Chris Lattnercc98eac2008-12-17 07:13:27 +000010176 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010177
Douglas Gregor074149e2009-01-05 19:45:36 +000010178 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010179 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010180 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010181 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010182 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010183}
10184
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010185/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010186/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10187/// valid, it's the position of the closing '}' brace in a linkage
10188/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010189Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010190 Decl *LinkageSpec,
10191 SourceLocation RBraceLoc) {
10192 if (LinkageSpec) {
10193 if (RBraceLoc.isValid()) {
10194 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10195 LSDecl->setRBraceLoc(RBraceLoc);
10196 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010197 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010198 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010199 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010200}
10201
Michael Han684aa732013-02-22 17:15:32 +000010202Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10203 AttributeList *AttrList,
10204 SourceLocation SemiLoc) {
10205 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10206 // Attribute declarations appertain to empty declaration so we handle
10207 // them here.
10208 if (AttrList)
10209 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010210
Michael Han684aa732013-02-22 17:15:32 +000010211 CurContext->addDecl(ED);
10212 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010213}
10214
Douglas Gregord308e622009-05-18 20:51:54 +000010215/// \brief Perform semantic analysis for the variable declaration that
10216/// occurs within a C++ catch clause, returning the newly-created
10217/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010218VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010219 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010220 SourceLocation StartLoc,
10221 SourceLocation Loc,
10222 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010223 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010224 QualType ExDeclType = TInfo->getType();
10225
Sebastian Redl4b07b292008-12-22 19:15:10 +000010226 // Arrays and functions decay.
10227 if (ExDeclType->isArrayType())
10228 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10229 else if (ExDeclType->isFunctionType())
10230 ExDeclType = Context.getPointerType(ExDeclType);
10231
10232 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10233 // The exception-declaration shall not denote a pointer or reference to an
10234 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010235 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010236 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010237 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010238 Invalid = true;
10239 }
Douglas Gregord308e622009-05-18 20:51:54 +000010240
Sebastian Redl4b07b292008-12-22 19:15:10 +000010241 QualType BaseType = ExDeclType;
10242 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010243 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010244 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010245 BaseType = Ptr->getPointeeType();
10246 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010247 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010248 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010249 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010250 BaseType = Ref->getPointeeType();
10251 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010252 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010253 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010254 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010255 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010256 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010257
Mike Stump1eb44332009-09-09 15:08:12 +000010258 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010259 RequireNonAbstractType(Loc, ExDeclType,
10260 diag::err_abstract_type_in_decl,
10261 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010262 Invalid = true;
10263
John McCall5a180392010-07-24 00:37:23 +000010264 // Only the non-fragile NeXT runtime currently supports C++ catches
10265 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010266 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010267 QualType T = ExDeclType;
10268 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10269 T = RT->getPointeeType();
10270
10271 if (T->isObjCObjectType()) {
10272 Diag(Loc, diag::err_objc_object_catch);
10273 Invalid = true;
10274 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010275 // FIXME: should this be a test for macosx-fragile specifically?
10276 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010277 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010278 }
10279 }
10280
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010281 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10282 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010283 ExDecl->setExceptionVariable(true);
10284
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010285 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010286 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010287 Invalid = true;
10288
Douglas Gregorc41b8782011-07-06 18:14:43 +000010289 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010290 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010291 // Insulate this from anything else we might currently be parsing.
10292 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10293
Douglas Gregor6d182892010-03-05 23:38:39 +000010294 // C++ [except.handle]p16:
10295 // The object declared in an exception-declaration or, if the
10296 // exception-declaration does not specify a name, a temporary (12.2) is
10297 // copy-initialized (8.5) from the exception object. [...]
10298 // The object is destroyed when the handler exits, after the destruction
10299 // of any automatic objects initialized within the handler.
10300 //
10301 // We just pretend to initialize the object with itself, then make sure
10302 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010303 QualType initType = ExDeclType;
10304
10305 InitializedEntity entity =
10306 InitializedEntity::InitializeVariable(ExDecl);
10307 InitializationKind initKind =
10308 InitializationKind::CreateCopy(Loc, SourceLocation());
10309
10310 Expr *opaqueValue =
10311 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10312 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10313 ExprResult result = sequence.Perform(*this, entity, initKind,
10314 MultiExprArg(&opaqueValue, 1));
10315 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010316 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010317 else {
10318 // If the constructor used was non-trivial, set this as the
10319 // "initializer".
10320 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10321 if (!construct->getConstructor()->isTrivial()) {
10322 Expr *init = MaybeCreateExprWithCleanups(construct);
10323 ExDecl->setInit(init);
10324 }
10325
10326 // And make sure it's destructable.
10327 FinalizeVarWithDestructor(ExDecl, recordType);
10328 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010329 }
10330 }
10331
Douglas Gregord308e622009-05-18 20:51:54 +000010332 if (Invalid)
10333 ExDecl->setInvalidDecl();
10334
10335 return ExDecl;
10336}
10337
10338/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10339/// handler.
John McCalld226f652010-08-21 09:40:31 +000010340Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010341 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010342 bool Invalid = D.isInvalidType();
10343
10344 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010345 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10346 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010347 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10348 D.getIdentifierLoc());
10349 Invalid = true;
10350 }
10351
Sebastian Redl4b07b292008-12-22 19:15:10 +000010352 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010353 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010354 LookupOrdinaryName,
10355 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010356 // The scope should be freshly made just for us. There is just no way
10357 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010358 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010359 if (PrevDecl->isTemplateParameter()) {
10360 // Maybe we will complain about the shadowed template parameter.
10361 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010362 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010363 }
10364 }
10365
Chris Lattnereaaebc72009-04-25 08:06:05 +000010366 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010367 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10368 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010369 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010370 }
10371
Douglas Gregor83cb9422010-09-09 17:09:21 +000010372 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010373 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010374 D.getIdentifierLoc(),
10375 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010376 if (Invalid)
10377 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010378
Sebastian Redl4b07b292008-12-22 19:15:10 +000010379 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010380 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010381 PushOnScopeChains(ExDecl, S);
10382 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010383 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010384
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010385 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010386 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010387}
Anders Carlssonfb311762009-03-14 00:25:26 +000010388
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010389Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010390 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010391 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010392 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010393 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010394
Richard Smithe3f470a2012-07-11 22:37:56 +000010395 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10396 return 0;
10397
10398 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10399 AssertMessage, RParenLoc, false);
10400}
10401
10402Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10403 Expr *AssertExpr,
10404 StringLiteral *AssertMessage,
10405 SourceLocation RParenLoc,
10406 bool Failed) {
10407 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10408 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010409 // In a static_assert-declaration, the constant-expression shall be a
10410 // constant expression that can be contextually converted to bool.
10411 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10412 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010413 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010414
Richard Smithdaaefc52011-12-14 23:32:26 +000010415 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010416 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010417 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010418 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010419 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010420
Richard Smithe3f470a2012-07-11 22:37:56 +000010421 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010422 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010423 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010424 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010425 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010426 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010427 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010428 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010429 }
Mike Stump1eb44332009-09-09 15:08:12 +000010430
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010431 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010432 AssertExpr, AssertMessage, RParenLoc,
10433 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010434
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010435 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010436 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010437}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010438
Douglas Gregor1d869352010-04-07 16:53:43 +000010439/// \brief Perform semantic analysis of the given friend type declaration.
10440///
10441/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010442FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010443 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010444 TypeSourceInfo *TSInfo) {
10445 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10446
10447 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010448 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010449
Richard Smith6b130222011-10-18 21:39:00 +000010450 // C++03 [class.friend]p2:
10451 // An elaborated-type-specifier shall be used in a friend declaration
10452 // for a class.*
10453 //
10454 // * The class-key of the elaborated-type-specifier is required.
10455 if (!ActiveTemplateInstantiations.empty()) {
10456 // Do not complain about the form of friend template types during
10457 // template instantiation; we will already have complained when the
10458 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010459 } else {
10460 if (!T->isElaboratedTypeSpecifier()) {
10461 // If we evaluated the type to a record type, suggest putting
10462 // a tag in front.
10463 if (const RecordType *RT = T->getAs<RecordType>()) {
10464 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010465
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010466 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010467
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010468 Diag(TypeRange.getBegin(),
10469 getLangOpts().CPlusPlus11 ?
10470 diag::warn_cxx98_compat_unelaborated_friend_type :
10471 diag::ext_unelaborated_friend_type)
10472 << (unsigned) RD->getTagKind()
10473 << T
10474 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10475 InsertionText);
10476 } else {
10477 Diag(FriendLoc,
10478 getLangOpts().CPlusPlus11 ?
10479 diag::warn_cxx98_compat_nonclass_type_friend :
10480 diag::ext_nonclass_type_friend)
10481 << T
10482 << TypeRange;
10483 }
10484 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010485 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010486 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010487 diag::warn_cxx98_compat_enum_friend :
10488 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010489 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010490 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010491 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010492
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010493 // C++11 [class.friend]p3:
10494 // A friend declaration that does not declare a function shall have one
10495 // of the following forms:
10496 // friend elaborated-type-specifier ;
10497 // friend simple-type-specifier ;
10498 // friend typename-specifier ;
10499 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10500 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10501 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010502
Douglas Gregor06245bf2010-04-07 17:57:12 +000010503 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010504 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010505 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010506 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010507}
10508
John McCall9a34edb2010-10-19 01:40:49 +000010509/// Handle a friend tag declaration where the scope specifier was
10510/// templated.
10511Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10512 unsigned TagSpec, SourceLocation TagLoc,
10513 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010514 IdentifierInfo *Name,
10515 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010516 AttributeList *Attr,
10517 MultiTemplateParamsArg TempParamLists) {
10518 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10519
10520 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010521 bool Invalid = false;
10522
10523 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010524 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010525 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010526 TempParamLists.size(),
10527 /*friend*/ true,
10528 isExplicitSpecialization,
10529 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010530 if (TemplateParams->size() > 0) {
10531 // This is a declaration of a class template.
10532 if (Invalid)
10533 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010534
Eric Christopher4110e132011-07-21 05:34:24 +000010535 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10536 SS, Name, NameLoc, Attr,
10537 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010538 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010539 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010540 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010541 } else {
10542 // The "template<>" header is extraneous.
10543 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10544 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10545 isExplicitSpecialization = true;
10546 }
10547 }
10548
10549 if (Invalid) return 0;
10550
John McCall9a34edb2010-10-19 01:40:49 +000010551 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010552 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010553 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010554 isAllExplicitSpecializations = false;
10555 break;
10556 }
10557 }
10558
10559 // FIXME: don't ignore attributes.
10560
10561 // If it's explicit specializations all the way down, just forget
10562 // about the template header and build an appropriate non-templated
10563 // friend. TODO: for source fidelity, remember the headers.
10564 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010565 if (SS.isEmpty()) {
10566 bool Owned = false;
10567 bool IsDependent = false;
10568 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10569 Attr, AS_public,
10570 /*ModulePrivateLoc=*/SourceLocation(),
10571 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010572 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010573 /*ScopedEnumUsesClassTag=*/false,
10574 /*UnderlyingType=*/TypeResult());
10575 }
10576
Douglas Gregor2494dd02011-03-01 01:34:45 +000010577 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010578 ElaboratedTypeKeyword Keyword
10579 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010580 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010581 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010582 if (T.isNull())
10583 return 0;
10584
10585 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10586 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010587 DependentNameTypeLoc TL =
10588 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010589 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010590 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010591 TL.setNameLoc(NameLoc);
10592 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010593 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010594 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010595 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010596 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010597 }
10598
10599 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010600 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010601 Friend->setAccess(AS_public);
10602 CurContext->addDecl(Friend);
10603 return Friend;
10604 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010605
10606 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10607
10608
John McCall9a34edb2010-10-19 01:40:49 +000010609
10610 // Handle the case of a templated-scope friend class. e.g.
10611 // template <class T> class A<T>::B;
10612 // FIXME: we don't support these right now.
10613 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10614 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10615 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010616 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010617 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010618 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010619 TL.setNameLoc(NameLoc);
10620
10621 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010622 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010623 Friend->setAccess(AS_public);
10624 Friend->setUnsupportedFriend(true);
10625 CurContext->addDecl(Friend);
10626 return Friend;
10627}
10628
10629
John McCalldd4a3b02009-09-16 22:47:08 +000010630/// Handle a friend type declaration. This works in tandem with
10631/// ActOnTag.
10632///
10633/// Notes on friend class templates:
10634///
10635/// We generally treat friend class declarations as if they were
10636/// declaring a class. So, for example, the elaborated type specifier
10637/// in a friend declaration is required to obey the restrictions of a
10638/// class-head (i.e. no typedefs in the scope chain), template
10639/// parameters are required to match up with simple template-ids, &c.
10640/// However, unlike when declaring a template specialization, it's
10641/// okay to refer to a template specialization without an empty
10642/// template parameter declaration, e.g.
10643/// friend class A<T>::B<unsigned>;
10644/// We permit this as a special case; if there are any template
10645/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010646/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010647Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010648 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010649 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010650
10651 assert(DS.isFriendSpecified());
10652 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10653
John McCalldd4a3b02009-09-16 22:47:08 +000010654 // Try to convert the decl specifier to a type. This works for
10655 // friend templates because ActOnTag never produces a ClassTemplateDecl
10656 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010657 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010658 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10659 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010660 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010661 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010662
Douglas Gregor6ccab972010-12-16 01:14:37 +000010663 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10664 return 0;
10665
John McCalldd4a3b02009-09-16 22:47:08 +000010666 // This is definitely an error in C++98. It's probably meant to
10667 // be forbidden in C++0x, too, but the specification is just
10668 // poorly written.
10669 //
10670 // The problem is with declarations like the following:
10671 // template <T> friend A<T>::foo;
10672 // where deciding whether a class C is a friend or not now hinges
10673 // on whether there exists an instantiation of A that causes
10674 // 'foo' to equal C. There are restrictions on class-heads
10675 // (which we declare (by fiat) elaborated friend declarations to
10676 // be) that makes this tractable.
10677 //
10678 // FIXME: handle "template <> friend class A<T>;", which
10679 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010680 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010681 Diag(Loc, diag::err_tagless_friend_type_template)
10682 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010683 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010684 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010685
John McCall02cace72009-08-28 07:59:38 +000010686 // C++98 [class.friend]p1: A friend of a class is a function
10687 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010688 // This is fixed in DR77, which just barely didn't make the C++03
10689 // deadline. It's also a very silly restriction that seriously
10690 // affects inner classes and which nobody else seems to implement;
10691 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010692 //
10693 // But note that we could warn about it: it's always useless to
10694 // friend one of your own members (it's not, however, worthless to
10695 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010696
John McCalldd4a3b02009-09-16 22:47:08 +000010697 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010698 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010699 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010700 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010701 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010702 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010703 DS.getFriendSpecLoc());
10704 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010705 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010706
10707 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010708 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010709
John McCalldd4a3b02009-09-16 22:47:08 +000010710 D->setAccess(AS_public);
10711 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010712
John McCalld226f652010-08-21 09:40:31 +000010713 return D;
John McCall02cace72009-08-28 07:59:38 +000010714}
10715
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000010716NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10717 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010718 const DeclSpec &DS = D.getDeclSpec();
10719
10720 assert(DS.isFriendSpecified());
10721 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10722
10723 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010724 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010725
10726 // C++ [class.friend]p1
10727 // A friend of a class is a function or class....
10728 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010729 // It *doesn't* see through dependent types, which is correct
10730 // according to [temp.arg.type]p3:
10731 // If a declaration acquires a function type through a
10732 // type dependent on a template-parameter and this causes
10733 // a declaration that does not use the syntactic form of a
10734 // function declarator to have a function type, the program
10735 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010736 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010737 Diag(Loc, diag::err_unexpected_friend);
10738
10739 // It might be worthwhile to try to recover by creating an
10740 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010741 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010742 }
10743
10744 // C++ [namespace.memdef]p3
10745 // - If a friend declaration in a non-local class first declares a
10746 // class or function, the friend class or function is a member
10747 // of the innermost enclosing namespace.
10748 // - The name of the friend is not found by simple name lookup
10749 // until a matching declaration is provided in that namespace
10750 // scope (either before or after the class declaration granting
10751 // friendship).
10752 // - If a friend function is called, its name may be found by the
10753 // name lookup that considers functions from namespaces and
10754 // classes associated with the types of the function arguments.
10755 // - When looking for a prior declaration of a class or a function
10756 // declared as a friend, scopes outside the innermost enclosing
10757 // namespace scope are not considered.
10758
John McCall337ec3d2010-10-12 23:13:28 +000010759 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010760 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10761 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010762 assert(Name);
10763
Douglas Gregor6ccab972010-12-16 01:14:37 +000010764 // Check for unexpanded parameter packs.
10765 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10766 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10767 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10768 return 0;
10769
John McCall67d1a672009-08-06 02:15:43 +000010770 // The context we found the declaration in, or in which we should
10771 // create the declaration.
10772 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010773 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010774 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010775 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010776
John McCall337ec3d2010-10-12 23:13:28 +000010777 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010778
John McCall337ec3d2010-10-12 23:13:28 +000010779 // There are four cases here.
10780 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010781 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010782 // there as appropriate.
10783 // Recover from invalid scope qualifiers as if they just weren't there.
10784 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010785 // C++0x [namespace.memdef]p3:
10786 // If the name in a friend declaration is neither qualified nor
10787 // a template-id and the declaration is a function or an
10788 // elaborated-type-specifier, the lookup to determine whether
10789 // the entity has been previously declared shall not consider
10790 // any scopes outside the innermost enclosing namespace.
10791 // C++0x [class.friend]p11:
10792 // If a friend declaration appears in a local class and the name
10793 // specified is an unqualified name, a prior declaration is
10794 // looked up without considering scopes that are outside the
10795 // innermost enclosing non-class scope. For a friend function
10796 // declaration, if there is no prior declaration, the program is
10797 // ill-formed.
10798 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010799 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010800
John McCall29ae6e52010-10-13 05:45:15 +000010801 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010802 DC = CurContext;
10803 while (true) {
10804 // Skip class contexts. If someone can cite chapter and verse
10805 // for this behavior, that would be nice --- it's what GCC and
10806 // EDG do, and it seems like a reasonable intent, but the spec
10807 // really only says that checks for unqualified existing
10808 // declarations should stop at the nearest enclosing namespace,
10809 // not that they should only consider the nearest enclosing
10810 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010811 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010812 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010813
John McCall68263142009-11-18 22:49:29 +000010814 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010815
10816 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010817 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010818 break;
John McCall29ae6e52010-10-13 05:45:15 +000010819
John McCall8a407372010-10-14 22:22:28 +000010820 if (isTemplateId) {
10821 if (isa<TranslationUnitDecl>(DC)) break;
10822 } else {
10823 if (DC->isFileContext()) break;
10824 }
John McCall67d1a672009-08-06 02:15:43 +000010825 DC = DC->getParent();
10826 }
10827
John McCall380aaa42010-10-13 06:22:15 +000010828 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010829
Douglas Gregor883af832011-10-10 01:11:59 +000010830 // C++ [class.friend]p6:
10831 // A function can be defined in a friend declaration of a class if and
10832 // only if the class is a non-local class (9.8), the function name is
10833 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010834 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010835 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10836 }
10837
John McCall337ec3d2010-10-12 23:13:28 +000010838 // - There's a non-dependent scope specifier, in which case we
10839 // compute it and do a previous lookup there for a function
10840 // or function template.
10841 } else if (!SS.getScopeRep()->isDependent()) {
10842 DC = computeDeclContext(SS);
10843 if (!DC) return 0;
10844
10845 if (RequireCompleteDeclContext(SS, DC)) return 0;
10846
10847 LookupQualifiedName(Previous, DC);
10848
10849 // Ignore things found implicitly in the wrong scope.
10850 // TODO: better diagnostics for this case. Suggesting the right
10851 // qualified scope would be nice...
10852 LookupResult::Filter F = Previous.makeFilter();
10853 while (F.hasNext()) {
10854 NamedDecl *D = F.next();
10855 if (!DC->InEnclosingNamespaceSetOf(
10856 D->getDeclContext()->getRedeclContext()))
10857 F.erase();
10858 }
10859 F.done();
10860
10861 if (Previous.empty()) {
10862 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010863 Diag(Loc, diag::err_qualified_friend_not_found)
10864 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010865 return 0;
10866 }
10867
10868 // C++ [class.friend]p1: A friend of a class is a function or
10869 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010870 if (DC->Equals(CurContext))
10871 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010872 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010873 diag::warn_cxx98_compat_friend_is_member :
10874 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010875
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010876 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010877 // C++ [class.friend]p6:
10878 // A function can be defined in a friend declaration of a class if and
10879 // only if the class is a non-local class (9.8), the function name is
10880 // unqualified, and the function has namespace scope.
10881 SemaDiagnosticBuilder DB
10882 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10883
10884 DB << SS.getScopeRep();
10885 if (DC->isFileContext())
10886 DB << FixItHint::CreateRemoval(SS.getRange());
10887 SS.clear();
10888 }
John McCall337ec3d2010-10-12 23:13:28 +000010889
10890 // - There's a scope specifier that does not match any template
10891 // parameter lists, in which case we use some arbitrary context,
10892 // create a method or method template, and wait for instantiation.
10893 // - There's a scope specifier that does match some template
10894 // parameter lists, which we don't handle right now.
10895 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010896 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010897 // C++ [class.friend]p6:
10898 // A function can be defined in a friend declaration of a class if and
10899 // only if the class is a non-local class (9.8), the function name is
10900 // unqualified, and the function has namespace scope.
10901 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10902 << SS.getScopeRep();
10903 }
10904
John McCall337ec3d2010-10-12 23:13:28 +000010905 DC = CurContext;
10906 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010907 }
Douglas Gregor883af832011-10-10 01:11:59 +000010908
John McCall29ae6e52010-10-13 05:45:15 +000010909 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010910 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010911 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10912 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10913 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010914 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010915 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10916 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010917 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010918 }
John McCall67d1a672009-08-06 02:15:43 +000010919 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010920
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010921 // FIXME: This is an egregious hack to cope with cases where the scope stack
10922 // does not contain the declaration context, i.e., in an out-of-line
10923 // definition of a class.
10924 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10925 if (!DCScope) {
10926 FakeDCScope.setEntity(DC);
10927 DCScope = &FakeDCScope;
10928 }
10929
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010930 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010931 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010932 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010933 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010934
Douglas Gregor182ddf02009-09-28 00:08:27 +000010935 assert(ND->getDeclContext() == DC);
10936 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010937
John McCallab88d972009-08-31 22:39:49 +000010938 // Add the function declaration to the appropriate lookup tables,
10939 // adjusting the redeclarations list as necessary. We don't
10940 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010941 //
John McCallab88d972009-08-31 22:39:49 +000010942 // Also update the scope-based lookup if the target context's
10943 // lookup context is in lexical scope.
10944 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010945 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010946 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010947 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010948 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010949 }
John McCall02cace72009-08-28 07:59:38 +000010950
10951 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010952 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010953 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010954 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010955 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010956
John McCall1f2e1a92012-08-10 03:15:35 +000010957 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010958 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010959 } else {
10960 if (DC->isRecord()) CheckFriendAccess(ND);
10961
John McCall6102ca12010-10-16 06:59:13 +000010962 FunctionDecl *FD;
10963 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10964 FD = FTD->getTemplatedDecl();
10965 else
10966 FD = cast<FunctionDecl>(ND);
10967
10968 // Mark templated-scope function declarations as unsupported.
10969 if (FD->getNumTemplateParameterLists())
10970 FrD->setUnsupportedFriend(true);
10971 }
John McCall337ec3d2010-10-12 23:13:28 +000010972
John McCalld226f652010-08-21 09:40:31 +000010973 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010974}
10975
John McCalld226f652010-08-21 09:40:31 +000010976void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10977 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010978
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000010979 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000010980 if (!Fn) {
10981 Diag(DelLoc, diag::err_deleted_non_function);
10982 return;
10983 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010984 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010985 // Don't consider the implicit declaration we generate for explicit
10986 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010987 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10988 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010989 Diag(DelLoc, diag::err_deleted_decl_not_first);
10990 Diag(Prev->getLocation(), diag::note_previous_declaration);
10991 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010992 // If the declaration wasn't the first, we delete the function anyway for
10993 // recovery.
10994 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010995 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010996}
Sebastian Redl13e88542009-04-27 21:33:24 +000010997
Sean Hunte4246a62011-05-12 06:15:49 +000010998void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000010999 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011000
11001 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011002 if (MD->getParent()->isDependentType()) {
11003 MD->setDefaulted();
11004 MD->setExplicitlyDefaulted();
11005 return;
11006 }
11007
Sean Hunte4246a62011-05-12 06:15:49 +000011008 CXXSpecialMember Member = getSpecialMember(MD);
11009 if (Member == CXXInvalid) {
11010 Diag(DefaultLoc, diag::err_default_special_members);
11011 return;
11012 }
11013
11014 MD->setDefaulted();
11015 MD->setExplicitlyDefaulted();
11016
Sean Huntcd10dec2011-05-23 23:14:04 +000011017 // If this definition appears within the record, do the checking when
11018 // the record is complete.
11019 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011020 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011021 // Find the uninstantiated declaration that actually had the '= default'
11022 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011023 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011024
11025 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011026 return;
11027
Richard Smithb9d0b762012-07-27 04:22:15 +000011028 CheckExplicitlyDefaultedSpecialMember(MD);
11029
Richard Smith1d28caf2012-12-11 01:14:52 +000011030 // The exception specification is needed because we are defining the
11031 // function.
11032 ResolveExceptionSpec(DefaultLoc,
11033 MD->getType()->castAs<FunctionProtoType>());
11034
Sean Hunte4246a62011-05-12 06:15:49 +000011035 switch (Member) {
11036 case CXXDefaultConstructor: {
11037 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011038 if (!CD->isInvalidDecl())
11039 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11040 break;
11041 }
11042
11043 case CXXCopyConstructor: {
11044 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011045 if (!CD->isInvalidDecl())
11046 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011047 break;
11048 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011049
Sean Hunt2b188082011-05-14 05:23:28 +000011050 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011051 if (!MD->isInvalidDecl())
11052 DefineImplicitCopyAssignment(DefaultLoc, MD);
11053 break;
11054 }
11055
Sean Huntcb45a0f2011-05-12 22:46:25 +000011056 case CXXDestructor: {
11057 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011058 if (!DD->isInvalidDecl())
11059 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011060 break;
11061 }
11062
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011063 case CXXMoveConstructor: {
11064 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011065 if (!CD->isInvalidDecl())
11066 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011067 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011068 }
Sean Hunt82713172011-05-25 23:16:36 +000011069
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011070 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011071 if (!MD->isInvalidDecl())
11072 DefineImplicitMoveAssignment(DefaultLoc, MD);
11073 break;
11074 }
11075
11076 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011077 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011078 }
11079 } else {
11080 Diag(DefaultLoc, diag::err_default_special_members);
11081 }
11082}
11083
Sebastian Redl13e88542009-04-27 21:33:24 +000011084static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011085 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011086 Stmt *SubStmt = *CI;
11087 if (!SubStmt)
11088 continue;
11089 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011090 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011091 diag::err_return_in_constructor_handler);
11092 if (!isa<Expr>(SubStmt))
11093 SearchForReturnInStmt(Self, SubStmt);
11094 }
11095}
11096
11097void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11098 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11099 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11100 SearchForReturnInStmt(*this, Handler);
11101 }
11102}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011103
David Blaikie299adab2013-01-18 23:03:15 +000011104bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011105 const CXXMethodDecl *Old) {
11106 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11107 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11108
11109 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11110
11111 // If the calling conventions match, everything is fine
11112 if (NewCC == OldCC)
11113 return false;
11114
11115 // If either of the calling conventions are set to "default", we need to pick
11116 // something more sensible based on the target. This supports code where the
11117 // one method explicitly sets thiscall, and another has no explicit calling
11118 // convention.
11119 CallingConv Default =
11120 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11121 if (NewCC == CC_Default)
11122 NewCC = Default;
11123 if (OldCC == CC_Default)
11124 OldCC = Default;
11125
11126 // If the calling conventions still don't match, then report the error
11127 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011128 Diag(New->getLocation(),
11129 diag::err_conflicting_overriding_cc_attributes)
11130 << New->getDeclName() << New->getType() << Old->getType();
11131 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11132 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011133 }
11134
11135 return false;
11136}
11137
Mike Stump1eb44332009-09-09 15:08:12 +000011138bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011139 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011140 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11141 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011142
Chandler Carruth73857792010-02-15 11:53:20 +000011143 if (Context.hasSameType(NewTy, OldTy) ||
11144 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011145 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011146
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011147 // Check if the return types are covariant
11148 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011149
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011150 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011151 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11152 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011153 NewClassTy = NewPT->getPointeeType();
11154 OldClassTy = OldPT->getPointeeType();
11155 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011156 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11157 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11158 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11159 NewClassTy = NewRT->getPointeeType();
11160 OldClassTy = OldRT->getPointeeType();
11161 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011162 }
11163 }
Mike Stump1eb44332009-09-09 15:08:12 +000011164
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011165 // The return types aren't either both pointers or references to a class type.
11166 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011167 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011168 diag::err_different_return_type_for_overriding_virtual_function)
11169 << New->getDeclName() << NewTy << OldTy;
11170 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011171
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011172 return true;
11173 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011174
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011175 // C++ [class.virtual]p6:
11176 // If the return type of D::f differs from the return type of B::f, the
11177 // class type in the return type of D::f shall be complete at the point of
11178 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011179 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11180 if (!RT->isBeingDefined() &&
11181 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011182 diag::err_covariant_return_incomplete,
11183 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011184 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011185 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011186
Douglas Gregora4923eb2009-11-16 21:35:15 +000011187 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011188 // Check if the new class derives from the old class.
11189 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11190 Diag(New->getLocation(),
11191 diag::err_covariant_return_not_derived)
11192 << New->getDeclName() << NewTy << OldTy;
11193 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11194 return true;
11195 }
Mike Stump1eb44332009-09-09 15:08:12 +000011196
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011197 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011198 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011199 diag::err_covariant_return_inaccessible_base,
11200 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11201 // FIXME: Should this point to the return type?
11202 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011203 // FIXME: this note won't trigger for delayed access control
11204 // diagnostics, and it's impossible to get an undelayed error
11205 // here from access control during the original parse because
11206 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011207 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11208 return true;
11209 }
11210 }
Mike Stump1eb44332009-09-09 15:08:12 +000011211
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011212 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011213 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011214 Diag(New->getLocation(),
11215 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011216 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011217 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11218 return true;
11219 };
Mike Stump1eb44332009-09-09 15:08:12 +000011220
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011221
11222 // The new class type must have the same or less qualifiers as the old type.
11223 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11224 Diag(New->getLocation(),
11225 diag::err_covariant_return_type_class_type_more_qualified)
11226 << New->getDeclName() << NewTy << OldTy;
11227 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11228 return true;
11229 };
Mike Stump1eb44332009-09-09 15:08:12 +000011230
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011231 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011232}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011233
Douglas Gregor4ba31362009-12-01 17:24:26 +000011234/// \brief Mark the given method pure.
11235///
11236/// \param Method the method to be marked pure.
11237///
11238/// \param InitRange the source range that covers the "0" initializer.
11239bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011240 SourceLocation EndLoc = InitRange.getEnd();
11241 if (EndLoc.isValid())
11242 Method->setRangeEnd(EndLoc);
11243
Douglas Gregor4ba31362009-12-01 17:24:26 +000011244 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11245 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011246 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011247 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011248
11249 if (!Method->isInvalidDecl())
11250 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11251 << Method->getDeclName() << InitRange;
11252 return true;
11253}
11254
Douglas Gregor552e2992012-02-21 02:22:07 +000011255/// \brief Determine whether the given declaration is a static data member.
11256static bool isStaticDataMember(Decl *D) {
11257 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11258 if (!Var)
11259 return false;
11260
11261 return Var->isStaticDataMember();
11262}
John McCall731ad842009-12-19 09:28:58 +000011263/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11264/// an initializer for the out-of-line declaration 'Dcl'. The scope
11265/// is a fresh scope pushed for just this purpose.
11266///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011267/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11268/// static data member of class X, names should be looked up in the scope of
11269/// class X.
John McCalld226f652010-08-21 09:40:31 +000011270void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011271 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011272 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011273
John McCall731ad842009-12-19 09:28:58 +000011274 // We should only get called for declarations with scope specifiers, like:
11275 // int foo::bar;
11276 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011277 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011278
11279 // If we are parsing the initializer for a static data member, push a
11280 // new expression evaluation context that is associated with this static
11281 // data member.
11282 if (isStaticDataMember(D))
11283 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011284}
11285
11286/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011287/// initializer for the out-of-line declaration 'D'.
11288void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011289 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011290 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011291
Douglas Gregor552e2992012-02-21 02:22:07 +000011292 if (isStaticDataMember(D))
11293 PopExpressionEvaluationContext();
11294
John McCall731ad842009-12-19 09:28:58 +000011295 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011296 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011297}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011298
11299/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11300/// C++ if/switch/while/for statement.
11301/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011302DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011303 // C++ 6.4p2:
11304 // The declarator shall not specify a function or an array.
11305 // The type-specifier-seq shall not contain typedef and shall not declare a
11306 // new class or enumeration.
11307 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11308 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011309
11310 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011311 if (!Dcl)
11312 return true;
11313
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011314 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11315 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011316 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011317 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011318 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011319
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011320 return Dcl;
11321}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011322
Douglas Gregordfe65432011-07-28 19:11:31 +000011323void Sema::LoadExternalVTableUses() {
11324 if (!ExternalSource)
11325 return;
11326
11327 SmallVector<ExternalVTableUse, 4> VTables;
11328 ExternalSource->ReadUsedVTables(VTables);
11329 SmallVector<VTableUse, 4> NewUses;
11330 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11331 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11332 = VTablesUsed.find(VTables[I].Record);
11333 // Even if a definition wasn't required before, it may be required now.
11334 if (Pos != VTablesUsed.end()) {
11335 if (!Pos->second && VTables[I].DefinitionRequired)
11336 Pos->second = true;
11337 continue;
11338 }
11339
11340 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11341 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11342 }
11343
11344 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11345}
11346
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011347void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11348 bool DefinitionRequired) {
11349 // Ignore any vtable uses in unevaluated operands or for classes that do
11350 // not have a vtable.
11351 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11352 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011353 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011354 return;
11355
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011356 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011357 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011358 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11359 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11360 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11361 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011362 // If we already had an entry, check to see if we are promoting this vtable
11363 // to required a definition. If so, we need to reappend to the VTableUses
11364 // list, since we may have already processed the first entry.
11365 if (DefinitionRequired && !Pos.first->second) {
11366 Pos.first->second = true;
11367 } else {
11368 // Otherwise, we can early exit.
11369 return;
11370 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011371 }
11372
11373 // Local classes need to have their virtual members marked
11374 // immediately. For all other classes, we mark their virtual members
11375 // at the end of the translation unit.
11376 if (Class->isLocalClass())
11377 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011378 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011379 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011380}
11381
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011382bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011383 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011384 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011385 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011386
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011387 // Note: The VTableUses vector could grow as a result of marking
11388 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011389 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011390 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011391 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011392 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011393 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011394 if (!Class)
11395 continue;
11396
11397 SourceLocation Loc = VTableUses[I].second;
11398
Richard Smithb9d0b762012-07-27 04:22:15 +000011399 bool DefineVTable = true;
11400
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011401 // If this class has a key function, but that key function is
11402 // defined in another translation unit, we don't need to emit the
11403 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011404 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011405 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011406 switch (KeyFunction->getTemplateSpecializationKind()) {
11407 case TSK_Undeclared:
11408 case TSK_ExplicitSpecialization:
11409 case TSK_ExplicitInstantiationDeclaration:
11410 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011411 DefineVTable = false;
11412 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011413
11414 case TSK_ExplicitInstantiationDefinition:
11415 case TSK_ImplicitInstantiation:
11416 // We will be instantiating the key function.
11417 break;
11418 }
11419 } else if (!KeyFunction) {
11420 // If we have a class with no key function that is the subject
11421 // of an explicit instantiation declaration, suppress the
11422 // vtable; it will live with the explicit instantiation
11423 // definition.
11424 bool IsExplicitInstantiationDeclaration
11425 = Class->getTemplateSpecializationKind()
11426 == TSK_ExplicitInstantiationDeclaration;
11427 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11428 REnd = Class->redecls_end();
11429 R != REnd; ++R) {
11430 TemplateSpecializationKind TSK
11431 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11432 if (TSK == TSK_ExplicitInstantiationDeclaration)
11433 IsExplicitInstantiationDeclaration = true;
11434 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11435 IsExplicitInstantiationDeclaration = false;
11436 break;
11437 }
11438 }
11439
11440 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011441 DefineVTable = false;
11442 }
11443
11444 // The exception specifications for all virtual members may be needed even
11445 // if we are not providing an authoritative form of the vtable in this TU.
11446 // We may choose to emit it available_externally anyway.
11447 if (!DefineVTable) {
11448 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11449 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011450 }
11451
11452 // Mark all of the virtual members of this class as referenced, so
11453 // that we can build a vtable. Then, tell the AST consumer that a
11454 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011455 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011456 MarkVirtualMembersReferenced(Loc, Class);
11457 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11458 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11459
11460 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola531db822013-03-07 02:00:27 +000011461 if (Class->hasExternalLinkage() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011462 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011463 const FunctionDecl *KeyFunctionDef = 0;
11464 if (!KeyFunction ||
11465 (KeyFunction->hasBody(KeyFunctionDef) &&
11466 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011467 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11468 TSK_ExplicitInstantiationDefinition
11469 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11470 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011471 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011472 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011473 VTableUses.clear();
11474
Douglas Gregor78844032011-04-22 22:25:37 +000011475 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011476}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011477
Richard Smithb9d0b762012-07-27 04:22:15 +000011478void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11479 const CXXRecordDecl *RD) {
11480 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11481 E = RD->method_end(); I != E; ++I)
11482 if ((*I)->isVirtual() && !(*I)->isPure())
11483 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11484}
11485
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011486void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11487 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011488 // Mark all functions which will appear in RD's vtable as used.
11489 CXXFinalOverriderMap FinalOverriders;
11490 RD->getFinalOverriders(FinalOverriders);
11491 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11492 E = FinalOverriders.end();
11493 I != E; ++I) {
11494 for (OverridingMethods::const_iterator OI = I->second.begin(),
11495 OE = I->second.end();
11496 OI != OE; ++OI) {
11497 assert(OI->second.size() > 0 && "no final overrider");
11498 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011499
Richard Smithff817f72012-07-07 06:59:51 +000011500 // C++ [basic.def.odr]p2:
11501 // [...] A virtual member function is used if it is not pure. [...]
11502 if (!Overrider->isPure())
11503 MarkFunctionReferenced(Loc, Overrider);
11504 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011505 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011506
11507 // Only classes that have virtual bases need a VTT.
11508 if (RD->getNumVBases() == 0)
11509 return;
11510
11511 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11512 e = RD->bases_end(); i != e; ++i) {
11513 const CXXRecordDecl *Base =
11514 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011515 if (Base->getNumVBases() == 0)
11516 continue;
11517 MarkVirtualMembersReferenced(Loc, Base);
11518 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011519}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011520
11521/// SetIvarInitializers - This routine builds initialization ASTs for the
11522/// Objective-C implementation whose ivars need be initialized.
11523void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011524 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011525 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011526 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011527 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011528 CollectIvarsToConstructOrDestruct(OID, ivars);
11529 if (ivars.empty())
11530 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011531 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011532 for (unsigned i = 0; i < ivars.size(); i++) {
11533 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011534 if (Field->isInvalidDecl())
11535 continue;
11536
Sean Huntcbb67482011-01-08 20:30:50 +000011537 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011538 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11539 InitializationKind InitKind =
11540 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11541
11542 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011543 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011544 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011545 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011546 // Note, MemberInit could actually come back empty if no initialization
11547 // is required (e.g., because it would call a trivial default constructor)
11548 if (!MemberInit.get() || MemberInit.isInvalid())
11549 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011550
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011551 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011552 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11553 SourceLocation(),
11554 MemberInit.takeAs<Expr>(),
11555 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011556 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011557
11558 // Be sure that the destructor is accessible and is marked as referenced.
11559 if (const RecordType *RecordTy
11560 = Context.getBaseElementType(Field->getType())
11561 ->getAs<RecordType>()) {
11562 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011563 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011564 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011565 CheckDestructorAccess(Field->getLocation(), Destructor,
11566 PDiag(diag::err_access_dtor_ivar)
11567 << Context.getBaseElementType(Field->getType()));
11568 }
11569 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011570 }
11571 ObjCImplementation->setIvarInitializers(Context,
11572 AllToInit.data(), AllToInit.size());
11573 }
11574}
Sean Huntfe57eef2011-05-04 05:57:24 +000011575
Sean Huntebcbe1d2011-05-04 23:29:54 +000011576static
11577void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11578 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11579 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11580 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11581 Sema &S) {
11582 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11583 CE = Current.end();
11584 if (Ctor->isInvalidDecl())
11585 return;
11586
Richard Smitha8eaf002012-08-23 06:16:52 +000011587 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11588
11589 // Target may not be determinable yet, for instance if this is a dependent
11590 // call in an uninstantiated template.
11591 if (Target) {
11592 const FunctionDecl *FNTarget = 0;
11593 (void)Target->hasBody(FNTarget);
11594 Target = const_cast<CXXConstructorDecl*>(
11595 cast_or_null<CXXConstructorDecl>(FNTarget));
11596 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011597
11598 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11599 // Avoid dereferencing a null pointer here.
11600 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11601
11602 if (!Current.insert(Canonical))
11603 return;
11604
11605 // We know that beyond here, we aren't chaining into a cycle.
11606 if (!Target || !Target->isDelegatingConstructor() ||
11607 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11608 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11609 Valid.insert(*CI);
11610 Current.clear();
11611 // We've hit a cycle.
11612 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11613 Current.count(TCanonical)) {
11614 // If we haven't diagnosed this cycle yet, do so now.
11615 if (!Invalid.count(TCanonical)) {
11616 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011617 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011618 << Ctor;
11619
Richard Smitha8eaf002012-08-23 06:16:52 +000011620 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011621 if (TCanonical != Canonical)
11622 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11623
11624 CXXConstructorDecl *C = Target;
11625 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011626 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011627 (void)C->getTargetConstructor()->hasBody(FNTarget);
11628 assert(FNTarget && "Ctor cycle through bodiless function");
11629
Richard Smitha8eaf002012-08-23 06:16:52 +000011630 C = const_cast<CXXConstructorDecl*>(
11631 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011632 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11633 }
11634 }
11635
11636 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11637 Invalid.insert(*CI);
11638 Current.clear();
11639 } else {
11640 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11641 }
11642}
11643
11644
Sean Huntfe57eef2011-05-04 05:57:24 +000011645void Sema::CheckDelegatingCtorCycles() {
11646 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11647
Sean Huntebcbe1d2011-05-04 23:29:54 +000011648 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11649 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011650
Douglas Gregor0129b562011-07-27 21:57:17 +000011651 for (DelegatingCtorDeclsType::iterator
11652 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011653 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011654 I != E; ++I)
11655 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011656
11657 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11658 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011659}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011660
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011661namespace {
11662 /// \brief AST visitor that finds references to the 'this' expression.
11663 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11664 Sema &S;
11665
11666 public:
11667 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11668
11669 bool VisitCXXThisExpr(CXXThisExpr *E) {
11670 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11671 << E->isImplicit();
11672 return false;
11673 }
11674 };
11675}
11676
11677bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11678 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11679 if (!TSInfo)
11680 return false;
11681
11682 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011683 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011684 if (!ProtoTL)
11685 return false;
11686
11687 // C++11 [expr.prim.general]p3:
11688 // [The expression this] shall not appear before the optional
11689 // cv-qualifier-seq and it shall not appear within the declaration of a
11690 // static member function (although its type and value category are defined
11691 // within a static member function as they are within a non-static member
11692 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011693 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000011694 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011695 FindCXXThisExpr Finder(*this);
11696
11697 // If the return type came after the cv-qualifier-seq, check it now.
11698 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000011699 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011700 return true;
11701
11702 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011703 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11704 return true;
11705
11706 return checkThisInStaticMemberFunctionAttributes(Method);
11707}
11708
11709bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11710 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11711 if (!TSInfo)
11712 return false;
11713
11714 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011715 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011716 if (!ProtoTL)
11717 return false;
11718
David Blaikie39e6ab42013-02-18 22:06:02 +000011719 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011720 FindCXXThisExpr Finder(*this);
11721
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011722 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011723 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011724 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011725 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011726 case EST_DynamicNone:
11727 case EST_MSAny:
11728 case EST_None:
11729 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011730
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011731 case EST_ComputedNoexcept:
11732 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11733 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011734
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011735 case EST_Dynamic:
11736 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011737 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011738 E != EEnd; ++E) {
11739 if (!Finder.TraverseType(*E))
11740 return true;
11741 }
11742 break;
11743 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011744
11745 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011746}
11747
11748bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11749 FindCXXThisExpr Finder(*this);
11750
11751 // Check attributes.
11752 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11753 A != AEnd; ++A) {
11754 // FIXME: This should be emitted by tblgen.
11755 Expr *Arg = 0;
11756 ArrayRef<Expr *> Args;
11757 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11758 Arg = G->getArg();
11759 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11760 Arg = G->getArg();
11761 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11762 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11763 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11764 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11765 else if (ExclusiveLockFunctionAttr *ELF
11766 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11767 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11768 else if (SharedLockFunctionAttr *SLF
11769 = dyn_cast<SharedLockFunctionAttr>(*A))
11770 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11771 else if (ExclusiveTrylockFunctionAttr *ETLF
11772 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11773 Arg = ETLF->getSuccessValue();
11774 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11775 } else if (SharedTrylockFunctionAttr *STLF
11776 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11777 Arg = STLF->getSuccessValue();
11778 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11779 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11780 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11781 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11782 Arg = LR->getArg();
11783 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11784 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11785 else if (ExclusiveLocksRequiredAttr *ELR
11786 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11787 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11788 else if (SharedLocksRequiredAttr *SLR
11789 = dyn_cast<SharedLocksRequiredAttr>(*A))
11790 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11791
11792 if (Arg && !Finder.TraverseStmt(Arg))
11793 return true;
11794
11795 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11796 if (!Finder.TraverseStmt(Args[I]))
11797 return true;
11798 }
11799 }
11800
11801 return false;
11802}
11803
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011804void
11805Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11806 ArrayRef<ParsedType> DynamicExceptions,
11807 ArrayRef<SourceRange> DynamicExceptionRanges,
11808 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011809 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011810 FunctionProtoType::ExtProtoInfo &EPI) {
11811 Exceptions.clear();
11812 EPI.ExceptionSpecType = EST;
11813 if (EST == EST_Dynamic) {
11814 Exceptions.reserve(DynamicExceptions.size());
11815 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11816 // FIXME: Preserve type source info.
11817 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11818
11819 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11820 collectUnexpandedParameterPacks(ET, Unexpanded);
11821 if (!Unexpanded.empty()) {
11822 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11823 UPPC_ExceptionType,
11824 Unexpanded);
11825 continue;
11826 }
11827
11828 // Check that the type is valid for an exception spec, and
11829 // drop it if not.
11830 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11831 Exceptions.push_back(ET);
11832 }
11833 EPI.NumExceptions = Exceptions.size();
11834 EPI.Exceptions = Exceptions.data();
11835 return;
11836 }
11837
11838 if (EST == EST_ComputedNoexcept) {
11839 // If an error occurred, there's no expression here.
11840 if (NoexceptExpr) {
11841 assert((NoexceptExpr->isTypeDependent() ||
11842 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11843 Context.BoolTy) &&
11844 "Parser should have made sure that the expression is boolean");
11845 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11846 EPI.ExceptionSpecType = EST_BasicNoexcept;
11847 return;
11848 }
11849
11850 if (!NoexceptExpr->isValueDependent())
11851 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011852 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011853 /*AllowFold*/ false).take();
11854 EPI.NoexceptExpr = NoexceptExpr;
11855 }
11856 return;
11857 }
11858}
11859
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011860/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11861Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11862 // Implicitly declared functions (e.g. copy constructors) are
11863 // __host__ __device__
11864 if (D->isImplicit())
11865 return CFT_HostDevice;
11866
11867 if (D->hasAttr<CUDAGlobalAttr>())
11868 return CFT_Global;
11869
11870 if (D->hasAttr<CUDADeviceAttr>()) {
11871 if (D->hasAttr<CUDAHostAttr>())
11872 return CFT_HostDevice;
11873 else
11874 return CFT_Device;
11875 }
11876
11877 return CFT_Host;
11878}
11879
11880bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11881 CUDAFunctionTarget CalleeTarget) {
11882 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11883 // Callable from the device only."
11884 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11885 return true;
11886
11887 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11888 // Callable from the host only."
11889 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11890 // Callable from the host only."
11891 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11892 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11893 return true;
11894
11895 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11896 return true;
11897
11898 return false;
11899}