blob: 828083527a7fb430e782f09cd14ec7138cc39e79 [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"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Eli Friedman7badd242012-02-09 20:13:14 +000019#include "clang/Sema/ScopeInfo.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000020#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000021#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000025#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000027#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000028#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000029#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000030#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000031#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000032#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000033#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000035#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000036#include "clang/Lex/Preprocessor.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000037#include "llvm/ADT/SmallString.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000039#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000040#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000041
42using namespace clang;
43
Chris Lattner8123a952008-04-10 02:22:51 +000044//===----------------------------------------------------------------------===//
45// CheckDefaultArgumentVisitor
46//===----------------------------------------------------------------------===//
47
Chris Lattner9e979552008-04-12 23:52:44 +000048namespace {
49 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
50 /// the default argument of a parameter to determine whether it
51 /// contains any ill-formed subexpressions. For example, this will
52 /// diagnose the use of local variables or parameters within the
53 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000054 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000055 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000056 Expr *DefaultArg;
57 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-04-12 23:52:44 +000059 public:
Mike Stump1eb44332009-09-09 15:08:12 +000060 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000061 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000062
Chris Lattner9e979552008-04-12 23:52:44 +000063 bool VisitExpr(Expr *Node);
64 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000065 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000066 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattner9e979552008-04-12 23:52:44 +000067 };
Chris Lattner8123a952008-04-10 02:22:51 +000068
Chris Lattner9e979552008-04-12 23:52:44 +000069 /// VisitExpr - Visit all of the children of this expression.
70 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
71 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000072 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000073 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000074 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000075 }
76
Chris Lattner9e979552008-04-12 23:52:44 +000077 /// VisitDeclRefExpr - Visit a reference to a declaration, to
78 /// determine whether this declaration can be used in the default
79 /// argument expression.
80 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000081 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000082 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
83 // C++ [dcl.fct.default]p9
84 // Default arguments are evaluated each time the function is
85 // called. The order of evaluation of function arguments is
86 // unspecified. Consequently, parameters of a function shall not
87 // be used in default argument expressions, even if they are not
88 // evaluated. Parameters of a function declared before a default
89 // argument expression are in scope and can hide namespace and
90 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000091 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000092 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000093 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000094 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000095 // C++ [dcl.fct.default]p7
96 // Local variables shall not be used in default argument
97 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000098 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +000099 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000100 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000101 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000102 }
Chris Lattner8123a952008-04-10 02:22:51 +0000103
Douglas Gregor3996f232008-11-04 13:41:56 +0000104 return false;
105 }
Chris Lattner9e979552008-04-12 23:52:44 +0000106
Douglas Gregor796da182008-11-04 14:32:21 +0000107 /// VisitCXXThisExpr - Visit a C++ "this" expression.
108 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
109 // C++ [dcl.fct.default]p8:
110 // The keyword this shall not be used in a default argument of a
111 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000112 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000113 diag::err_param_default_argument_references_this)
114 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000115 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000116
117 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
118 // C++11 [expr.lambda.prim]p13:
119 // A lambda-expression appearing in a default argument shall not
120 // implicitly or explicitly capture any entity.
121 if (Lambda->capture_begin() == Lambda->capture_end())
122 return false;
123
124 return S->Diag(Lambda->getLocStart(),
125 diag::err_lambda_capture_default_arg);
126 }
Chris Lattner8123a952008-04-10 02:22:51 +0000127}
128
Richard Smithe6975e92012-04-17 00:58:00 +0000129void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
130 CXXMethodDecl *Method) {
Richard Smith7a614d82011-06-11 17:19:42 +0000131 // If we have an MSAny or unknown spec already, don't bother.
132 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Sean Hunt001cad92011-05-10 00:49:42 +0000133 return;
134
135 const FunctionProtoType *Proto
136 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000137 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
138 if (!Proto)
139 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000140
141 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
142
143 // If this function can throw any exceptions, make a note of that.
Richard Smith7a614d82011-06-11 17:19:42 +0000144 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000145 ClearExceptions();
146 ComputedEST = EST;
147 return;
148 }
149
Richard Smith7a614d82011-06-11 17:19:42 +0000150 // FIXME: If the call to this decl is using any of its default arguments, we
151 // need to search them for potentially-throwing calls.
152
Sean Hunt001cad92011-05-10 00:49:42 +0000153 // If this function has a basic noexcept, it doesn't affect the outcome.
154 if (EST == EST_BasicNoexcept)
155 return;
156
157 // If we have a throw-all spec at this point, ignore the function.
158 if (ComputedEST == EST_None)
159 return;
160
161 // If we're still at noexcept(true) and there's a nothrow() callee,
162 // change to that specification.
163 if (EST == EST_DynamicNone) {
164 if (ComputedEST == EST_BasicNoexcept)
165 ComputedEST = EST_DynamicNone;
166 return;
167 }
168
169 // Check out noexcept specs.
170 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000171 FunctionProtoType::NoexceptResult NR =
172 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000173 assert(NR != FunctionProtoType::NR_NoNoexcept &&
174 "Must have noexcept result for EST_ComputedNoexcept.");
175 assert(NR != FunctionProtoType::NR_Dependent &&
176 "Should not generate implicit declarations for dependent cases, "
177 "and don't know how to handle them anyway.");
178
179 // noexcept(false) -> no spec on the new function
180 if (NR == FunctionProtoType::NR_Throw) {
181 ClearExceptions();
182 ComputedEST = EST_None;
183 }
184 // noexcept(true) won't change anything either.
185 return;
186 }
187
188 assert(EST == EST_Dynamic && "EST case not considered earlier.");
189 assert(ComputedEST != EST_None &&
190 "Shouldn't collect exceptions when throw-all is guaranteed.");
191 ComputedEST = EST_Dynamic;
192 // Record the exceptions in this function's exception specification.
193 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
194 EEnd = Proto->exception_end();
195 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000196 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000197 Exceptions.push_back(*E);
198}
199
Richard Smith7a614d82011-06-11 17:19:42 +0000200void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
201 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
202 return;
203
204 // FIXME:
205 //
206 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000207 // [An] implicit exception-specification specifies the type-id T if and
208 // only if T is allowed by the exception-specification of a function directly
209 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000210 // function it directly invokes allows all exceptions, and f shall allow no
211 // exceptions if every function it directly invokes allows no exceptions.
212 //
213 // Note in particular that if an implicit exception-specification is generated
214 // for a function containing a throw-expression, that specification can still
215 // be noexcept(true).
216 //
217 // Note also that 'directly invoked' is not defined in the standard, and there
218 // is no indication that we should only consider potentially-evaluated calls.
219 //
220 // Ultimately we should implement the intent of the standard: the exception
221 // specification should be the set of exceptions which can be thrown by the
222 // implicit definition. For now, we assume that any non-nothrow expression can
223 // throw any exception.
224
Richard Smithe6975e92012-04-17 00:58:00 +0000225 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000226 ComputedEST = EST_None;
227}
228
Anders Carlssoned961f92009-08-25 02:29:20 +0000229bool
John McCall9ae2f072010-08-23 23:25:46 +0000230Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000231 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000232 if (RequireCompleteType(Param->getLocation(), Param->getType(),
233 diag::err_typecheck_decl_incomplete_type)) {
234 Param->setInvalidDecl();
235 return true;
236 }
237
Anders Carlssoned961f92009-08-25 02:29:20 +0000238 // C++ [dcl.fct.default]p5
239 // A default argument expression is implicitly converted (clause
240 // 4) to the parameter type. The default argument expression has
241 // the same semantic constraints as the initializer expression in
242 // a declaration of a variable of the parameter type, using the
243 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000244 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
245 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000246 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
247 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000248 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000249 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000250 MultiExprArg(*this, &Arg, 1));
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
John McCallb4eb64d2010-10-08 02:01:28 +0000255 CheckImplicitConversions(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.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000355 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000356 DeclaratorChunk &chunk = D.getTypeObject(i);
357 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000358 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
359 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000360 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000361 if (Param->hasUnparsedDefaultArg()) {
362 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000363 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
364 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
365 delete Toks;
366 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000367 } else if (Param->getDefaultArg()) {
368 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
369 << Param->getDefaultArg()->getSourceRange();
370 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000371 }
372 }
373 }
374 }
375}
376
Chris Lattner3d1cee32008-04-08 05:04:30 +0000377// MergeCXXFunctionDecl - Merge two declarations of the same C++
378// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000379// type. Subroutine of MergeFunctionDecl. Returns true if there was an
380// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000381bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
382 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000383 bool Invalid = false;
384
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000386 // For non-template functions, default arguments can be added in
387 // later declarations of a function in the same
388 // scope. Declarations in different scopes have completely
389 // distinct sets of default arguments. That is, declarations in
390 // inner scopes do not acquire default arguments from
391 // declarations in outer scopes, and vice versa. In a given
392 // function declaration, all parameters subsequent to a
393 // parameter with a default argument shall have default
394 // arguments supplied in this or previous declarations. A
395 // default argument shall not be redefined by a later
396 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000397 //
398 // C++ [dcl.fct.default]p6:
399 // Except for member functions of class templates, the default arguments
400 // in a member function definition that appears outside of the class
401 // definition are added to the set of default arguments provided by the
402 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000403 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
404 ParmVarDecl *OldParam = Old->getParamDecl(p);
405 ParmVarDecl *NewParam = New->getParamDecl(p);
406
James Molloy9cda03f2012-03-13 08:55:35 +0000407 bool OldParamHasDfl = OldParam->hasDefaultArg();
408 bool NewParamHasDfl = NewParam->hasDefaultArg();
409
410 NamedDecl *ND = Old;
411 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
412 // Ignore default parameters of old decl if they are not in
413 // the same scope.
414 OldParamHasDfl = false;
415
416 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000417
Francois Pichet8d051e02011-04-10 03:03:52 +0000418 unsigned DiagDefaultParamID =
419 diag::err_param_default_argument_redefinition;
420
421 // MSVC accepts that default parameters be redefined for member functions
422 // of template class. The new default parameter's value is ignored.
423 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000424 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000425 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
426 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000427 // Merge the old default argument into the new parameter.
428 NewParam->setHasInheritedDefaultArg();
429 if (OldParam->hasUninstantiatedDefaultArg())
430 NewParam->setUninstantiatedDefaultArg(
431 OldParam->getUninstantiatedDefaultArg());
432 else
433 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000434 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000435 Invalid = false;
436 }
437 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000438
Francois Pichet8cf90492011-04-10 04:58:30 +0000439 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
440 // hint here. Alternatively, we could walk the type-source information
441 // for NewParam to find the last source location in the type... but it
442 // isn't worth the effort right now. This is the kind of test case that
443 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000444 // int f(int);
445 // void g(int (*fp)(int) = f);
446 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000447 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000448 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000449
450 // Look for the function declaration where the default argument was
451 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000452 for (FunctionDecl *Older = Old->getPreviousDecl();
453 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000454 if (!Older->getParamDecl(p)->hasDefaultArg())
455 break;
456
457 OldParam = Older->getParamDecl(p);
458 }
459
460 Diag(OldParam->getLocation(), diag::note_previous_definition)
461 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000462 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000463 // Merge the old default argument into the new parameter.
464 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000465 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000466 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000467 if (OldParam->hasUninstantiatedDefaultArg())
468 NewParam->setUninstantiatedDefaultArg(
469 OldParam->getUninstantiatedDefaultArg());
470 else
John McCall3d6c1782010-05-04 01:53:42 +0000471 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000472 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000473 if (New->getDescribedFunctionTemplate()) {
474 // Paragraph 4, quoted above, only applies to non-template functions.
475 Diag(NewParam->getLocation(),
476 diag::err_param_default_argument_template_redecl)
477 << NewParam->getDefaultArgRange();
478 Diag(Old->getLocation(), diag::note_template_prev_declaration)
479 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000480 } else if (New->getTemplateSpecializationKind()
481 != TSK_ImplicitInstantiation &&
482 New->getTemplateSpecializationKind() != TSK_Undeclared) {
483 // C++ [temp.expr.spec]p21:
484 // Default function arguments shall not be specified in a declaration
485 // or a definition for one of the following explicit specializations:
486 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000487 // - the explicit specialization of a member function template;
488 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000489 // template where the class template specialization to which the
490 // member function specialization belongs is implicitly
491 // instantiated.
492 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
493 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
494 << New->getDeclName()
495 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000496 } else if (New->getDeclContext()->isDependentContext()) {
497 // C++ [dcl.fct.default]p6 (DR217):
498 // Default arguments for a member function of a class template shall
499 // be specified on the initial declaration of the member function
500 // within the class template.
501 //
502 // Reading the tea leaves a bit in DR217 and its reference to DR205
503 // leads me to the conclusion that one cannot add default function
504 // arguments for an out-of-line definition of a member function of a
505 // dependent type.
506 int WhichKind = 2;
507 if (CXXRecordDecl *Record
508 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
509 if (Record->getDescribedClassTemplate())
510 WhichKind = 0;
511 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
512 WhichKind = 1;
513 else
514 WhichKind = 2;
515 }
516
517 Diag(NewParam->getLocation(),
518 diag::err_param_default_argument_member_template_redecl)
519 << WhichKind
520 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000521 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
522 CXXSpecialMember NewSM = getSpecialMember(Ctor),
523 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
524 if (NewSM != OldSM) {
525 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
526 << NewParam->getDefaultArgRange() << NewSM;
527 Diag(Old->getLocation(), diag::note_previous_declaration_special)
528 << OldSM;
529 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000530 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000531 }
532 }
533
Richard Smithff234882012-02-20 23:28:05 +0000534 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000535 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000536 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000537 if (New->isConstexpr() != Old->isConstexpr()) {
538 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
539 << New << New->isConstexpr();
540 Diag(Old->getLocation(), diag::note_previous_declaration);
541 Invalid = true;
542 }
543
Douglas Gregore13ad832010-02-12 07:32:17 +0000544 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000545 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000546
Douglas Gregorcda9c672009-02-16 17:45:42 +0000547 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000548}
549
Sebastian Redl60618fa2011-03-12 11:50:43 +0000550/// \brief Merge the exception specifications of two variable declarations.
551///
552/// This is called when there's a redeclaration of a VarDecl. The function
553/// checks if the redeclaration might have an exception specification and
554/// validates compatibility and merges the specs if necessary.
555void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
556 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000557 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000558 return;
559
560 assert(Context.hasSameType(New->getType(), Old->getType()) &&
561 "Should only be called if types are otherwise the same.");
562
563 QualType NewType = New->getType();
564 QualType OldType = Old->getType();
565
566 // We're only interested in pointers and references to functions, as well
567 // as pointers to member functions.
568 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
569 NewType = R->getPointeeType();
570 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
571 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
572 NewType = P->getPointeeType();
573 OldType = OldType->getAs<PointerType>()->getPointeeType();
574 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
575 NewType = M->getPointeeType();
576 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
577 }
578
579 if (!NewType->isFunctionProtoType())
580 return;
581
582 // There's lots of special cases for functions. For function pointers, system
583 // libraries are hopefully not as broken so that we don't need these
584 // workarounds.
585 if (CheckEquivalentExceptionSpec(
586 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
587 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
588 New->setInvalidDecl();
589 }
590}
591
Chris Lattner3d1cee32008-04-08 05:04:30 +0000592/// CheckCXXDefaultArguments - Verify that the default arguments for a
593/// function declaration are well-formed according to C++
594/// [dcl.fct.default].
595void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
596 unsigned NumParams = FD->getNumParams();
597 unsigned p;
598
Douglas Gregorc6889e72012-02-14 22:28:59 +0000599 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
600 isa<CXXMethodDecl>(FD) &&
601 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
602
Chris Lattner3d1cee32008-04-08 05:04:30 +0000603 // Find first parameter with a default argument
604 for (p = 0; p < NumParams; ++p) {
605 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000606 if (Param->hasDefaultArg()) {
607 // C++11 [expr.prim.lambda]p5:
608 // [...] Default arguments (8.3.6) shall not be specified in the
609 // parameter-declaration-clause of a lambda-declarator.
610 //
611 // FIXME: Core issue 974 strikes this sentence, we only provide an
612 // extension warning.
613 if (IsLambda)
614 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
615 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000616 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000617 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000618 }
619
620 // C++ [dcl.fct.default]p4:
621 // In a given function declaration, all parameters
622 // subsequent to a parameter with a default argument shall
623 // have default arguments supplied in this or previous
624 // declarations. A default argument shall not be redefined
625 // by a later declaration (not even to the same value).
626 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000627 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000628 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000629 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000630 if (Param->isInvalidDecl())
631 /* We already complained about this parameter. */;
632 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000633 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000634 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000635 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000636 else
Mike Stump1eb44332009-09-09 15:08:12 +0000637 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000638 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000639
Chris Lattner3d1cee32008-04-08 05:04:30 +0000640 LastMissingDefaultArg = p;
641 }
642 }
643
644 if (LastMissingDefaultArg > 0) {
645 // Some default arguments were missing. Clear out all of the
646 // default arguments up to (and including) the last missing
647 // default argument, so that we leave the function parameters
648 // in a semantically valid state.
649 for (p = 0; p <= LastMissingDefaultArg; ++p) {
650 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000651 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000652 Param->setDefaultArg(0);
653 }
654 }
655 }
656}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000657
Richard Smith9f569cc2011-10-01 02:31:28 +0000658// CheckConstexprParameterTypes - Check whether a function's parameter types
659// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000660// diagnostic and return false.
661static bool CheckConstexprParameterTypes(Sema &SemaRef,
662 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000663 unsigned ArgIndex = 0;
664 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
665 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
666 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
667 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
668 SourceLocation ParamLoc = PD->getLocation();
669 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000670 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000671 diag::err_constexpr_non_literal_param,
672 ArgIndex+1, PD->getSourceRange(),
673 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000674 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000675 }
676 return true;
677}
678
679// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
Richard Smith86c3ae42012-02-13 03:54:03 +0000680// the requirements of a constexpr function definition or a constexpr
681// constructor definition. If so, return true. If not, produce appropriate
682// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000683//
Richard Smith86c3ae42012-02-13 03:54:03 +0000684// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
685bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000686 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
687 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000688 // C++11 [dcl.constexpr]p4:
689 // The definition of a constexpr constructor shall satisfy the following
690 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000691 // - the class shall not have any virtual base classes;
Richard Smith35340502012-01-13 04:54:00 +0000692 const CXXRecordDecl *RD = MD->getParent();
Richard Smith9f569cc2011-10-01 02:31:28 +0000693 if (RD->getNumVBases()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000694 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
695 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
696 << RD->getNumVBases();
697 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
698 E = RD->vbases_end(); I != E; ++I)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000699 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000700 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000701 return false;
702 }
Richard Smith35340502012-01-13 04:54:00 +0000703 }
704
705 if (!isa<CXXConstructorDecl>(NewFD)) {
706 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000707 // The definition of a constexpr function shall satisfy the following
708 // constraints:
709 // - it shall not be virtual;
710 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
711 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000712 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000713
Richard Smith86c3ae42012-02-13 03:54:03 +0000714 // If it's not obvious why this function is virtual, find an overridden
715 // function which uses the 'virtual' keyword.
716 const CXXMethodDecl *WrittenVirtual = Method;
717 while (!WrittenVirtual->isVirtualAsWritten())
718 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
719 if (WrittenVirtual != Method)
720 Diag(WrittenVirtual->getLocation(),
721 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000722 return false;
723 }
724
725 // - its return type shall be a literal type;
726 QualType RT = NewFD->getResultType();
727 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000728 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000729 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000730 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000731 }
732
Richard Smith35340502012-01-13 04:54:00 +0000733 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000734 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000735 return false;
736
Richard Smith9f569cc2011-10-01 02:31:28 +0000737 return true;
738}
739
740/// Check the given declaration statement is legal within a constexpr function
741/// body. C++0x [dcl.constexpr]p3,p4.
742///
743/// \return true if the body is OK, false if we have diagnosed a problem.
744static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
745 DeclStmt *DS) {
746 // C++0x [dcl.constexpr]p3 and p4:
747 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
748 // contain only
749 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
750 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
751 switch ((*DclIt)->getKind()) {
752 case Decl::StaticAssert:
753 case Decl::Using:
754 case Decl::UsingShadow:
755 case Decl::UsingDirective:
756 case Decl::UnresolvedUsingTypename:
757 // - static_assert-declarations
758 // - using-declarations,
759 // - using-directives,
760 continue;
761
762 case Decl::Typedef:
763 case Decl::TypeAlias: {
764 // - typedef declarations and alias-declarations that do not define
765 // classes or enumerations,
766 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
767 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
768 // Don't allow variably-modified types in constexpr functions.
769 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
770 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
771 << TL.getSourceRange() << TL.getType()
772 << isa<CXXConstructorDecl>(Dcl);
773 return false;
774 }
775 continue;
776 }
777
778 case Decl::Enum:
779 case Decl::CXXRecord:
780 // As an extension, we allow the declaration (but not the definition) of
781 // classes and enumerations in all declarations, not just in typedef and
782 // alias declarations.
783 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
784 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
785 << isa<CXXConstructorDecl>(Dcl);
786 return false;
787 }
788 continue;
789
790 case Decl::Var:
791 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
792 << isa<CXXConstructorDecl>(Dcl);
793 return false;
794
795 default:
796 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
797 << isa<CXXConstructorDecl>(Dcl);
798 return false;
799 }
800 }
801
802 return true;
803}
804
805/// Check that the given field is initialized within a constexpr constructor.
806///
807/// \param Dcl The constexpr constructor being checked.
808/// \param Field The field being checked. This may be a member of an anonymous
809/// struct or union nested within the class being checked.
810/// \param Inits All declarations, including anonymous struct/union members and
811/// indirect members, for which any initialization was provided.
812/// \param Diagnosed Set to true if an error is produced.
813static void CheckConstexprCtorInitializer(Sema &SemaRef,
814 const FunctionDecl *Dcl,
815 FieldDecl *Field,
816 llvm::SmallSet<Decl*, 16> &Inits,
817 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000818 if (Field->isUnnamedBitfield())
819 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000820
821 if (Field->isAnonymousStructOrUnion() &&
822 Field->getType()->getAsCXXRecordDecl()->isEmpty())
823 return;
824
Richard Smith9f569cc2011-10-01 02:31:28 +0000825 if (!Inits.count(Field)) {
826 if (!Diagnosed) {
827 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
828 Diagnosed = true;
829 }
830 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
831 } else if (Field->isAnonymousStructOrUnion()) {
832 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
833 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
834 I != E; ++I)
835 // If an anonymous union contains an anonymous struct of which any member
836 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000837 if (!RD->isUnion() || Inits.count(*I))
838 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000839 }
840}
841
842/// Check the body for the given constexpr function declaration only contains
843/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
844///
845/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000846bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000847 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000848 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000849 // The definition of a constexpr function shall satisfy the following
850 // constraints: [...]
851 // - its function-body shall be = delete, = default, or a
852 // compound-statement
853 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000854 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000855 // In the definition of a constexpr constructor, [...]
856 // - its function-body shall not be a function-try-block;
857 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
858 << isa<CXXConstructorDecl>(Dcl);
859 return false;
860 }
861
862 // - its function-body shall be [...] a compound-statement that contains only
863 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
864
865 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
866 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
867 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
868 switch ((*BodyIt)->getStmtClass()) {
869 case Stmt::NullStmtClass:
870 // - null statements,
871 continue;
872
873 case Stmt::DeclStmtClass:
874 // - static_assert-declarations
875 // - using-declarations,
876 // - using-directives,
877 // - typedef declarations and alias-declarations that do not define
878 // classes or enumerations,
879 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
880 return false;
881 continue;
882
883 case Stmt::ReturnStmtClass:
884 // - and exactly one return statement;
885 if (isa<CXXConstructorDecl>(Dcl))
886 break;
887
888 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000889 continue;
890
891 default:
892 break;
893 }
894
895 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
896 << isa<CXXConstructorDecl>(Dcl);
897 return false;
898 }
899
900 if (const CXXConstructorDecl *Constructor
901 = dyn_cast<CXXConstructorDecl>(Dcl)) {
902 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000903 // DR1359:
904 // - every non-variant non-static data member and base class sub-object
905 // shall be initialized;
906 // - if the class is a non-empty union, or for each non-empty anonymous
907 // union member of a non-union class, exactly one non-static data member
908 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000909 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000910 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000911 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
912 return false;
913 }
Richard Smith6e433752011-10-10 16:38:04 +0000914 } else if (!Constructor->isDependentContext() &&
915 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000916 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
917
918 // Skip detailed checking if we have enough initializers, and we would
919 // allow at most one initializer per member.
920 bool AnyAnonStructUnionMembers = false;
921 unsigned Fields = 0;
922 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
923 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000924 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000925 AnyAnonStructUnionMembers = true;
926 break;
927 }
928 }
929 if (AnyAnonStructUnionMembers ||
930 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
931 // Check initialization of non-static data members. Base classes are
932 // always initialized so do not need to be checked. Dependent bases
933 // might not have initializers in the member initializer list.
934 llvm::SmallSet<Decl*, 16> Inits;
935 for (CXXConstructorDecl::init_const_iterator
936 I = Constructor->init_begin(), E = Constructor->init_end();
937 I != E; ++I) {
938 if (FieldDecl *FD = (*I)->getMember())
939 Inits.insert(FD);
940 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
941 Inits.insert(ID->chain_begin(), ID->chain_end());
942 }
943
944 bool Diagnosed = false;
945 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
946 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000947 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000948 if (Diagnosed)
949 return false;
950 }
951 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000952 } else {
953 if (ReturnStmts.empty()) {
954 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
955 return false;
956 }
957 if (ReturnStmts.size() > 1) {
958 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
959 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
960 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
961 return false;
962 }
963 }
964
Richard Smith5ba73e12012-02-04 00:33:54 +0000965 // C++11 [dcl.constexpr]p5:
966 // if no function argument values exist such that the function invocation
967 // substitution would produce a constant expression, the program is
968 // ill-formed; no diagnostic required.
969 // C++11 [dcl.constexpr]p3:
970 // - every constructor call and implicit conversion used in initializing the
971 // return value shall be one of those allowed in a constant expression.
972 // C++11 [dcl.constexpr]p4:
973 // - every constructor involved in initializing non-static data members and
974 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +0000975 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000976 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000977 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
978 << isa<CXXConstructorDecl>(Dcl);
979 for (size_t I = 0, N = Diags.size(); I != N; ++I)
980 Diag(Diags[I].first, Diags[I].second);
981 return false;
982 }
983
Richard Smith9f569cc2011-10-01 02:31:28 +0000984 return true;
985}
986
Douglas Gregorb48fe382008-10-31 09:07:45 +0000987/// isCurrentClassName - Determine whether the identifier II is the
988/// name of the class type currently being defined. In the case of
989/// nested classes, this will only return true if II is the name of
990/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000991bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
992 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000993 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000994
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000995 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000996 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000997 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000998 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
999 } else
1000 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1001
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001002 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001003 return &II == CurDecl->getIdentifier();
1004 else
1005 return false;
1006}
1007
Mike Stump1eb44332009-09-09 15:08:12 +00001008/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001009///
1010/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1011/// and returns NULL otherwise.
1012CXXBaseSpecifier *
1013Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1014 SourceRange SpecifierRange,
1015 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001016 TypeSourceInfo *TInfo,
1017 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001018 QualType BaseType = TInfo->getType();
1019
Douglas Gregor2943aed2009-03-03 04:44:36 +00001020 // C++ [class.union]p1:
1021 // A union shall not have base classes.
1022 if (Class->isUnion()) {
1023 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1024 << SpecifierRange;
1025 return 0;
1026 }
1027
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001028 if (EllipsisLoc.isValid() &&
1029 !TInfo->getType()->containsUnexpandedParameterPack()) {
1030 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1031 << TInfo->getTypeLoc().getSourceRange();
1032 EllipsisLoc = SourceLocation();
1033 }
1034
Douglas Gregor2943aed2009-03-03 04:44:36 +00001035 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001036 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001037 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001038 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001039
1040 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001041
1042 // Base specifiers must be record types.
1043 if (!BaseType->isRecordType()) {
1044 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1045 return 0;
1046 }
1047
1048 // C++ [class.union]p1:
1049 // A union shall not be used as a base class.
1050 if (BaseType->isUnionType()) {
1051 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1052 return 0;
1053 }
1054
1055 // C++ [class.derived]p2:
1056 // The class-name in a base-specifier shall not be an incompletely
1057 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001058 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001059 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001060 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001061 return 0;
John McCall572fc622010-08-17 07:23:57 +00001062 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001063
Eli Friedman1d954f62009-08-15 21:55:26 +00001064 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001065 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001066 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001067 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001068 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001069 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1070 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001071
Anders Carlsson1d209272011-03-25 14:55:14 +00001072 // C++ [class]p3:
1073 // If a class is marked final and it appears as a base-type-specifier in
1074 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001075 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001076 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1077 << CXXBaseDecl->getDeclName();
1078 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1079 << CXXBaseDecl->getDeclName();
1080 return 0;
1081 }
1082
John McCall572fc622010-08-17 07:23:57 +00001083 if (BaseDecl->isInvalidDecl())
1084 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001085
1086 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001087 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001088 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001089 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001090}
1091
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001092/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1093/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001094/// example:
1095/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001096/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001097BaseResult
John McCalld226f652010-08-21 09:40:31 +00001098Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001099 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001100 ParsedType basetype, SourceLocation BaseLoc,
1101 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001102 if (!classdecl)
1103 return true;
1104
Douglas Gregor40808ce2009-03-09 23:48:35 +00001105 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001106 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001107 if (!Class)
1108 return true;
1109
Nick Lewycky56062202010-07-26 16:56:01 +00001110 TypeSourceInfo *TInfo = 0;
1111 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001112
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001113 if (EllipsisLoc.isInvalid() &&
1114 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001115 UPPC_BaseType))
1116 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001117
Douglas Gregor2943aed2009-03-03 04:44:36 +00001118 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001119 Virtual, Access, TInfo,
1120 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001121 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Douglas Gregor2943aed2009-03-03 04:44:36 +00001123 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001124}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001125
Douglas Gregor2943aed2009-03-03 04:44:36 +00001126/// \brief Performs the actual work of attaching the given base class
1127/// specifiers to a C++ class.
1128bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1129 unsigned NumBases) {
1130 if (NumBases == 0)
1131 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001132
1133 // Used to keep track of which base types we have already seen, so
1134 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001135 // that the key is always the unqualified canonical type of the base
1136 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001137 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1138
1139 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001140 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001141 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001142 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001143 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001144 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001145 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001146
1147 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1148 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001149 // C++ [class.mi]p3:
1150 // A class shall not be specified as a direct base class of a
1151 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001152 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001153 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001154 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001155 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001156
1157 // Delete the duplicate base class specifier; we're going to
1158 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001159 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001160
1161 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001162 } else {
1163 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001164 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001165 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001166 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001167 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1168 if (RD->hasAttr<WeakAttr>())
1169 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001170 }
1171 }
1172
1173 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001174 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001175
1176 // Delete the remaining (good) base class specifiers, since their
1177 // data has been copied into the CXXRecordDecl.
1178 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001179 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001180
1181 return Invalid;
1182}
1183
1184/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1185/// class, after checking whether there are any duplicate base
1186/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001187void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001188 unsigned NumBases) {
1189 if (!ClassDecl || !Bases || !NumBases)
1190 return;
1191
1192 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001193 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001194 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001195}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001196
John McCall3cb0ebd2010-03-10 03:28:59 +00001197static CXXRecordDecl *GetClassForType(QualType T) {
1198 if (const RecordType *RT = T->getAs<RecordType>())
1199 return cast<CXXRecordDecl>(RT->getDecl());
1200 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1201 return ICT->getDecl();
1202 else
1203 return 0;
1204}
1205
Douglas Gregora8f32e02009-10-06 17:59:45 +00001206/// \brief Determine whether the type \p Derived is a C++ class that is
1207/// derived from the type \p Base.
1208bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001209 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001210 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001211
1212 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1213 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001214 return false;
1215
John McCall3cb0ebd2010-03-10 03:28:59 +00001216 CXXRecordDecl *BaseRD = GetClassForType(Base);
1217 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001218 return false;
1219
John McCall86ff3082010-02-04 22:26:26 +00001220 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1221 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001222}
1223
1224/// \brief Determine whether the type \p Derived is a C++ class that is
1225/// derived from the type \p Base.
1226bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001227 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001228 return false;
1229
John McCall3cb0ebd2010-03-10 03:28:59 +00001230 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1231 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001232 return false;
1233
John McCall3cb0ebd2010-03-10 03:28:59 +00001234 CXXRecordDecl *BaseRD = GetClassForType(Base);
1235 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001236 return false;
1237
Douglas Gregora8f32e02009-10-06 17:59:45 +00001238 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1239}
1240
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001241void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001242 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001243 assert(BasePathArray.empty() && "Base path array must be empty!");
1244 assert(Paths.isRecordingPaths() && "Must record paths!");
1245
1246 const CXXBasePath &Path = Paths.front();
1247
1248 // We first go backward and check if we have a virtual base.
1249 // FIXME: It would be better if CXXBasePath had the base specifier for
1250 // the nearest virtual base.
1251 unsigned Start = 0;
1252 for (unsigned I = Path.size(); I != 0; --I) {
1253 if (Path[I - 1].Base->isVirtual()) {
1254 Start = I - 1;
1255 break;
1256 }
1257 }
1258
1259 // Now add all bases.
1260 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001261 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001262}
1263
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001264/// \brief Determine whether the given base path includes a virtual
1265/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001266bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1267 for (CXXCastPath::const_iterator B = BasePath.begin(),
1268 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001269 B != BEnd; ++B)
1270 if ((*B)->isVirtual())
1271 return true;
1272
1273 return false;
1274}
1275
Douglas Gregora8f32e02009-10-06 17:59:45 +00001276/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1277/// conversion (where Derived and Base are class types) is
1278/// well-formed, meaning that the conversion is unambiguous (and
1279/// that all of the base classes are accessible). Returns true
1280/// and emits a diagnostic if the code is ill-formed, returns false
1281/// otherwise. Loc is the location where this routine should point to
1282/// if there is an error, and Range is the source range to highlight
1283/// if there is an error.
1284bool
1285Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001286 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001287 unsigned AmbigiousBaseConvID,
1288 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001289 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001290 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001291 // First, determine whether the path from Derived to Base is
1292 // ambiguous. This is slightly more expensive than checking whether
1293 // the Derived to Base conversion exists, because here we need to
1294 // explore multiple paths to determine if there is an ambiguity.
1295 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1296 /*DetectVirtual=*/false);
1297 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1298 assert(DerivationOkay &&
1299 "Can only be used with a derived-to-base conversion");
1300 (void)DerivationOkay;
1301
1302 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001303 if (InaccessibleBaseID) {
1304 // Check that the base class can be accessed.
1305 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1306 InaccessibleBaseID)) {
1307 case AR_inaccessible:
1308 return true;
1309 case AR_accessible:
1310 case AR_dependent:
1311 case AR_delayed:
1312 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001313 }
John McCall6b2accb2010-02-10 09:31:12 +00001314 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001315
1316 // Build a base path if necessary.
1317 if (BasePath)
1318 BuildBasePathArray(Paths, *BasePath);
1319 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001320 }
1321
1322 // We know that the derived-to-base conversion is ambiguous, and
1323 // we're going to produce a diagnostic. Perform the derived-to-base
1324 // search just one more time to compute all of the possible paths so
1325 // that we can print them out. This is more expensive than any of
1326 // the previous derived-to-base checks we've done, but at this point
1327 // performance isn't as much of an issue.
1328 Paths.clear();
1329 Paths.setRecordingPaths(true);
1330 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1331 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1332 (void)StillOkay;
1333
1334 // Build up a textual representation of the ambiguous paths, e.g.,
1335 // D -> B -> A, that will be used to illustrate the ambiguous
1336 // conversions in the diagnostic. We only print one of the paths
1337 // to each base class subobject.
1338 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1339
1340 Diag(Loc, AmbigiousBaseConvID)
1341 << Derived << Base << PathDisplayStr << Range << Name;
1342 return true;
1343}
1344
1345bool
1346Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001347 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001348 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001349 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001350 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001351 IgnoreAccess ? 0
1352 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001353 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001354 Loc, Range, DeclarationName(),
1355 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001356}
1357
1358
1359/// @brief Builds a string representing ambiguous paths from a
1360/// specific derived class to different subobjects of the same base
1361/// class.
1362///
1363/// This function builds a string that can be used in error messages
1364/// to show the different paths that one can take through the
1365/// inheritance hierarchy to go from the derived class to different
1366/// subobjects of a base class. The result looks something like this:
1367/// @code
1368/// struct D -> struct B -> struct A
1369/// struct D -> struct C -> struct A
1370/// @endcode
1371std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1372 std::string PathDisplayStr;
1373 std::set<unsigned> DisplayedPaths;
1374 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1375 Path != Paths.end(); ++Path) {
1376 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1377 // We haven't displayed a path to this particular base
1378 // class subobject yet.
1379 PathDisplayStr += "\n ";
1380 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1381 for (CXXBasePath::const_iterator Element = Path->begin();
1382 Element != Path->end(); ++Element)
1383 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1384 }
1385 }
1386
1387 return PathDisplayStr;
1388}
1389
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001390//===----------------------------------------------------------------------===//
1391// C++ class member Handling
1392//===----------------------------------------------------------------------===//
1393
Abramo Bagnara6206d532010-06-05 05:09:32 +00001394/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001395bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1396 SourceLocation ASLoc,
1397 SourceLocation ColonLoc,
1398 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001399 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001400 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001401 ASLoc, ColonLoc);
1402 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001403 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001404}
1405
Anders Carlsson9e682d92011-01-20 05:57:14 +00001406/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001407void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001408 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001409 if (!MD || !MD->isVirtual())
1410 return;
1411
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001412 if (MD->isDependentContext())
1413 return;
1414
Anders Carlsson9e682d92011-01-20 05:57:14 +00001415 // C++0x [class.virtual]p3:
1416 // If a virtual function is marked with the virt-specifier override and does
1417 // not override a member function of a base class,
1418 // the program is ill-formed.
1419 bool HasOverriddenMethods =
1420 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001421 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001422 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001423 diag::err_function_marked_override_not_overriding)
1424 << MD->getDeclName();
1425 return;
1426 }
1427}
1428
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001429/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1430/// function overrides a virtual member function marked 'final', according to
1431/// C++0x [class.virtual]p3.
1432bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1433 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001434 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001435 return false;
1436
1437 Diag(New->getLocation(), diag::err_final_function_overridden)
1438 << New->getDeclName();
1439 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1440 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001441}
1442
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001443static bool InitializationHasSideEffects(const FieldDecl &FD) {
1444 if (!FD.getType().isNull()) {
1445 if (const CXXRecordDecl *RD = FD.getType()->getAsCXXRecordDecl()) {
1446 return !RD->isCompleteDefinition() ||
1447 !RD->hasTrivialDefaultConstructor() ||
1448 !RD->hasTrivialDestructor();
1449 }
1450 }
1451 return false;
1452}
1453
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001454/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1455/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001456/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001457/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1458/// present (but parsing it has been deferred).
John McCalld226f652010-08-21 09:40:31 +00001459Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001460Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001461 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001462 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001463 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001464 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001465 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1466 DeclarationName Name = NameInfo.getName();
1467 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001468
1469 // For anonymous bitfields, the location should point to the type.
1470 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001471 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001472
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001473 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001474
John McCall4bde1e12010-06-04 08:34:12 +00001475 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001476 assert(!DS.isFriendSpecified());
1477
Richard Smith1ab0d902011-06-25 02:28:38 +00001478 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001479
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001480 // C++ 9.2p6: A member shall not be declared to have automatic storage
1481 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001482 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1483 // data members and cannot be applied to names declared const or static,
1484 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001485 switch (DS.getStorageClassSpec()) {
1486 case DeclSpec::SCS_unspecified:
1487 case DeclSpec::SCS_typedef:
1488 case DeclSpec::SCS_static:
1489 // FALL THROUGH.
1490 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001491 case DeclSpec::SCS_mutable:
1492 if (isFunc) {
1493 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001494 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001495 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001496 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Sebastian Redla11f42f2008-11-17 23:24:37 +00001498 // FIXME: It would be nicer if the keyword was ignored only for this
1499 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001500 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001501 }
1502 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001503 default:
1504 if (DS.getStorageClassSpecLoc().isValid())
1505 Diag(DS.getStorageClassSpecLoc(),
1506 diag::err_storageclass_invalid_for_member);
1507 else
1508 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1509 D.getMutableDeclSpec().ClearStorageClassSpecs();
1510 }
1511
Sebastian Redl669d5d72008-11-14 23:42:31 +00001512 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1513 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001514 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001515
1516 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001517 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001518 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001519
1520 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001521 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001522 Diag(Loc, diag::err_bad_variable_name)
1523 << Name;
1524 return 0;
1525 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001526
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001527 IdentifierInfo *II = Name.getAsIdentifierInfo();
1528
Douglas Gregorf2503652011-09-21 14:40:46 +00001529 // Member field could not be with "template" keyword.
1530 // So TemplateParameterLists should be empty in this case.
1531 if (TemplateParameterLists.size()) {
1532 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1533 if (TemplateParams->size()) {
1534 // There is no such thing as a member field template.
1535 Diag(D.getIdentifierLoc(), diag::err_template_member)
1536 << II
1537 << SourceRange(TemplateParams->getTemplateLoc(),
1538 TemplateParams->getRAngleLoc());
1539 } else {
1540 // There is an extraneous 'template<>' for this member.
1541 Diag(TemplateParams->getTemplateLoc(),
1542 diag::err_template_member_noparams)
1543 << II
1544 << SourceRange(TemplateParams->getTemplateLoc(),
1545 TemplateParams->getRAngleLoc());
1546 }
1547 return 0;
1548 }
1549
Douglas Gregor922fff22010-10-13 22:19:53 +00001550 if (SS.isSet() && !SS.isInvalid()) {
1551 // The user provided a superfluous scope specifier inside a class
1552 // definition:
1553 //
1554 // class X {
1555 // int X::member;
1556 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001557 if (DeclContext *DC = computeDeclContext(SS, false))
1558 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001559 else
1560 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1561 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001562
Douglas Gregor922fff22010-10-13 22:19:53 +00001563 SS.clear();
1564 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001565
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001566 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001567 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001568 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001569 } else {
Richard Smithca523302012-06-10 03:12:00 +00001570 assert(InitStyle == ICIS_NoInit);
Richard Smith7a614d82011-06-11 17:19:42 +00001571
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001572 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001573 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001574 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001575 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001576
1577 // Non-instance-fields can't have a bitfield.
1578 if (BitWidth) {
1579 if (Member->isInvalidDecl()) {
1580 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001581 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001582 // C++ 9.6p3: A bit-field shall not be a static member.
1583 // "static member 'A' cannot be a bit-field"
1584 Diag(Loc, diag::err_static_not_bitfield)
1585 << Name << BitWidth->getSourceRange();
1586 } else if (isa<TypedefDecl>(Member)) {
1587 // "typedef member 'x' cannot be a bit-field"
1588 Diag(Loc, diag::err_typedef_not_bitfield)
1589 << Name << BitWidth->getSourceRange();
1590 } else {
1591 // A function typedef ("typedef int f(); f a;").
1592 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1593 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001594 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001595 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001596 }
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Chris Lattner8b963ef2009-03-05 23:01:03 +00001598 BitWidth = 0;
1599 Member->setInvalidDecl();
1600 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001601
1602 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Douglas Gregor37b372b2009-08-20 22:52:58 +00001604 // If we have declared a member function template, set the access of the
1605 // templated declaration as well.
1606 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1607 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001608 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001609
Anders Carlssonaae5af22011-01-20 04:34:22 +00001610 if (VS.isOverrideSpecified()) {
1611 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1612 if (!MD || !MD->isVirtual()) {
1613 Diag(Member->getLocStart(),
1614 diag::override_keyword_only_allowed_on_virtual_member_functions)
1615 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001616 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001617 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001618 }
1619 if (VS.isFinalSpecified()) {
1620 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1621 if (!MD || !MD->isVirtual()) {
1622 Diag(Member->getLocStart(),
1623 diag::override_keyword_only_allowed_on_virtual_member_functions)
1624 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001625 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001626 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001627 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001628
Douglas Gregorf5251602011-03-08 17:10:18 +00001629 if (VS.getLastLocation().isValid()) {
1630 // Update the end location of a method that has a virt-specifiers.
1631 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1632 MD->setRangeEnd(VS.getLastLocation());
1633 }
1634
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001635 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001636
Douglas Gregor10bd3682008-11-17 22:58:34 +00001637 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001638
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001639 if (isInstField) {
1640 FieldDecl *FD = cast<FieldDecl>(Member);
1641 FieldCollector->Add(FD);
1642
1643 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1644 FD->getLocation())
1645 != DiagnosticsEngine::Ignored) {
1646 // Remember all explicit private FieldDecls that have a name, no side
1647 // effects and are not part of a dependent type declaration.
1648 if (!FD->isImplicit() && FD->getDeclName() &&
1649 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001650 !FD->hasAttr<UnusedAttr>() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001651 !FD->getParent()->getTypeForDecl()->isDependentType() &&
1652 !InitializationHasSideEffects(*FD))
1653 UnusedPrivateFields.insert(FD);
1654 }
1655 }
1656
John McCalld226f652010-08-21 09:40:31 +00001657 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001658}
1659
Richard Smith7a614d82011-06-11 17:19:42 +00001660/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001661/// in-class initializer for a non-static C++ class member, and after
1662/// instantiating an in-class initializer in a class template. Such actions
1663/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001664void
Richard Smithca523302012-06-10 03:12:00 +00001665Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001666 Expr *InitExpr) {
1667 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001668 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1669 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001670
1671 if (!InitExpr) {
1672 FD->setInvalidDecl();
1673 FD->removeInClassInitializer();
1674 return;
1675 }
1676
Peter Collingbournefef21892011-10-23 18:59:44 +00001677 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1678 FD->setInvalidDecl();
1679 FD->removeInClassInitializer();
1680 return;
1681 }
1682
Richard Smith7a614d82011-06-11 17:19:42 +00001683 ExprResult Init = InitExpr;
1684 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001685 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001686 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001687 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1688 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001689 Expr **Inits = &InitExpr;
1690 unsigned NumInits = 1;
1691 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00001692 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00001693 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00001694 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00001695 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1696 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001697 if (Init.isInvalid()) {
1698 FD->setInvalidDecl();
1699 return;
1700 }
1701
Richard Smithca523302012-06-10 03:12:00 +00001702 CheckImplicitConversions(Init.get(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00001703 }
1704
1705 // C++0x [class.base.init]p7:
1706 // The initialization of each base and member constitutes a
1707 // full-expression.
1708 Init = MaybeCreateExprWithCleanups(Init);
1709 if (Init.isInvalid()) {
1710 FD->setInvalidDecl();
1711 return;
1712 }
1713
1714 InitExpr = Init.release();
1715
1716 FD->setInClassInitializer(InitExpr);
1717}
1718
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001719/// \brief Find the direct and/or virtual base specifiers that
1720/// correspond to the given base type, for use in base initialization
1721/// within a constructor.
1722static bool FindBaseInitializer(Sema &SemaRef,
1723 CXXRecordDecl *ClassDecl,
1724 QualType BaseType,
1725 const CXXBaseSpecifier *&DirectBaseSpec,
1726 const CXXBaseSpecifier *&VirtualBaseSpec) {
1727 // First, check for a direct base class.
1728 DirectBaseSpec = 0;
1729 for (CXXRecordDecl::base_class_const_iterator Base
1730 = ClassDecl->bases_begin();
1731 Base != ClassDecl->bases_end(); ++Base) {
1732 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1733 // We found a direct base of this type. That's what we're
1734 // initializing.
1735 DirectBaseSpec = &*Base;
1736 break;
1737 }
1738 }
1739
1740 // Check for a virtual base class.
1741 // FIXME: We might be able to short-circuit this if we know in advance that
1742 // there are no virtual bases.
1743 VirtualBaseSpec = 0;
1744 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1745 // We haven't found a base yet; search the class hierarchy for a
1746 // virtual base class.
1747 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1748 /*DetectVirtual=*/false);
1749 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1750 BaseType, Paths)) {
1751 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1752 Path != Paths.end(); ++Path) {
1753 if (Path->back().Base->isVirtual()) {
1754 VirtualBaseSpec = Path->back().Base;
1755 break;
1756 }
1757 }
1758 }
1759 }
1760
1761 return DirectBaseSpec || VirtualBaseSpec;
1762}
1763
Sebastian Redl6df65482011-09-24 17:48:25 +00001764/// \brief Handle a C++ member initializer using braced-init-list syntax.
1765MemInitResult
1766Sema::ActOnMemInitializer(Decl *ConstructorD,
1767 Scope *S,
1768 CXXScopeSpec &SS,
1769 IdentifierInfo *MemberOrBase,
1770 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001771 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001772 SourceLocation IdLoc,
1773 Expr *InitList,
1774 SourceLocation EllipsisLoc) {
1775 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001776 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00001777 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001778}
1779
1780/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001781MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001782Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001783 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001784 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001785 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001786 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001787 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001788 SourceLocation IdLoc,
1789 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001790 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001791 SourceLocation RParenLoc,
1792 SourceLocation EllipsisLoc) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001793 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1794 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001795 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001796 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001797}
1798
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001799namespace {
1800
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001801// Callback to only accept typo corrections that can be a valid C++ member
1802// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001803class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1804 public:
1805 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1806 : ClassDecl(ClassDecl) {}
1807
1808 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1809 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1810 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1811 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1812 else
1813 return isa<TypeDecl>(ND);
1814 }
1815 return false;
1816 }
1817
1818 private:
1819 CXXRecordDecl *ClassDecl;
1820};
1821
1822}
1823
Sebastian Redl6df65482011-09-24 17:48:25 +00001824/// \brief Handle a C++ member initializer.
1825MemInitResult
1826Sema::BuildMemInitializer(Decl *ConstructorD,
1827 Scope *S,
1828 CXXScopeSpec &SS,
1829 IdentifierInfo *MemberOrBase,
1830 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001831 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001832 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001833 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00001834 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001835 if (!ConstructorD)
1836 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001838 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001839
1840 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001841 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001842 if (!Constructor) {
1843 // The user wrote a constructor initializer on a function that is
1844 // not a C++ constructor. Ignore the error for now, because we may
1845 // have more member initializers coming; we'll diagnose it just
1846 // once in ActOnMemInitializers.
1847 return true;
1848 }
1849
1850 CXXRecordDecl *ClassDecl = Constructor->getParent();
1851
1852 // C++ [class.base.init]p2:
1853 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001854 // constructor's class and, if not found in that scope, are looked
1855 // up in the scope containing the constructor's definition.
1856 // [Note: if the constructor's class contains a member with the
1857 // same name as a direct or virtual base class of the class, a
1858 // mem-initializer-id naming the member or base class and composed
1859 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001860 // mem-initializer-id for the hidden base class may be specified
1861 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001862 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001863 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001864 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001865 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001866 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001867 ValueDecl *Member;
1868 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1869 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001870 if (EllipsisLoc.isValid())
1871 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001872 << MemberOrBase
1873 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00001874
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001875 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001876 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001877 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001878 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001879 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001880 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001881 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001882
1883 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001884 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001885 } else if (DS.getTypeSpecType() == TST_decltype) {
1886 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001887 } else {
1888 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1889 LookupParsedName(R, S, &SS);
1890
1891 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1892 if (!TyD) {
1893 if (R.isAmbiguous()) return true;
1894
John McCallfd225442010-04-09 19:01:14 +00001895 // We don't want access-control diagnostics here.
1896 R.suppressDiagnostics();
1897
Douglas Gregor7a886e12010-01-19 06:46:48 +00001898 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1899 bool NotUnknownSpecialization = false;
1900 DeclContext *DC = computeDeclContext(SS, false);
1901 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1902 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1903
1904 if (!NotUnknownSpecialization) {
1905 // When the scope specifier can refer to a member of an unknown
1906 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001907 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1908 SS.getWithLocInContext(Context),
1909 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001910 if (BaseType.isNull())
1911 return true;
1912
Douglas Gregor7a886e12010-01-19 06:46:48 +00001913 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001914 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001915 }
1916 }
1917
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001918 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001919 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001920 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001921 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001922 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001923 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001924 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1925 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001926 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001927 // We have found a non-static data member with a similar
1928 // name to what was typed; complain and initialize that
1929 // member.
1930 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1931 << MemberOrBase << true << CorrectedQuotedStr
1932 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1933 Diag(Member->getLocation(), diag::note_previous_decl)
1934 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001935
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001936 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001937 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001938 const CXXBaseSpecifier *DirectBaseSpec;
1939 const CXXBaseSpecifier *VirtualBaseSpec;
1940 if (FindBaseInitializer(*this, ClassDecl,
1941 Context.getTypeDeclType(Type),
1942 DirectBaseSpec, VirtualBaseSpec)) {
1943 // We have found a direct or virtual base class with a
1944 // similar name to what was typed; complain and initialize
1945 // that base class.
1946 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001947 << MemberOrBase << false << CorrectedQuotedStr
1948 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001949
1950 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1951 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00001952 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00001953 diag::note_base_class_specified_here)
1954 << BaseSpec->getType()
1955 << BaseSpec->getSourceRange();
1956
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001957 TyD = Type;
1958 }
1959 }
1960 }
1961
Douglas Gregor7a886e12010-01-19 06:46:48 +00001962 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001963 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001964 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001965 return true;
1966 }
John McCall2b194412009-12-21 10:41:20 +00001967 }
1968
Douglas Gregor7a886e12010-01-19 06:46:48 +00001969 if (BaseType.isNull()) {
1970 BaseType = Context.getTypeDeclType(TyD);
1971 if (SS.isSet()) {
1972 NestedNameSpecifier *Qualifier =
1973 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001974
Douglas Gregor7a886e12010-01-19 06:46:48 +00001975 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001976 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001977 }
John McCall2b194412009-12-21 10:41:20 +00001978 }
1979 }
Mike Stump1eb44332009-09-09 15:08:12 +00001980
John McCalla93c9342009-12-07 02:54:59 +00001981 if (!TInfo)
1982 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001983
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001984 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001985}
1986
Chandler Carruth81c64772011-09-03 01:14:15 +00001987/// Checks a member initializer expression for cases where reference (or
1988/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001989static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1990 Expr *Init,
1991 SourceLocation IdLoc) {
1992 QualType MemberTy = Member->getType();
1993
1994 // We only handle pointers and references currently.
1995 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1996 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1997 return;
1998
1999 const bool IsPointer = MemberTy->isPointerType();
2000 if (IsPointer) {
2001 if (const UnaryOperator *Op
2002 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2003 // The only case we're worried about with pointers requires taking the
2004 // address.
2005 if (Op->getOpcode() != UO_AddrOf)
2006 return;
2007
2008 Init = Op->getSubExpr();
2009 } else {
2010 // We only handle address-of expression initializers for pointers.
2011 return;
2012 }
2013 }
2014
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002015 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2016 // Taking the address of a temporary will be diagnosed as a hard error.
2017 if (IsPointer)
2018 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002019
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002020 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2021 << Member << Init->getSourceRange();
2022 } else if (const DeclRefExpr *DRE
2023 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2024 // We only warn when referring to a non-reference parameter declaration.
2025 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2026 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002027 return;
2028
2029 S.Diag(Init->getExprLoc(),
2030 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2031 : diag::warn_bind_ref_member_to_parameter)
2032 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002033 } else {
2034 // Other initializers are fine.
2035 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002036 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002037
2038 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2039 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002040}
2041
Richard Trieude5e75c2012-06-14 23:11:34 +00002042namespace {
2043 class UninitializedFieldVisitor
2044 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2045 Sema &S;
2046 ValueDecl *VD;
2047 public:
2048 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2049 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
2050 S(S), VD(VD) {
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002051 }
2052
Richard Trieude5e75c2012-06-14 23:11:34 +00002053 void HandleExpr(Expr *E) {
2054 if (!E) return;
2055
2056 // Expressions like x(x) sometimes lack the surrounding expressions
2057 // but need to be checked anyways.
2058 HandleValue(E);
2059 Visit(E);
2060 }
2061
2062 void HandleValue(Expr *E) {
2063 E = E->IgnoreParens();
2064
Richard Trieue0991252012-06-14 23:18:09 +00002065 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieude5e75c2012-06-14 23:11:34 +00002066 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2067 return;
Richard Trieue0991252012-06-14 23:18:09 +00002068 Expr *Base = E;
Richard Trieude5e75c2012-06-14 23:11:34 +00002069 while (isa<MemberExpr>(Base)) {
2070 ME = dyn_cast<MemberExpr>(Base);
2071 if (VarDecl *VarD = dyn_cast<VarDecl>(ME->getMemberDecl()))
2072 if (VarD->hasGlobalStorage())
2073 return;
2074 Base = ME->getBase();
2075 }
2076
2077 if (VD == ME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
2078 S.Diag(ME->getExprLoc(), diag::warn_field_is_uninit);
2079 return;
2080 }
John McCallb4190042009-11-04 23:02:40 +00002081 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002082
2083 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2084 HandleValue(CO->getTrueExpr());
2085 HandleValue(CO->getFalseExpr());
2086 return;
2087 }
2088
2089 if (BinaryConditionalOperator *BCO =
2090 dyn_cast<BinaryConditionalOperator>(E)) {
2091 HandleValue(BCO->getCommon());
2092 HandleValue(BCO->getFalseExpr());
2093 return;
2094 }
2095
2096 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2097 switch (BO->getOpcode()) {
2098 default:
2099 return;
2100 case(BO_PtrMemD):
2101 case(BO_PtrMemI):
2102 HandleValue(BO->getLHS());
2103 return;
2104 case(BO_Comma):
2105 HandleValue(BO->getRHS());
2106 return;
2107 }
2108 }
John McCallb4190042009-11-04 23:02:40 +00002109 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002110
2111 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2112 if (E->getCastKind() == CK_LValueToRValue)
2113 HandleValue(E->getSubExpr());
2114
2115 Inherited::VisitImplicitCastExpr(E);
John McCallb4190042009-11-04 23:02:40 +00002116 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002117
2118 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2119 Expr *Callee = E->getCallee();
2120 if (isa<MemberExpr>(Callee))
2121 HandleValue(Callee);
2122
2123 Inherited::VisitCXXMemberCallExpr(E);
2124 }
2125 };
2126 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2127 ValueDecl *VD) {
2128 UninitializedFieldVisitor(S, VD).HandleExpr(E);
John McCallb4190042009-11-04 23:02:40 +00002129 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002130} // namespace
John McCallb4190042009-11-04 23:02:40 +00002131
John McCallf312b1e2010-08-26 23:41:50 +00002132MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002133Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002134 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002135 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2136 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2137 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002138 "Member must be a FieldDecl or IndirectFieldDecl");
2139
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002140 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002141 return true;
2142
Douglas Gregor464b2f02010-11-05 22:21:31 +00002143 if (Member->isInvalidDecl())
2144 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002145
John McCallb4190042009-11-04 23:02:40 +00002146 // Diagnose value-uses of fields to initialize themselves, e.g.
2147 // foo(foo)
2148 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002149 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002150 Expr **Args;
2151 unsigned NumArgs;
2152 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2153 Args = ParenList->getExprs();
2154 NumArgs = ParenList->getNumExprs();
2155 } else {
2156 InitListExpr *InitList = cast<InitListExpr>(Init);
2157 Args = InitList->getInits();
2158 NumArgs = InitList->getNumInits();
2159 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002160
2161 // Mark FieldDecl as being used if it is a non-primitive type and the
2162 // initializer does not call the default constructor (which is trivial
2163 // for all entries in UnusedPrivateFields).
2164 // FIXME: Make this smarter once more side effect-free types can be
2165 // determined.
2166 if (NumArgs > 0) {
2167 if (Member->getType()->isRecordType()) {
2168 UnusedPrivateFields.remove(Member);
2169 } else {
2170 for (unsigned i = 0; i < NumArgs; ++i) {
2171 if (Args[i]->HasSideEffects(Context)) {
2172 UnusedPrivateFields.remove(Member);
2173 break;
2174 }
2175 }
2176 }
2177 }
2178
Richard Trieude5e75c2012-06-14 23:11:34 +00002179 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2180 != DiagnosticsEngine::Ignored)
2181 for (unsigned i = 0; i < NumArgs; ++i)
2182 // FIXME: Warn about the case when other fields are used before being
John McCallb4190042009-11-04 23:02:40 +00002183 // uninitialized. For example, let this field be the i'th field. When
2184 // initializing the i'th field, throw a warning if any of the >= i'th
2185 // fields are used, as they are not yet initialized.
2186 // Right now we are only handling the case where the i'th field uses
2187 // itself in its initializer.
Richard Trieude5e75c2012-06-14 23:11:34 +00002188 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002189
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002190 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002191
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002192 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002193 // Can't check initialization for a member of dependent type or when
2194 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002195 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002196 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002197 bool InitList = false;
2198 if (isa<InitListExpr>(Init)) {
2199 InitList = true;
2200 Args = &Init;
2201 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002202
2203 if (isStdInitializerList(Member->getType(), 0)) {
2204 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2205 << /*at end of ctor*/1 << InitRange;
2206 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002207 }
2208
Chandler Carruth894aed92010-12-06 09:23:57 +00002209 // Initialize the member.
2210 InitializedEntity MemberEntity =
2211 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2212 : InitializedEntity::InitializeMember(IndirectMember, 0);
2213 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002214 InitList ? InitializationKind::CreateDirectList(IdLoc)
2215 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2216 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002217
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002218 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2219 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2220 MultiExprArg(*this, Args, NumArgs),
2221 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002222 if (MemberInit.isInvalid())
2223 return true;
2224
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002225 CheckImplicitConversions(MemberInit.get(),
2226 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002227
2228 // C++0x [class.base.init]p7:
2229 // The initialization of each base and member constitutes a
2230 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002231 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002232 if (MemberInit.isInvalid())
2233 return true;
2234
2235 // If we are in a dependent context, template instantiation will
2236 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002237 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002238 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2239 // of the information that we have about the member
2240 // initializer. However, deconstructing the ASTs is a dicey process,
2241 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002242 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002243 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002244 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002245 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002246 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2247 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002248 }
2249
Chandler Carruth894aed92010-12-06 09:23:57 +00002250 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002251 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2252 InitRange.getBegin(), Init,
2253 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002254 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002255 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2256 InitRange.getBegin(), Init,
2257 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002258 }
Eli Friedman59c04372009-07-29 19:44:27 +00002259}
2260
John McCallf312b1e2010-08-26 23:41:50 +00002261MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002262Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002263 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002264 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002265 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002266 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002267 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002268 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002269
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002270 bool InitList = true;
2271 Expr **Args = &Init;
2272 unsigned NumArgs = 1;
2273 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2274 InitList = false;
2275 Args = ParenList->getExprs();
2276 NumArgs = ParenList->getNumExprs();
2277 }
2278
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002279 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002280 // Initialize the object.
2281 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2282 QualType(ClassDecl->getTypeForDecl(), 0));
2283 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002284 InitList ? InitializationKind::CreateDirectList(NameLoc)
2285 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2286 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002287 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2288 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2289 MultiExprArg(*this, Args,NumArgs),
2290 0);
Sean Hunt41717662011-02-26 19:13:13 +00002291 if (DelegationInit.isInvalid())
2292 return true;
2293
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002294 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2295 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002296
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002297 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002298
2299 // C++0x [class.base.init]p7:
2300 // The initialization of each base and member constitutes a
2301 // full-expression.
2302 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2303 if (DelegationInit.isInvalid())
2304 return true;
2305
Eli Friedmand21016f2012-05-19 23:35:23 +00002306 // If we are in a dependent context, template instantiation will
2307 // perform this type-checking again. Just save the arguments that we
2308 // received in a ParenListExpr.
2309 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2310 // of the information that we have about the base
2311 // initializer. However, deconstructing the ASTs is a dicey process,
2312 // and this approach is far more likely to get the corner cases right.
2313 if (CurContext->isDependentContext())
2314 DelegationInit = Owned(Init);
2315
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002316 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002317 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002318 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002319}
2320
2321MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002322Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002323 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002324 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002325 SourceLocation BaseLoc
2326 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002327
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002328 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2329 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2330 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2331
2332 // C++ [class.base.init]p2:
2333 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002334 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002335 // of that class, the mem-initializer is ill-formed. A
2336 // mem-initializer-list can initialize a base class using any
2337 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002338 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002339
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002340 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002341 if (EllipsisLoc.isValid()) {
2342 // This is a pack expansion.
2343 if (!BaseType->containsUnexpandedParameterPack()) {
2344 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002345 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002346
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002347 EllipsisLoc = SourceLocation();
2348 }
2349 } else {
2350 // Check for any unexpanded parameter packs.
2351 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2352 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002353
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002354 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002355 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002356 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002357
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002358 // Check for direct and virtual base classes.
2359 const CXXBaseSpecifier *DirectBaseSpec = 0;
2360 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2361 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002362 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2363 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002364 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002365
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002366 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2367 VirtualBaseSpec);
2368
2369 // C++ [base.class.init]p2:
2370 // Unless the mem-initializer-id names a nonstatic data member of the
2371 // constructor's class or a direct or virtual base of that class, the
2372 // mem-initializer is ill-formed.
2373 if (!DirectBaseSpec && !VirtualBaseSpec) {
2374 // If the class has any dependent bases, then it's possible that
2375 // one of those types will resolve to the same type as
2376 // BaseType. Therefore, just treat this as a dependent base
2377 // class initialization. FIXME: Should we try to check the
2378 // initialization anyway? It seems odd.
2379 if (ClassDecl->hasAnyDependentBases())
2380 Dependent = true;
2381 else
2382 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2383 << BaseType << Context.getTypeDeclType(ClassDecl)
2384 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2385 }
2386 }
2387
2388 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002389 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002390
Sebastian Redl6df65482011-09-24 17:48:25 +00002391 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2392 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002393 InitRange.getBegin(), Init,
2394 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002395 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002396
2397 // C++ [base.class.init]p2:
2398 // If a mem-initializer-id is ambiguous because it designates both
2399 // a direct non-virtual base class and an inherited virtual base
2400 // class, the mem-initializer is ill-formed.
2401 if (DirectBaseSpec && VirtualBaseSpec)
2402 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002403 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002404
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002405 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002406 if (!BaseSpec)
2407 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2408
2409 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002410 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002411 Expr **Args = &Init;
2412 unsigned NumArgs = 1;
2413 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002414 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002415 Args = ParenList->getExprs();
2416 NumArgs = ParenList->getNumExprs();
2417 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002418
2419 InitializedEntity BaseEntity =
2420 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2421 InitializationKind Kind =
2422 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2423 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2424 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002425 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2426 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2427 MultiExprArg(*this, Args, NumArgs),
2428 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002429 if (BaseInit.isInvalid())
2430 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002431
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002432 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002433
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002434 // C++0x [class.base.init]p7:
2435 // The initialization of each base and member constitutes a
2436 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002437 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002438 if (BaseInit.isInvalid())
2439 return true;
2440
2441 // If we are in a dependent context, template instantiation will
2442 // perform this type-checking again. Just save the arguments that we
2443 // received in a ParenListExpr.
2444 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2445 // of the information that we have about the base
2446 // initializer. However, deconstructing the ASTs is a dicey process,
2447 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002448 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002449 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002450
Sean Huntcbb67482011-01-08 20:30:50 +00002451 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002452 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002453 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002454 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002455 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002456}
2457
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002458// Create a static_cast\<T&&>(expr).
2459static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2460 QualType ExprType = E->getType();
2461 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2462 SourceLocation ExprLoc = E->getLocStart();
2463 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2464 TargetType, ExprLoc);
2465
2466 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2467 SourceRange(ExprLoc, ExprLoc),
2468 E->getSourceRange()).take();
2469}
2470
Anders Carlssone5ef7402010-04-23 03:10:23 +00002471/// ImplicitInitializerKind - How an implicit base or member initializer should
2472/// initialize its base or member.
2473enum ImplicitInitializerKind {
2474 IIK_Default,
2475 IIK_Copy,
2476 IIK_Move
2477};
2478
Anders Carlssondefefd22010-04-23 02:00:02 +00002479static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002480BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002481 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002482 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002483 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002484 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002485 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002486 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2487 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002488
John McCall60d7b3a2010-08-24 06:29:42 +00002489 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002490
2491 switch (ImplicitInitKind) {
2492 case IIK_Default: {
2493 InitializationKind InitKind
2494 = InitializationKind::CreateDefault(Constructor->getLocation());
2495 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2496 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002497 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002498 break;
2499 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002500
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002501 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002502 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002503 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002504 ParmVarDecl *Param = Constructor->getParamDecl(0);
2505 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002506
Anders Carlssone5ef7402010-04-23 03:10:23 +00002507 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002508 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002509 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002510 Constructor->getLocation(), ParamType,
2511 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002512
Eli Friedman5f2987c2012-02-02 03:46:19 +00002513 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2514
Anders Carlssonc7957502010-04-24 22:02:54 +00002515 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002516 QualType ArgTy =
2517 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2518 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002519
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002520 if (Moving) {
2521 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2522 }
2523
John McCallf871d0c2010-08-07 06:22:56 +00002524 CXXCastPath BasePath;
2525 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002526 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2527 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002528 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002529 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002530
Anders Carlssone5ef7402010-04-23 03:10:23 +00002531 InitializationKind InitKind
2532 = InitializationKind::CreateDirect(Constructor->getLocation(),
2533 SourceLocation(), SourceLocation());
2534 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2535 &CopyCtorArg, 1);
2536 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002537 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002538 break;
2539 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002540 }
John McCall9ae2f072010-08-23 23:25:46 +00002541
Douglas Gregor53c374f2010-12-07 00:41:46 +00002542 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002543 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002544 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002545
Anders Carlssondefefd22010-04-23 02:00:02 +00002546 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002547 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002548 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2549 SourceLocation()),
2550 BaseSpec->isVirtual(),
2551 SourceLocation(),
2552 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002553 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002554 SourceLocation());
2555
Anders Carlssondefefd22010-04-23 02:00:02 +00002556 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002557}
2558
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002559static bool RefersToRValueRef(Expr *MemRef) {
2560 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2561 return Referenced->getType()->isRValueReferenceType();
2562}
2563
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002564static bool
2565BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002566 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002567 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002568 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002569 if (Field->isInvalidDecl())
2570 return true;
2571
Chandler Carruthf186b542010-06-29 23:50:44 +00002572 SourceLocation Loc = Constructor->getLocation();
2573
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002574 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2575 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002576 ParmVarDecl *Param = Constructor->getParamDecl(0);
2577 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002578
2579 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002580 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2581 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002582
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002583 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002584 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002585 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002586 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002587
Eli Friedman5f2987c2012-02-02 03:46:19 +00002588 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2589
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002590 if (Moving) {
2591 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2592 }
2593
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002594 // Build a reference to this field within the parameter.
2595 CXXScopeSpec SS;
2596 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2597 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002598 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2599 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002600 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002601 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002602 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002603 ParamType, Loc,
2604 /*IsArrow=*/false,
2605 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002606 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002607 /*FirstQualifierInScope=*/0,
2608 MemberLookup,
2609 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002610 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002611 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002612
2613 // C++11 [class.copy]p15:
2614 // - if a member m has rvalue reference type T&&, it is direct-initialized
2615 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002616 if (RefersToRValueRef(CtorArg.get())) {
2617 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002618 }
2619
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002620 // When the field we are copying is an array, create index variables for
2621 // each dimension of the array. We use these index variables to subscript
2622 // the source array, and other clients (e.g., CodeGen) will perform the
2623 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002624 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002625 QualType BaseType = Field->getType();
2626 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002627 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002628 while (const ConstantArrayType *Array
2629 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002630 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002631 // Create the iteration variable for this array index.
2632 IdentifierInfo *IterationVarName = 0;
2633 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002634 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002635 llvm::raw_svector_ostream OS(Str);
2636 OS << "__i" << IndexVariables.size();
2637 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2638 }
2639 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002640 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002641 IterationVarName, SizeType,
2642 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002643 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002644 IndexVariables.push_back(IterationVar);
2645
2646 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002647 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002648 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002649 assert(!IterationVarRef.isInvalid() &&
2650 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002651 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2652 assert(!IterationVarRef.isInvalid() &&
2653 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002654
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002655 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002656 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002657 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002658 Loc);
2659 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002660 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002661
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002662 BaseType = Array->getElementType();
2663 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002664
2665 // The array subscript expression is an lvalue, which is wrong for moving.
2666 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002667 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002668
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002669 // Construct the entity that we will be initializing. For an array, this
2670 // will be first element in the array, which may require several levels
2671 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002672 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002673 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002674 if (Indirect)
2675 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2676 else
2677 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002678 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2679 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2680 0,
2681 Entities.back()));
2682
2683 // Direct-initialize to use the copy constructor.
2684 InitializationKind InitKind =
2685 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2686
Sebastian Redl74e611a2011-09-04 18:14:28 +00002687 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002688 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002689 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002690
John McCall60d7b3a2010-08-24 06:29:42 +00002691 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002692 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002693 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002694 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002695 if (MemberInit.isInvalid())
2696 return true;
2697
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002698 if (Indirect) {
2699 assert(IndexVariables.size() == 0 &&
2700 "Indirect field improperly initialized");
2701 CXXMemberInit
2702 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2703 Loc, Loc,
2704 MemberInit.takeAs<Expr>(),
2705 Loc);
2706 } else
2707 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2708 Loc, MemberInit.takeAs<Expr>(),
2709 Loc,
2710 IndexVariables.data(),
2711 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002712 return false;
2713 }
2714
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002715 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2716
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002717 QualType FieldBaseElementType =
2718 SemaRef.Context.getBaseElementType(Field->getType());
2719
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002720 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002721 InitializedEntity InitEntity
2722 = Indirect? InitializedEntity::InitializeMember(Indirect)
2723 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002724 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002725 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002726
2727 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002728 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002729 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002730
Douglas Gregor53c374f2010-12-07 00:41:46 +00002731 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002732 if (MemberInit.isInvalid())
2733 return true;
2734
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002735 if (Indirect)
2736 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2737 Indirect, Loc,
2738 Loc,
2739 MemberInit.get(),
2740 Loc);
2741 else
2742 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2743 Field, Loc, Loc,
2744 MemberInit.get(),
2745 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002746 return false;
2747 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002748
Sean Hunt1f2f3842011-05-17 00:19:05 +00002749 if (!Field->getParent()->isUnion()) {
2750 if (FieldBaseElementType->isReferenceType()) {
2751 SemaRef.Diag(Constructor->getLocation(),
2752 diag::err_uninitialized_member_in_ctor)
2753 << (int)Constructor->isImplicit()
2754 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2755 << 0 << Field->getDeclName();
2756 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2757 return true;
2758 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002759
Sean Hunt1f2f3842011-05-17 00:19:05 +00002760 if (FieldBaseElementType.isConstQualified()) {
2761 SemaRef.Diag(Constructor->getLocation(),
2762 diag::err_uninitialized_member_in_ctor)
2763 << (int)Constructor->isImplicit()
2764 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2765 << 1 << Field->getDeclName();
2766 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2767 return true;
2768 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002769 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002770
David Blaikie4e4d0842012-03-11 07:00:24 +00002771 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002772 FieldBaseElementType->isObjCRetainableType() &&
2773 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2774 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2775 // Instant objects:
2776 // Default-initialize Objective-C pointers to NULL.
2777 CXXMemberInit
2778 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2779 Loc, Loc,
2780 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2781 Loc);
2782 return false;
2783 }
2784
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002785 // Nothing to initialize.
2786 CXXMemberInit = 0;
2787 return false;
2788}
John McCallf1860e52010-05-20 23:23:51 +00002789
2790namespace {
2791struct BaseAndFieldInfo {
2792 Sema &S;
2793 CXXConstructorDecl *Ctor;
2794 bool AnyErrorsInInits;
2795 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002796 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002797 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002798
2799 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2800 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002801 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2802 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002803 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002804 else if (Generated && Ctor->isMoveConstructor())
2805 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002806 else
2807 IIK = IIK_Default;
2808 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002809
2810 bool isImplicitCopyOrMove() const {
2811 switch (IIK) {
2812 case IIK_Copy:
2813 case IIK_Move:
2814 return true;
2815
2816 case IIK_Default:
2817 return false;
2818 }
David Blaikie30263482012-01-20 21:50:17 +00002819
2820 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002821 }
John McCallf1860e52010-05-20 23:23:51 +00002822};
2823}
2824
Richard Smitha4950662011-09-19 13:34:43 +00002825/// \brief Determine whether the given indirect field declaration is somewhere
2826/// within an anonymous union.
2827static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2828 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2829 CEnd = F->chain_end();
2830 C != CEnd; ++C)
2831 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2832 if (Record->isUnion())
2833 return true;
2834
2835 return false;
2836}
2837
Douglas Gregorddb21472011-11-02 23:04:16 +00002838/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2839/// array type.
2840static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2841 if (T->isIncompleteArrayType())
2842 return true;
2843
2844 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2845 if (!ArrayT->getSize())
2846 return true;
2847
2848 T = ArrayT->getElementType();
2849 }
2850
2851 return false;
2852}
2853
Richard Smith7a614d82011-06-11 17:19:42 +00002854static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002855 FieldDecl *Field,
2856 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002857
Chandler Carruthe861c602010-06-30 02:59:29 +00002858 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002859 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002860 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002861 return false;
2862 }
2863
Richard Smith7a614d82011-06-11 17:19:42 +00002864 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2865 // has a brace-or-equal-initializer, the entity is initialized as specified
2866 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002867 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002868 CXXCtorInitializer *Init;
2869 if (Indirect)
2870 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2871 SourceLocation(),
2872 SourceLocation(), 0,
2873 SourceLocation());
2874 else
2875 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2876 SourceLocation(),
2877 SourceLocation(), 0,
2878 SourceLocation());
2879 Info.AllToInit.push_back(Init);
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002880
2881 // Check whether this initializer makes the field "used".
2882 Expr *InitExpr = Field->getInClassInitializer();
2883 if (Field->getType()->isRecordType() ||
2884 (InitExpr && InitExpr->HasSideEffects(SemaRef.Context)))
2885 SemaRef.UnusedPrivateFields.remove(Field);
2886
Richard Smith7a614d82011-06-11 17:19:42 +00002887 return false;
2888 }
2889
Richard Smithc115f632011-09-18 11:14:50 +00002890 // Don't build an implicit initializer for union members if none was
2891 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002892 if (Field->getParent()->isUnion() ||
2893 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002894 return false;
2895
Douglas Gregorddb21472011-11-02 23:04:16 +00002896 // Don't initialize incomplete or zero-length arrays.
2897 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2898 return false;
2899
John McCallf1860e52010-05-20 23:23:51 +00002900 // Don't try to build an implicit initializer if there were semantic
2901 // errors in any of the initializers (and therefore we might be
2902 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002903 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002904 return false;
2905
Sean Huntcbb67482011-01-08 20:30:50 +00002906 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002907 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2908 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002909 return true;
John McCallf1860e52010-05-20 23:23:51 +00002910
Francois Pichet00eb3f92010-12-04 09:14:42 +00002911 if (Init)
2912 Info.AllToInit.push_back(Init);
2913
John McCallf1860e52010-05-20 23:23:51 +00002914 return false;
2915}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002916
2917bool
2918Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2919 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002920 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002921 Constructor->setNumCtorInitializers(1);
2922 CXXCtorInitializer **initializer =
2923 new (Context) CXXCtorInitializer*[1];
2924 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2925 Constructor->setCtorInitializers(initializer);
2926
Sean Huntb76af9c2011-05-03 23:05:34 +00002927 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002928 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002929 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2930 }
2931
Sean Huntc1598702011-05-05 00:05:47 +00002932 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002933
Sean Hunt059ce0d2011-05-01 07:04:31 +00002934 return false;
2935}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002936
John McCallb77115d2011-06-17 00:18:42 +00002937bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2938 CXXCtorInitializer **Initializers,
2939 unsigned NumInitializers,
2940 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002941 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002942 // Just store the initializers as written, they will be checked during
2943 // instantiation.
2944 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002945 Constructor->setNumCtorInitializers(NumInitializers);
2946 CXXCtorInitializer **baseOrMemberInitializers =
2947 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002948 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002949 NumInitializers * sizeof(CXXCtorInitializer*));
2950 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002951 }
2952
2953 return false;
2954 }
2955
John McCallf1860e52010-05-20 23:23:51 +00002956 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002957
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002958 // We need to build the initializer AST according to order of construction
2959 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002960 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002961 if (!ClassDecl)
2962 return true;
2963
Eli Friedman80c30da2009-11-09 19:20:36 +00002964 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002965
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002966 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002967 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002968
2969 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002970 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002971 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002972 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002973 }
2974
Anders Carlsson711f34a2010-04-21 19:52:01 +00002975 // Keep track of the direct virtual bases.
2976 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2977 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2978 E = ClassDecl->bases_end(); I != E; ++I) {
2979 if (I->isVirtual())
2980 DirectVBases.insert(I);
2981 }
2982
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002983 // Push virtual bases before others.
2984 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2985 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2986
Sean Huntcbb67482011-01-08 20:30:50 +00002987 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002988 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2989 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002990 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002991 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002992 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002993 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002994 VBase, IsInheritedVirtualBase,
2995 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002996 HadError = true;
2997 continue;
2998 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002999
John McCallf1860e52010-05-20 23:23:51 +00003000 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003001 }
3002 }
Mike Stump1eb44332009-09-09 15:08:12 +00003003
John McCallf1860e52010-05-20 23:23:51 +00003004 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003005 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3006 E = ClassDecl->bases_end(); Base != E; ++Base) {
3007 // Virtuals are in the virtual base list and already constructed.
3008 if (Base->isVirtual())
3009 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003010
Sean Huntcbb67482011-01-08 20:30:50 +00003011 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003012 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3013 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003014 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003015 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003016 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003017 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003018 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003019 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003020 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003021 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003022
John McCallf1860e52010-05-20 23:23:51 +00003023 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003024 }
3025 }
Mike Stump1eb44332009-09-09 15:08:12 +00003026
John McCallf1860e52010-05-20 23:23:51 +00003027 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003028 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3029 MemEnd = ClassDecl->decls_end();
3030 Mem != MemEnd; ++Mem) {
3031 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003032 // C++ [class.bit]p2:
3033 // A declaration for a bit-field that omits the identifier declares an
3034 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3035 // initialized.
3036 if (F->isUnnamedBitfield())
3037 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003038
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003039 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003040 // handle anonymous struct/union fields based on their individual
3041 // indirect fields.
3042 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3043 continue;
3044
3045 if (CollectFieldInitializer(*this, Info, F))
3046 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003047 continue;
3048 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003049
3050 // Beyond this point, we only consider default initialization.
3051 if (Info.IIK != IIK_Default)
3052 continue;
3053
3054 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3055 if (F->getType()->isIncompleteArrayType()) {
3056 assert(ClassDecl->hasFlexibleArrayMember() &&
3057 "Incomplete array type is not valid");
3058 continue;
3059 }
3060
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003061 // Initialize each field of an anonymous struct individually.
3062 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3063 HadError = true;
3064
3065 continue;
3066 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003067 }
Mike Stump1eb44332009-09-09 15:08:12 +00003068
John McCallf1860e52010-05-20 23:23:51 +00003069 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003070 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003071 Constructor->setNumCtorInitializers(NumInitializers);
3072 CXXCtorInitializer **baseOrMemberInitializers =
3073 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003074 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003075 NumInitializers * sizeof(CXXCtorInitializer*));
3076 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003077
John McCallef027fe2010-03-16 21:39:52 +00003078 // Constructors implicitly reference the base and member
3079 // destructors.
3080 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3081 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003082 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003083
3084 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003085}
3086
Eli Friedman6347f422009-07-21 19:28:10 +00003087static void *GetKeyForTopLevelField(FieldDecl *Field) {
3088 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003089 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003090 if (RT->getDecl()->isAnonymousStructOrUnion())
3091 return static_cast<void *>(RT->getDecl());
3092 }
3093 return static_cast<void *>(Field);
3094}
3095
Anders Carlssonea356fb2010-04-02 05:42:15 +00003096static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003097 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003098}
3099
Anders Carlssonea356fb2010-04-02 05:42:15 +00003100static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003101 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003102 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003103 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003104
Eli Friedman6347f422009-07-21 19:28:10 +00003105 // For fields injected into the class via declaration of an anonymous union,
3106 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003107 FieldDecl *Field = Member->getAnyMember();
3108
John McCall3c3ccdb2010-04-10 09:28:51 +00003109 // If the field is a member of an anonymous struct or union, our key
3110 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003111 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003112 if (RD->isAnonymousStructOrUnion()) {
3113 while (true) {
3114 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3115 if (Parent->isAnonymousStructOrUnion())
3116 RD = Parent;
3117 else
3118 break;
3119 }
3120
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003121 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003122 }
Mike Stump1eb44332009-09-09 15:08:12 +00003123
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003124 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003125}
3126
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003127static void
3128DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003129 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003130 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003131 unsigned NumInits) {
3132 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003133 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003134
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003135 // Don't check initializers order unless the warning is enabled at the
3136 // location of at least one initializer.
3137 bool ShouldCheckOrder = false;
3138 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003139 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003140 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3141 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003142 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003143 ShouldCheckOrder = true;
3144 break;
3145 }
3146 }
3147 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003148 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003149
John McCalld6ca8da2010-04-10 07:37:23 +00003150 // Build the list of bases and members in the order that they'll
3151 // actually be initialized. The explicit initializers should be in
3152 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003153 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003154
Anders Carlsson071d6102010-04-02 03:38:04 +00003155 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3156
John McCalld6ca8da2010-04-10 07:37:23 +00003157 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003158 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003159 ClassDecl->vbases_begin(),
3160 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003161 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003162
John McCalld6ca8da2010-04-10 07:37:23 +00003163 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003164 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003165 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003166 if (Base->isVirtual())
3167 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003168 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003169 }
Mike Stump1eb44332009-09-09 15:08:12 +00003170
John McCalld6ca8da2010-04-10 07:37:23 +00003171 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003172 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003173 E = ClassDecl->field_end(); Field != E; ++Field) {
3174 if (Field->isUnnamedBitfield())
3175 continue;
3176
David Blaikie581deb32012-06-06 20:45:41 +00003177 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003178 }
3179
John McCalld6ca8da2010-04-10 07:37:23 +00003180 unsigned NumIdealInits = IdealInitKeys.size();
3181 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003182
Sean Huntcbb67482011-01-08 20:30:50 +00003183 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003184 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003185 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003186 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003187
3188 // Scan forward to try to find this initializer in the idealized
3189 // initializers list.
3190 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3191 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003192 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003193
3194 // If we didn't find this initializer, it must be because we
3195 // scanned past it on a previous iteration. That can only
3196 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003197 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003198 Sema::SemaDiagnosticBuilder D =
3199 SemaRef.Diag(PrevInit->getSourceLocation(),
3200 diag::warn_initializer_out_of_order);
3201
Francois Pichet00eb3f92010-12-04 09:14:42 +00003202 if (PrevInit->isAnyMemberInitializer())
3203 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003204 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003205 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003206
Francois Pichet00eb3f92010-12-04 09:14:42 +00003207 if (Init->isAnyMemberInitializer())
3208 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003209 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003210 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003211
3212 // Move back to the initializer's location in the ideal list.
3213 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3214 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003215 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003216
3217 assert(IdealIndex != NumIdealInits &&
3218 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003219 }
John McCalld6ca8da2010-04-10 07:37:23 +00003220
3221 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003222 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003223}
3224
John McCall3c3ccdb2010-04-10 09:28:51 +00003225namespace {
3226bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003227 CXXCtorInitializer *Init,
3228 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003229 if (!PrevInit) {
3230 PrevInit = Init;
3231 return false;
3232 }
3233
3234 if (FieldDecl *Field = Init->getMember())
3235 S.Diag(Init->getSourceLocation(),
3236 diag::err_multiple_mem_initialization)
3237 << Field->getDeclName()
3238 << Init->getSourceRange();
3239 else {
John McCallf4c73712011-01-19 06:33:43 +00003240 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003241 assert(BaseClass && "neither field nor base");
3242 S.Diag(Init->getSourceLocation(),
3243 diag::err_multiple_base_initialization)
3244 << QualType(BaseClass, 0)
3245 << Init->getSourceRange();
3246 }
3247 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3248 << 0 << PrevInit->getSourceRange();
3249
3250 return true;
3251}
3252
Sean Huntcbb67482011-01-08 20:30:50 +00003253typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003254typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3255
3256bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003257 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003258 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003259 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003260 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003261 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003262
3263 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003264 if (Parent->isUnion()) {
3265 UnionEntry &En = Unions[Parent];
3266 if (En.first && En.first != Child) {
3267 S.Diag(Init->getSourceLocation(),
3268 diag::err_multiple_mem_union_initialization)
3269 << Field->getDeclName()
3270 << Init->getSourceRange();
3271 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3272 << 0 << En.second->getSourceRange();
3273 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003274 }
3275 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003276 En.first = Child;
3277 En.second = Init;
3278 }
David Blaikie6fe29652011-11-17 06:01:57 +00003279 if (!Parent->isAnonymousStructOrUnion())
3280 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003281 }
3282
3283 Child = Parent;
3284 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003285 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003286
3287 return false;
3288}
3289}
3290
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003291/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003292void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003293 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003294 CXXCtorInitializer **meminits,
3295 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003296 bool AnyErrors) {
3297 if (!ConstructorDecl)
3298 return;
3299
3300 AdjustDeclIfTemplate(ConstructorDecl);
3301
3302 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003303 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003304
3305 if (!Constructor) {
3306 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3307 return;
3308 }
3309
Sean Huntcbb67482011-01-08 20:30:50 +00003310 CXXCtorInitializer **MemInits =
3311 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003312
3313 // Mapping for the duplicate initializers check.
3314 // For member initializers, this is keyed with a FieldDecl*.
3315 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003316 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003317
3318 // Mapping for the inconsistent anonymous-union initializers check.
3319 RedundantUnionMap MemberUnions;
3320
Anders Carlssonea356fb2010-04-02 05:42:15 +00003321 bool HadError = false;
3322 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003323 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003324
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003325 // Set the source order index.
3326 Init->setSourceOrder(i);
3327
Francois Pichet00eb3f92010-12-04 09:14:42 +00003328 if (Init->isAnyMemberInitializer()) {
3329 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003330 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3331 CheckRedundantUnionInit(*this, Init, MemberUnions))
3332 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003333 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003334 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3335 if (CheckRedundantInit(*this, Init, Members[Key]))
3336 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003337 } else {
3338 assert(Init->isDelegatingInitializer());
3339 // This must be the only initializer
3340 if (i != 0 || NumMemInits > 1) {
3341 Diag(MemInits[0]->getSourceLocation(),
3342 diag::err_delegating_initializer_alone)
3343 << MemInits[0]->getSourceRange();
3344 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003345 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003346 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003347 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003348 // Return immediately as the initializer is set.
3349 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003350 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003351 }
3352
Anders Carlssonea356fb2010-04-02 05:42:15 +00003353 if (HadError)
3354 return;
3355
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003356 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003357
Sean Huntcbb67482011-01-08 20:30:50 +00003358 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003359}
3360
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003361void
John McCallef027fe2010-03-16 21:39:52 +00003362Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3363 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003364 // Ignore dependent contexts. Also ignore unions, since their members never
3365 // have destructors implicitly called.
3366 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003367 return;
John McCall58e6f342010-03-16 05:22:47 +00003368
3369 // FIXME: all the access-control diagnostics are positioned on the
3370 // field/base declaration. That's probably good; that said, the
3371 // user might reasonably want to know why the destructor is being
3372 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003373
Anders Carlsson9f853df2009-11-17 04:44:12 +00003374 // Non-static data members.
3375 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3376 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003377 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003378 if (Field->isInvalidDecl())
3379 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003380
3381 // Don't destroy incomplete or zero-length arrays.
3382 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3383 continue;
3384
Anders Carlsson9f853df2009-11-17 04:44:12 +00003385 QualType FieldType = Context.getBaseElementType(Field->getType());
3386
3387 const RecordType* RT = FieldType->getAs<RecordType>();
3388 if (!RT)
3389 continue;
3390
3391 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003392 if (FieldClassDecl->isInvalidDecl())
3393 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003394 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003395 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003396 // The destructor for an implicit anonymous union member is never invoked.
3397 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3398 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003399
Douglas Gregordb89f282010-07-01 22:47:18 +00003400 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003401 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003402 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003403 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003404 << Field->getDeclName()
3405 << FieldType);
3406
Eli Friedman5f2987c2012-02-02 03:46:19 +00003407 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003408 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003409 }
3410
John McCall58e6f342010-03-16 05:22:47 +00003411 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3412
Anders Carlsson9f853df2009-11-17 04:44:12 +00003413 // Bases.
3414 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3415 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003416 // Bases are always records in a well-formed non-dependent class.
3417 const RecordType *RT = Base->getType()->getAs<RecordType>();
3418
3419 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003420 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003421 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003422
John McCall58e6f342010-03-16 05:22:47 +00003423 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003424 // If our base class is invalid, we probably can't get its dtor anyway.
3425 if (BaseClassDecl->isInvalidDecl())
3426 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003427 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003428 continue;
John McCall58e6f342010-03-16 05:22:47 +00003429
Douglas Gregordb89f282010-07-01 22:47:18 +00003430 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003431 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003432
3433 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003434 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003435 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003436 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003437 << Base->getSourceRange(),
3438 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003439
Eli Friedman5f2987c2012-02-02 03:46:19 +00003440 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003441 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003442 }
3443
3444 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003445 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3446 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003447
3448 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003449 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003450
3451 // Ignore direct virtual bases.
3452 if (DirectVirtualBases.count(RT))
3453 continue;
3454
John McCall58e6f342010-03-16 05:22:47 +00003455 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003456 // If our base class is invalid, we probably can't get its dtor anyway.
3457 if (BaseClassDecl->isInvalidDecl())
3458 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003459 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003460 continue;
John McCall58e6f342010-03-16 05:22:47 +00003461
Douglas Gregordb89f282010-07-01 22:47:18 +00003462 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003463 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003464 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003465 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003466 << VBase->getType(),
3467 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003468
Eli Friedman5f2987c2012-02-02 03:46:19 +00003469 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003470 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003471 }
3472}
3473
John McCalld226f652010-08-21 09:40:31 +00003474void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003475 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003476 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003477
Mike Stump1eb44332009-09-09 15:08:12 +00003478 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003479 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003480 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003481}
3482
Mike Stump1eb44332009-09-09 15:08:12 +00003483bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003484 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003485 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3486 unsigned DiagID;
3487 AbstractDiagSelID SelID;
3488
3489 public:
3490 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3491 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3492
3493 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3494 if (SelID == -1)
3495 S.Diag(Loc, DiagID) << T;
3496 else
3497 S.Diag(Loc, DiagID) << SelID << T;
3498 }
3499 } Diagnoser(DiagID, SelID);
3500
3501 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003502}
3503
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003504bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003505 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003506 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003507 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003508
Anders Carlsson11f21a02009-03-23 19:10:31 +00003509 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003510 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003511
Ted Kremenek6217b802009-07-29 21:53:49 +00003512 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003513 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003514 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003515 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003516
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003517 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003518 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003519 }
Mike Stump1eb44332009-09-09 15:08:12 +00003520
Ted Kremenek6217b802009-07-29 21:53:49 +00003521 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003522 if (!RT)
3523 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003524
John McCall86ff3082010-02-04 22:26:26 +00003525 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003526
John McCall94c3b562010-08-18 09:41:07 +00003527 // We can't answer whether something is abstract until it has a
3528 // definition. If it's currently being defined, we'll walk back
3529 // over all the declarations when we have a full definition.
3530 const CXXRecordDecl *Def = RD->getDefinition();
3531 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003532 return false;
3533
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003534 if (!RD->isAbstract())
3535 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003536
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003537 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003538 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003539
John McCall94c3b562010-08-18 09:41:07 +00003540 return true;
3541}
3542
3543void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3544 // Check if we've already emitted the list of pure virtual functions
3545 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003546 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003547 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003548
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003549 CXXFinalOverriderMap FinalOverriders;
3550 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003551
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003552 // Keep a set of seen pure methods so we won't diagnose the same method
3553 // more than once.
3554 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3555
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003556 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3557 MEnd = FinalOverriders.end();
3558 M != MEnd;
3559 ++M) {
3560 for (OverridingMethods::iterator SO = M->second.begin(),
3561 SOEnd = M->second.end();
3562 SO != SOEnd; ++SO) {
3563 // C++ [class.abstract]p4:
3564 // A class is abstract if it contains or inherits at least one
3565 // pure virtual function for which the final overrider is pure
3566 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003567
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003568 //
3569 if (SO->second.size() != 1)
3570 continue;
3571
3572 if (!SO->second.front().Method->isPure())
3573 continue;
3574
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003575 if (!SeenPureMethods.insert(SO->second.front().Method))
3576 continue;
3577
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003578 Diag(SO->second.front().Method->getLocation(),
3579 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003580 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003581 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003582 }
3583
3584 if (!PureVirtualClassDiagSet)
3585 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3586 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003587}
3588
Anders Carlsson8211eff2009-03-24 01:19:16 +00003589namespace {
John McCall94c3b562010-08-18 09:41:07 +00003590struct AbstractUsageInfo {
3591 Sema &S;
3592 CXXRecordDecl *Record;
3593 CanQualType AbstractType;
3594 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003595
John McCall94c3b562010-08-18 09:41:07 +00003596 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3597 : S(S), Record(Record),
3598 AbstractType(S.Context.getCanonicalType(
3599 S.Context.getTypeDeclType(Record))),
3600 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003601
John McCall94c3b562010-08-18 09:41:07 +00003602 void DiagnoseAbstractType() {
3603 if (Invalid) return;
3604 S.DiagnoseAbstractType(Record);
3605 Invalid = true;
3606 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003607
John McCall94c3b562010-08-18 09:41:07 +00003608 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3609};
3610
3611struct CheckAbstractUsage {
3612 AbstractUsageInfo &Info;
3613 const NamedDecl *Ctx;
3614
3615 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3616 : Info(Info), Ctx(Ctx) {}
3617
3618 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3619 switch (TL.getTypeLocClass()) {
3620#define ABSTRACT_TYPELOC(CLASS, PARENT)
3621#define TYPELOC(CLASS, PARENT) \
3622 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3623#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003624 }
John McCall94c3b562010-08-18 09:41:07 +00003625 }
Mike Stump1eb44332009-09-09 15:08:12 +00003626
John McCall94c3b562010-08-18 09:41:07 +00003627 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3628 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3629 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003630 if (!TL.getArg(I))
3631 continue;
3632
John McCall94c3b562010-08-18 09:41:07 +00003633 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3634 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003635 }
John McCall94c3b562010-08-18 09:41:07 +00003636 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003637
John McCall94c3b562010-08-18 09:41:07 +00003638 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3639 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3640 }
Mike Stump1eb44332009-09-09 15:08:12 +00003641
John McCall94c3b562010-08-18 09:41:07 +00003642 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3643 // Visit the type parameters from a permissive context.
3644 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3645 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3646 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3647 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3648 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3649 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003650 }
John McCall94c3b562010-08-18 09:41:07 +00003651 }
Mike Stump1eb44332009-09-09 15:08:12 +00003652
John McCall94c3b562010-08-18 09:41:07 +00003653 // Visit pointee types from a permissive context.
3654#define CheckPolymorphic(Type) \
3655 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3656 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3657 }
3658 CheckPolymorphic(PointerTypeLoc)
3659 CheckPolymorphic(ReferenceTypeLoc)
3660 CheckPolymorphic(MemberPointerTypeLoc)
3661 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003662 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003663
John McCall94c3b562010-08-18 09:41:07 +00003664 /// Handle all the types we haven't given a more specific
3665 /// implementation for above.
3666 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3667 // Every other kind of type that we haven't called out already
3668 // that has an inner type is either (1) sugar or (2) contains that
3669 // inner type in some way as a subobject.
3670 if (TypeLoc Next = TL.getNextTypeLoc())
3671 return Visit(Next, Sel);
3672
3673 // If there's no inner type and we're in a permissive context,
3674 // don't diagnose.
3675 if (Sel == Sema::AbstractNone) return;
3676
3677 // Check whether the type matches the abstract type.
3678 QualType T = TL.getType();
3679 if (T->isArrayType()) {
3680 Sel = Sema::AbstractArrayType;
3681 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003682 }
John McCall94c3b562010-08-18 09:41:07 +00003683 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3684 if (CT != Info.AbstractType) return;
3685
3686 // It matched; do some magic.
3687 if (Sel == Sema::AbstractArrayType) {
3688 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3689 << T << TL.getSourceRange();
3690 } else {
3691 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3692 << Sel << T << TL.getSourceRange();
3693 }
3694 Info.DiagnoseAbstractType();
3695 }
3696};
3697
3698void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3699 Sema::AbstractDiagSelID Sel) {
3700 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3701}
3702
3703}
3704
3705/// Check for invalid uses of an abstract type in a method declaration.
3706static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3707 CXXMethodDecl *MD) {
3708 // No need to do the check on definitions, which require that
3709 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003710 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003711 return;
3712
3713 // For safety's sake, just ignore it if we don't have type source
3714 // information. This should never happen for non-implicit methods,
3715 // but...
3716 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3717 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3718}
3719
3720/// Check for invalid uses of an abstract type within a class definition.
3721static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3722 CXXRecordDecl *RD) {
3723 for (CXXRecordDecl::decl_iterator
3724 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3725 Decl *D = *I;
3726 if (D->isImplicit()) continue;
3727
3728 // Methods and method templates.
3729 if (isa<CXXMethodDecl>(D)) {
3730 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3731 } else if (isa<FunctionTemplateDecl>(D)) {
3732 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3733 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3734
3735 // Fields and static variables.
3736 } else if (isa<FieldDecl>(D)) {
3737 FieldDecl *FD = cast<FieldDecl>(D);
3738 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3739 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3740 } else if (isa<VarDecl>(D)) {
3741 VarDecl *VD = cast<VarDecl>(D);
3742 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3743 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3744
3745 // Nested classes and class templates.
3746 } else if (isa<CXXRecordDecl>(D)) {
3747 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3748 } else if (isa<ClassTemplateDecl>(D)) {
3749 CheckAbstractClassUsage(Info,
3750 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3751 }
3752 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003753}
3754
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003755/// \brief Perform semantic checks on a class definition that has been
3756/// completing, introducing implicitly-declared members, checking for
3757/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003758void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003759 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003760 return;
3761
John McCall94c3b562010-08-18 09:41:07 +00003762 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3763 AbstractUsageInfo Info(*this, Record);
3764 CheckAbstractClassUsage(Info, Record);
3765 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003766
3767 // If this is not an aggregate type and has no user-declared constructor,
3768 // complain about any non-static data members of reference or const scalar
3769 // type, since they will never get initializers.
3770 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003771 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3772 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003773 bool Complained = false;
3774 for (RecordDecl::field_iterator F = Record->field_begin(),
3775 FEnd = Record->field_end();
3776 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003777 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003778 continue;
3779
Douglas Gregor325e5932010-04-15 00:00:53 +00003780 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003781 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003782 if (!Complained) {
3783 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3784 << Record->getTagKind() << Record;
3785 Complained = true;
3786 }
3787
3788 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3789 << F->getType()->isReferenceType()
3790 << F->getDeclName();
3791 }
3792 }
3793 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003794
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003795 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003796 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003797
3798 if (Record->getIdentifier()) {
3799 // C++ [class.mem]p13:
3800 // If T is the name of a class, then each of the following shall have a
3801 // name different from T:
3802 // - every member of every anonymous union that is a member of class T.
3803 //
3804 // C++ [class.mem]p14:
3805 // In addition, if class T has a user-declared constructor (12.1), every
3806 // non-static data member of class T shall have a name different from T.
3807 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003808 R.first != R.second; ++R.first) {
3809 NamedDecl *D = *R.first;
3810 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3811 isa<IndirectFieldDecl>(D)) {
3812 Diag(D->getLocation(), diag::err_member_name_of_class)
3813 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003814 break;
3815 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003816 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003817 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003818
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003819 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003820 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003821 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003822 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003823 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3824 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3825 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003826
3827 // See if a method overloads virtual methods in a base
3828 /// class without overriding any.
3829 if (!Record->isDependentType()) {
3830 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3831 MEnd = Record->method_end();
3832 M != MEnd; ++M) {
David Blaikie262bc182012-04-30 02:36:29 +00003833 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003834 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003835 }
3836 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003837
Richard Smith9f569cc2011-10-01 02:31:28 +00003838 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3839 // function that is not a constructor declares that member function to be
3840 // const. [...] The class of which that function is a member shall be
3841 // a literal type.
3842 //
Richard Smith9f569cc2011-10-01 02:31:28 +00003843 // If the class has virtual bases, any constexpr members will already have
3844 // been diagnosed by the checks performed on the member declaration, so
3845 // suppress this (less useful) diagnostic.
3846 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3847 !Record->isLiteral() && !Record->getNumVBases()) {
3848 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3849 MEnd = Record->method_end();
3850 M != MEnd; ++M) {
Richard Smith86c3ae42012-02-13 03:54:03 +00003851 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003852 switch (Record->getTemplateSpecializationKind()) {
3853 case TSK_ImplicitInstantiation:
3854 case TSK_ExplicitInstantiationDeclaration:
3855 case TSK_ExplicitInstantiationDefinition:
3856 // If a template instantiates to a non-literal type, but its members
3857 // instantiate to constexpr functions, the template is technically
Richard Smith86c3ae42012-02-13 03:54:03 +00003858 // ill-formed, but we allow it for sanity.
Richard Smith9f569cc2011-10-01 02:31:28 +00003859 continue;
3860
3861 case TSK_Undeclared:
3862 case TSK_ExplicitSpecialization:
David Blaikie262bc182012-04-30 02:36:29 +00003863 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
Douglas Gregorf502d8e2012-05-04 16:48:41 +00003864 diag::err_constexpr_method_non_literal);
Richard Smith9f569cc2011-10-01 02:31:28 +00003865 break;
3866 }
3867
3868 // Only produce one error per class.
3869 break;
3870 }
3871 }
3872 }
3873
Sebastian Redlf677ea32011-02-05 19:23:19 +00003874 // Declare inherited constructors. We do this eagerly here because:
3875 // - The standard requires an eager diagnostic for conflicting inherited
3876 // constructors from different classes.
3877 // - The lazy declaration of the other implicit constructors is so as to not
3878 // waste space and performance on classes that are not meant to be
3879 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3880 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003881 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003882
Sean Hunteb88ae52011-05-23 21:07:59 +00003883 if (!Record->isDependentType())
3884 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003885}
3886
3887void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003888 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3889 ME = Record->method_end();
Richard Smith3003e1d2012-05-15 04:39:51 +00003890 MI != ME; ++MI)
3891 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
David Blaikie581deb32012-06-06 20:45:41 +00003892 CheckExplicitlyDefaultedSpecialMember(*MI);
Sean Hunt001cad92011-05-10 00:49:42 +00003893}
3894
Richard Smith7756afa2012-06-10 05:43:50 +00003895/// Is the special member function which would be selected to perform the
3896/// specified operation on the specified class type a constexpr constructor?
3897static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3898 Sema::CXXSpecialMember CSM,
3899 bool ConstArg) {
3900 Sema::SpecialMemberOverloadResult *SMOR =
3901 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
3902 false, false, false, false);
3903 if (!SMOR || !SMOR->getMethod())
3904 // A constructor we wouldn't select can't be "involved in initializing"
3905 // anything.
3906 return true;
3907 return SMOR->getMethod()->isConstexpr();
3908}
3909
3910/// Determine whether the specified special member function would be constexpr
3911/// if it were implicitly defined.
3912static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3913 Sema::CXXSpecialMember CSM,
3914 bool ConstArg) {
3915 if (!S.getLangOpts().CPlusPlus0x)
3916 return false;
3917
3918 // C++11 [dcl.constexpr]p4:
3919 // In the definition of a constexpr constructor [...]
3920 switch (CSM) {
3921 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00003922 // Since default constructor lookup is essentially trivial (and cannot
3923 // involve, for instance, template instantiation), we compute whether a
3924 // defaulted default constructor is constexpr directly within CXXRecordDecl.
3925 //
3926 // This is important for performance; we need to know whether the default
3927 // constructor is constexpr to determine whether the type is a literal type.
3928 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
3929
Richard Smith7756afa2012-06-10 05:43:50 +00003930 case Sema::CXXCopyConstructor:
3931 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00003932 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00003933 break;
3934
3935 case Sema::CXXCopyAssignment:
3936 case Sema::CXXMoveAssignment:
3937 case Sema::CXXDestructor:
3938 case Sema::CXXInvalid:
3939 return false;
3940 }
3941
3942 // -- if the class is a non-empty union, or for each non-empty anonymous
3943 // union member of a non-union class, exactly one non-static data member
3944 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00003945 //
3946 // If we squint, this is guaranteed, since exactly one non-static data member
3947 // will be initialized (if the constructor isn't deleted), we just don't know
3948 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00003949 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00003950 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00003951
3952 // -- the class shall not have any virtual base classes;
3953 if (ClassDecl->getNumVBases())
3954 return false;
3955
3956 // -- every constructor involved in initializing [...] base class
3957 // sub-objects shall be a constexpr constructor;
3958 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
3959 BEnd = ClassDecl->bases_end();
3960 B != BEnd; ++B) {
3961 const RecordType *BaseType = B->getType()->getAs<RecordType>();
3962 if (!BaseType) continue;
3963
3964 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
3965 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
3966 return false;
3967 }
3968
3969 // -- every constructor involved in initializing non-static data members
3970 // [...] shall be a constexpr constructor;
3971 // -- every non-static data member and base class sub-object shall be
3972 // initialized
3973 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
3974 FEnd = ClassDecl->field_end();
3975 F != FEnd; ++F) {
3976 if (F->isInvalidDecl())
3977 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00003978 if (const RecordType *RecordTy =
3979 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00003980 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
3981 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
3982 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00003983 }
3984 }
3985
3986 // All OK, it's constexpr!
3987 return true;
3988}
3989
Richard Smith3003e1d2012-05-15 04:39:51 +00003990void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
3991 CXXRecordDecl *RD = MD->getParent();
3992 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00003993
Richard Smith3003e1d2012-05-15 04:39:51 +00003994 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
3995 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00003996
3997 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00003998 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00003999 bool First = MD == MD->getCanonicalDecl();
4000
4001 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004002
4003 // C++11 [dcl.fct.def.default]p1:
4004 // A function that is explicitly defaulted shall
4005 // -- be a special member function (checked elsewhere),
4006 // -- have the same type (except for ref-qualifiers, and except that a
4007 // copy operation can take a non-const reference) as an implicit
4008 // declaration, and
4009 // -- not have default arguments.
4010 unsigned ExpectedParams = 1;
4011 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4012 ExpectedParams = 0;
4013 if (MD->getNumParams() != ExpectedParams) {
4014 // This also checks for default arguments: a copy or move constructor with a
4015 // default argument is classified as a default constructor, and assignment
4016 // operations and destructors can't have default arguments.
4017 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4018 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004019 HadError = true;
4020 }
4021
Richard Smith3003e1d2012-05-15 04:39:51 +00004022 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004023
Richard Smith3003e1d2012-05-15 04:39:51 +00004024 // Compute implicit exception specification, argument constness, constexpr
4025 // and triviality.
Richard Smithe6975e92012-04-17 00:58:00 +00004026 ImplicitExceptionSpecification Spec(*this);
Richard Smith7756afa2012-06-10 05:43:50 +00004027 bool CanHaveConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004028 bool Trivial;
4029 switch (CSM) {
4030 case CXXDefaultConstructor:
4031 Spec = ComputeDefaultedDefaultCtorExceptionSpec(RD);
4032 if (Spec.isDelayed())
4033 // Exception specification depends on some deferred part of the class.
4034 // We'll try again when the class's definition has been fully processed.
4035 return;
Richard Smith3003e1d2012-05-15 04:39:51 +00004036 Trivial = RD->hasTrivialDefaultConstructor();
4037 break;
4038 case CXXCopyConstructor:
Richard Smith7756afa2012-06-10 05:43:50 +00004039 llvm::tie(Spec, CanHaveConstParam) =
Richard Smith3003e1d2012-05-15 04:39:51 +00004040 ComputeDefaultedCopyCtorExceptionSpecAndConst(RD);
Richard Smith3003e1d2012-05-15 04:39:51 +00004041 Trivial = RD->hasTrivialCopyConstructor();
4042 break;
4043 case CXXCopyAssignment:
Richard Smith7756afa2012-06-10 05:43:50 +00004044 llvm::tie(Spec, CanHaveConstParam) =
Richard Smith3003e1d2012-05-15 04:39:51 +00004045 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(RD);
4046 Trivial = RD->hasTrivialCopyAssignment();
4047 break;
4048 case CXXMoveConstructor:
4049 Spec = ComputeDefaultedMoveCtorExceptionSpec(RD);
Richard Smith3003e1d2012-05-15 04:39:51 +00004050 Trivial = RD->hasTrivialMoveConstructor();
4051 break;
4052 case CXXMoveAssignment:
4053 Spec = ComputeDefaultedMoveAssignmentExceptionSpec(RD);
4054 Trivial = RD->hasTrivialMoveAssignment();
4055 break;
4056 case CXXDestructor:
4057 Spec = ComputeDefaultedDtorExceptionSpec(RD);
4058 Trivial = RD->hasTrivialDestructor();
4059 break;
4060 case CXXInvalid:
4061 llvm_unreachable("non-special member explicitly defaulted!");
4062 }
Sean Hunt2b188082011-05-14 05:23:28 +00004063
Richard Smith3003e1d2012-05-15 04:39:51 +00004064 QualType ReturnType = Context.VoidTy;
4065 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4066 // Check for return type matching.
4067 ReturnType = Type->getResultType();
4068 QualType ExpectedReturnType =
4069 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4070 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4071 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4072 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4073 HadError = true;
4074 }
4075
4076 // A defaulted special member cannot have cv-qualifiers.
4077 if (Type->getTypeQuals()) {
4078 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4079 << (CSM == CXXMoveAssignment);
4080 HadError = true;
4081 }
4082 }
4083
4084 // Check for parameter type matching.
4085 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004086 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004087 if (ExpectedParams && ArgType->isReferenceType()) {
4088 // Argument must be reference to possibly-const T.
4089 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004090 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004091
4092 if (ReferentType.isVolatileQualified()) {
4093 Diag(MD->getLocation(),
4094 diag::err_defaulted_special_member_volatile_param) << CSM;
4095 HadError = true;
4096 }
4097
Richard Smith7756afa2012-06-10 05:43:50 +00004098 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004099 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4100 Diag(MD->getLocation(),
4101 diag::err_defaulted_special_member_copy_const_param)
4102 << (CSM == CXXCopyAssignment);
4103 // FIXME: Explain why this special member can't be const.
4104 } else {
4105 Diag(MD->getLocation(),
4106 diag::err_defaulted_special_member_move_const_param)
4107 << (CSM == CXXMoveAssignment);
4108 }
4109 HadError = true;
4110 }
4111
4112 // If a function is explicitly defaulted on its first declaration, it shall
4113 // have the same parameter type as if it had been implicitly declared.
4114 // (Presumably this is to prevent it from being trivial?)
Richard Smith7756afa2012-06-10 05:43:50 +00004115 if (!HasConstParam && CanHaveConstParam && First)
Richard Smith3003e1d2012-05-15 04:39:51 +00004116 Diag(MD->getLocation(),
4117 diag::err_defaulted_special_member_copy_non_const_param)
4118 << (CSM == CXXCopyAssignment);
4119 } else if (ExpectedParams) {
4120 // A copy assignment operator can take its argument by value, but a
4121 // defaulted one cannot.
4122 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004123 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004124 HadError = true;
4125 }
Sean Huntbe631222011-05-17 20:44:43 +00004126
Richard Smith3003e1d2012-05-15 04:39:51 +00004127 // Rebuild the type with the implicit exception specification added.
4128 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4129 Spec.getEPI(EPI);
4130 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4131 Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004132
Richard Smith61802452011-12-22 02:22:31 +00004133 // C++11 [dcl.fct.def.default]p2:
4134 // An explicitly-defaulted function may be declared constexpr only if it
4135 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004136 // Do not apply this rule to members of class templates, since core issue 1358
4137 // makes such functions always instantiate to constexpr functions. For
4138 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004139 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4140 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004141 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4142 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4143 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004144 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004145 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004146 }
4147 // and may have an explicit exception-specification only if it is compatible
4148 // with the exception-specification on the implicit declaration.
Richard Smith3003e1d2012-05-15 04:39:51 +00004149 if (Type->hasExceptionSpec() &&
4150 CheckEquivalentExceptionSpec(
4151 PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
4152 PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
4153 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004154
4155 // If a function is explicitly defaulted on its first declaration,
4156 if (First) {
4157 // -- it is implicitly considered to be constexpr if the implicit
4158 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004159 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004160
Richard Smith3003e1d2012-05-15 04:39:51 +00004161 // -- it is implicitly considered to have the same exception-specification
4162 // as if it had been implicitly declared,
4163 MD->setType(QualType(ImplicitType, 0));
Richard Smithe653ba22012-02-26 00:31:33 +00004164
4165 // Such a function is also trivial if the implicitly-declared function
4166 // would have been.
Richard Smith3003e1d2012-05-15 04:39:51 +00004167 MD->setTrivial(Trivial);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004168 }
4169
Richard Smith3003e1d2012-05-15 04:39:51 +00004170 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004171 if (First) {
4172 MD->setDeletedAsWritten();
4173 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004174 // C++11 [dcl.fct.def.default]p4:
4175 // [For a] user-provided explicitly-defaulted function [...] if such a
4176 // function is implicitly defined as deleted, the program is ill-formed.
4177 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4178 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004179 }
4180 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004181
Richard Smith3003e1d2012-05-15 04:39:51 +00004182 if (HadError)
4183 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004184}
4185
Richard Smith7d5088a2012-02-18 02:02:13 +00004186namespace {
4187struct SpecialMemberDeletionInfo {
4188 Sema &S;
4189 CXXMethodDecl *MD;
4190 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004191 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004192
4193 // Properties of the special member, computed for convenience.
4194 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4195 SourceLocation Loc;
4196
4197 bool AllFieldsAreConst;
4198
4199 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004200 Sema::CXXSpecialMember CSM, bool Diagnose)
4201 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004202 IsConstructor(false), IsAssignment(false), IsMove(false),
4203 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4204 AllFieldsAreConst(true) {
4205 switch (CSM) {
4206 case Sema::CXXDefaultConstructor:
4207 case Sema::CXXCopyConstructor:
4208 IsConstructor = true;
4209 break;
4210 case Sema::CXXMoveConstructor:
4211 IsConstructor = true;
4212 IsMove = true;
4213 break;
4214 case Sema::CXXCopyAssignment:
4215 IsAssignment = true;
4216 break;
4217 case Sema::CXXMoveAssignment:
4218 IsAssignment = true;
4219 IsMove = true;
4220 break;
4221 case Sema::CXXDestructor:
4222 break;
4223 case Sema::CXXInvalid:
4224 llvm_unreachable("invalid special member kind");
4225 }
4226
4227 if (MD->getNumParams()) {
4228 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4229 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4230 }
4231 }
4232
4233 bool inUnion() const { return MD->getParent()->isUnion(); }
4234
4235 /// Look up the corresponding special member in the given class.
4236 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class) {
4237 unsigned TQ = MD->getTypeQualifiers();
4238 return S.LookupSpecialMember(Class, CSM, ConstArg, VolatileArg,
4239 MD->getRefQualifier() == RQ_RValue,
4240 TQ & Qualifiers::Const,
4241 TQ & Qualifiers::Volatile);
4242 }
4243
Richard Smith6c4c36c2012-03-30 20:53:28 +00004244 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004245
Richard Smith6c4c36c2012-03-30 20:53:28 +00004246 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004247 bool shouldDeleteForField(FieldDecl *FD);
4248 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004249
4250 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj);
4251 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4252 Sema::SpecialMemberOverloadResult *SMOR,
4253 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004254
4255 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004256};
4257}
4258
John McCall12d8d802012-04-09 20:53:23 +00004259/// Is the given special member inaccessible when used on the given
4260/// sub-object.
4261bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4262 CXXMethodDecl *target) {
4263 /// If we're operating on a base class, the object type is the
4264 /// type of this special member.
4265 QualType objectTy;
4266 AccessSpecifier access = target->getAccess();;
4267 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4268 objectTy = S.Context.getTypeDeclType(MD->getParent());
4269 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4270
4271 // If we're operating on a field, the object type is the type of the field.
4272 } else {
4273 objectTy = S.Context.getTypeDeclType(target->getParent());
4274 }
4275
4276 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4277}
4278
Richard Smith6c4c36c2012-03-30 20:53:28 +00004279/// Check whether we should delete a special member due to the implicit
4280/// definition containing a call to a special member of a subobject.
4281bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4282 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4283 bool IsDtorCallInCtor) {
4284 CXXMethodDecl *Decl = SMOR->getMethod();
4285 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4286
4287 int DiagKind = -1;
4288
4289 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4290 DiagKind = !Decl ? 0 : 1;
4291 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4292 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004293 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004294 DiagKind = 3;
4295 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4296 !Decl->isTrivial()) {
4297 // A member of a union must have a trivial corresponding special member.
4298 // As a weird special case, a destructor call from a union's constructor
4299 // must be accessible and non-deleted, but need not be trivial. Such a
4300 // destructor is never actually called, but is semantically checked as
4301 // if it were.
4302 DiagKind = 4;
4303 }
4304
4305 if (DiagKind == -1)
4306 return false;
4307
4308 if (Diagnose) {
4309 if (Field) {
4310 S.Diag(Field->getLocation(),
4311 diag::note_deleted_special_member_class_subobject)
4312 << CSM << MD->getParent() << /*IsField*/true
4313 << Field << DiagKind << IsDtorCallInCtor;
4314 } else {
4315 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4316 S.Diag(Base->getLocStart(),
4317 diag::note_deleted_special_member_class_subobject)
4318 << CSM << MD->getParent() << /*IsField*/false
4319 << Base->getType() << DiagKind << IsDtorCallInCtor;
4320 }
4321
4322 if (DiagKind == 1)
4323 S.NoteDeletedFunction(Decl);
4324 // FIXME: Explain inaccessibility if DiagKind == 3.
4325 }
4326
4327 return true;
4328}
4329
Richard Smith9a561d52012-02-26 09:11:52 +00004330/// Check whether we should delete a special member function due to having a
4331/// direct or virtual base class or static data member of class type M.
4332bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith6c4c36c2012-03-30 20:53:28 +00004333 CXXRecordDecl *Class, Subobject Subobj) {
4334 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004335
4336 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004337 // -- any direct or virtual base class, or non-static data member with no
4338 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004339 // either M has no default constructor or overload resolution as applied
4340 // to M's default constructor results in an ambiguity or in a function
4341 // that is deleted or inaccessible
4342 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4343 // -- a direct or virtual base class B that cannot be copied/moved because
4344 // overload resolution, as applied to B's corresponding special member,
4345 // results in an ambiguity or a function that is deleted or inaccessible
4346 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004347 // C++11 [class.dtor]p5:
4348 // -- any direct or virtual base class [...] has a type with a destructor
4349 // that is deleted or inaccessible
4350 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004351 Field && Field->hasInClassInitializer()) &&
4352 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class), false))
4353 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004354
Richard Smith6c4c36c2012-03-30 20:53:28 +00004355 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4356 // -- any direct or virtual base class or non-static data member has a
4357 // type with a destructor that is deleted or inaccessible
4358 if (IsConstructor) {
4359 Sema::SpecialMemberOverloadResult *SMOR =
4360 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4361 false, false, false, false, false);
4362 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4363 return true;
4364 }
4365
Richard Smith9a561d52012-02-26 09:11:52 +00004366 return false;
4367}
4368
4369/// Check whether we should delete a special member function due to the class
4370/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004371bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004372 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4373 return shouldDeleteForClassSubobject(BaseClass, Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004374}
4375
4376/// Check whether we should delete a special member function due to the class
4377/// having a particular non-static data member.
4378bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4379 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4380 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4381
4382 if (CSM == Sema::CXXDefaultConstructor) {
4383 // For a default constructor, all references must be initialized in-class
4384 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004385 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4386 if (Diagnose)
4387 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4388 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004389 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004390 }
Richard Smith79363f52012-02-27 06:07:25 +00004391 // C++11 [class.ctor]p5: any non-variant non-static data member of
4392 // const-qualified type (or array thereof) with no
4393 // brace-or-equal-initializer does not have a user-provided default
4394 // constructor.
4395 if (!inUnion() && FieldType.isConstQualified() &&
4396 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004397 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4398 if (Diagnose)
4399 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004400 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004401 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004402 }
4403
4404 if (inUnion() && !FieldType.isConstQualified())
4405 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004406 } else if (CSM == Sema::CXXCopyConstructor) {
4407 // For a copy constructor, data members must not be of rvalue reference
4408 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004409 if (FieldType->isRValueReferenceType()) {
4410 if (Diagnose)
4411 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4412 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004413 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004414 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004415 } else if (IsAssignment) {
4416 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004417 if (FieldType->isReferenceType()) {
4418 if (Diagnose)
4419 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4420 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004421 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004422 }
4423 if (!FieldRecord && FieldType.isConstQualified()) {
4424 // C++11 [class.copy]p23:
4425 // -- a non-static data member of const non-class type (or array thereof)
4426 if (Diagnose)
4427 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004428 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004429 return true;
4430 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004431 }
4432
4433 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004434 // Some additional restrictions exist on the variant members.
4435 if (!inUnion() && FieldRecord->isUnion() &&
4436 FieldRecord->isAnonymousStructOrUnion()) {
4437 bool AllVariantFieldsAreConst = true;
4438
Richard Smithdf8dc862012-03-29 19:00:10 +00004439 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004440 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4441 UE = FieldRecord->field_end();
4442 UI != UE; ++UI) {
4443 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004444
4445 if (!UnionFieldType.isConstQualified())
4446 AllVariantFieldsAreConst = false;
4447
Richard Smith9a561d52012-02-26 09:11:52 +00004448 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4449 if (UnionFieldRecord &&
David Blaikie581deb32012-06-06 20:45:41 +00004450 shouldDeleteForClassSubobject(UnionFieldRecord, *UI))
Richard Smith9a561d52012-02-26 09:11:52 +00004451 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004452 }
4453
4454 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004455 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004456 FieldRecord->field_begin() != FieldRecord->field_end()) {
4457 if (Diagnose)
4458 S.Diag(FieldRecord->getLocation(),
4459 diag::note_deleted_default_ctor_all_const)
4460 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004461 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004462 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004463
Richard Smithdf8dc862012-03-29 19:00:10 +00004464 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004465 // This is technically non-conformant, but sanity demands it.
4466 return false;
4467 }
4468
Richard Smithdf8dc862012-03-29 19:00:10 +00004469 if (shouldDeleteForClassSubobject(FieldRecord, FD))
4470 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004471 }
4472
4473 return false;
4474}
4475
4476/// C++11 [class.ctor] p5:
4477/// A defaulted default constructor for a class X is defined as deleted if
4478/// X is a union and all of its variant members are of const-qualified type.
4479bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004480 // This is a silly definition, because it gives an empty union a deleted
4481 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004482 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4483 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4484 if (Diagnose)
4485 S.Diag(MD->getParent()->getLocation(),
4486 diag::note_deleted_default_ctor_all_const)
4487 << MD->getParent() << /*not anonymous union*/0;
4488 return true;
4489 }
4490 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004491}
4492
4493/// Determine whether a defaulted special member function should be defined as
4494/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4495/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004496bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4497 bool Diagnose) {
Sean Hunte16da072011-10-10 06:18:57 +00004498 assert(!MD->isInvalidDecl());
4499 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004500 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004501 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004502 return false;
4503
Richard Smith7d5088a2012-02-18 02:02:13 +00004504 // C++11 [expr.lambda.prim]p19:
4505 // The closure type associated with a lambda-expression has a
4506 // deleted (8.4.3) default constructor and a deleted copy
4507 // assignment operator.
4508 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004509 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4510 if (Diagnose)
4511 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004512 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004513 }
4514
Richard Smith5bdaac52012-04-02 20:59:25 +00004515 // For an anonymous struct or union, the copy and assignment special members
4516 // will never be used, so skip the check. For an anonymous union declared at
4517 // namespace scope, the constructor and destructor are used.
4518 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4519 RD->isAnonymousStructOrUnion())
4520 return false;
4521
Richard Smith6c4c36c2012-03-30 20:53:28 +00004522 // C++11 [class.copy]p7, p18:
4523 // If the class definition declares a move constructor or move assignment
4524 // operator, an implicitly declared copy constructor or copy assignment
4525 // operator is defined as deleted.
4526 if (MD->isImplicit() &&
4527 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4528 CXXMethodDecl *UserDeclaredMove = 0;
4529
4530 // In Microsoft mode, a user-declared move only causes the deletion of the
4531 // corresponding copy operation, not both copy operations.
4532 if (RD->hasUserDeclaredMoveConstructor() &&
4533 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4534 if (!Diagnose) return true;
4535 UserDeclaredMove = RD->getMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00004536 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004537 } else if (RD->hasUserDeclaredMoveAssignment() &&
4538 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4539 if (!Diagnose) return true;
4540 UserDeclaredMove = RD->getMoveAssignmentOperator();
Richard Smith1c931be2012-04-02 18:40:40 +00004541 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004542 }
4543
4544 if (UserDeclaredMove) {
4545 Diag(UserDeclaredMove->getLocation(),
4546 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004547 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004548 << UserDeclaredMove->isMoveAssignmentOperator();
4549 return true;
4550 }
4551 }
Sean Hunte16da072011-10-10 06:18:57 +00004552
Richard Smith5bdaac52012-04-02 20:59:25 +00004553 // Do access control from the special member function
4554 ContextRAII MethodContext(*this, MD);
4555
Richard Smith9a561d52012-02-26 09:11:52 +00004556 // C++11 [class.dtor]p5:
4557 // -- for a virtual destructor, lookup of the non-array deallocation function
4558 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004559 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004560 FunctionDecl *OperatorDelete = 0;
4561 DeclarationName Name =
4562 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4563 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004564 OperatorDelete, false)) {
4565 if (Diagnose)
4566 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004567 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004568 }
Richard Smith9a561d52012-02-26 09:11:52 +00004569 }
4570
Richard Smith6c4c36c2012-03-30 20:53:28 +00004571 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004572
Sean Huntcdee3fe2011-05-11 22:34:38 +00004573 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004574 BE = RD->bases_end(); BI != BE; ++BI)
4575 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004576 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004577 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004578
4579 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004580 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004581 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004582 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004583
4584 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004585 FE = RD->field_end(); FI != FE; ++FI)
4586 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004587 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004588 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004589
Richard Smith7d5088a2012-02-18 02:02:13 +00004590 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004591 return true;
4592
4593 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004594}
4595
4596/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004597namespace {
4598 struct FindHiddenVirtualMethodData {
4599 Sema *S;
4600 CXXMethodDecl *Method;
4601 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004602 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004603 };
4604}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004605
4606/// \brief Member lookup function that determines whether a given C++
4607/// method overloads virtual methods in a base class without overriding any,
4608/// to be used with CXXRecordDecl::lookupInBases().
4609static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4610 CXXBasePath &Path,
4611 void *UserData) {
4612 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4613
4614 FindHiddenVirtualMethodData &Data
4615 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4616
4617 DeclarationName Name = Data.Method->getDeclName();
4618 assert(Name.getNameKind() == DeclarationName::Identifier);
4619
4620 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004621 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004622 for (Path.Decls = BaseRecord->lookup(Name);
4623 Path.Decls.first != Path.Decls.second;
4624 ++Path.Decls.first) {
4625 NamedDecl *D = *Path.Decls.first;
4626 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004627 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004628 foundSameNameMethod = true;
4629 // Interested only in hidden virtual methods.
4630 if (!MD->isVirtual())
4631 continue;
4632 // If the method we are checking overrides a method from its base
4633 // don't warn about the other overloaded methods.
4634 if (!Data.S->IsOverload(Data.Method, MD, false))
4635 return true;
4636 // Collect the overload only if its hidden.
4637 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4638 overloadedMethods.push_back(MD);
4639 }
4640 }
4641
4642 if (foundSameNameMethod)
4643 Data.OverloadedMethods.append(overloadedMethods.begin(),
4644 overloadedMethods.end());
4645 return foundSameNameMethod;
4646}
4647
4648/// \brief See if a method overloads virtual methods in a base class without
4649/// overriding any.
4650void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4651 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004652 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004653 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00004654 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004655 return;
4656
4657 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4658 /*bool RecordPaths=*/false,
4659 /*bool DetectVirtual=*/false);
4660 FindHiddenVirtualMethodData Data;
4661 Data.Method = MD;
4662 Data.S = this;
4663
4664 // Keep the base methods that were overriden or introduced in the subclass
4665 // by 'using' in a set. A base method not in this set is hidden.
4666 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4667 res.first != res.second; ++res.first) {
4668 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4669 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4670 E = MD->end_overridden_methods();
4671 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004672 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004673 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4674 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004675 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004676 }
4677
4678 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4679 !Data.OverloadedMethods.empty()) {
4680 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4681 << MD << (Data.OverloadedMethods.size() > 1);
4682
4683 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4684 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4685 Diag(overloadedMD->getLocation(),
4686 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4687 }
4688 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004689}
4690
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004691void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004692 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004693 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004694 SourceLocation RBrac,
4695 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004696 if (!TagDecl)
4697 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004698
Douglas Gregor42af25f2009-05-11 19:58:34 +00004699 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004700
David Blaikie77b6de02011-09-22 02:58:26 +00004701 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00004702 // strict aliasing violation!
4703 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00004704 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004705
Douglas Gregor23c94db2010-07-02 17:43:08 +00004706 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004707 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004708}
4709
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004710/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4711/// special functions, such as the default constructor, copy
4712/// constructor, or destructor, to the given C++ class (C++
4713/// [special]p1). This routine can only be executed just before the
4714/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004715void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004716 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004717 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004718
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004719 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004720 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004721
David Blaikie4e4d0842012-03-11 07:00:24 +00004722 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
Richard Smithb701d3d2011-12-24 21:56:24 +00004723 ++ASTContext::NumImplicitMoveConstructors;
4724
Douglas Gregora376d102010-07-02 21:50:04 +00004725 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4726 ++ASTContext::NumImplicitCopyAssignmentOperators;
4727
4728 // If we have a dynamic class, then the copy assignment operator may be
4729 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4730 // it shows up in the right place in the vtable and that we diagnose
4731 // problems with the implicit exception specification.
4732 if (ClassDecl->isDynamicClass())
4733 DeclareImplicitCopyAssignment(ClassDecl);
4734 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004735
Richard Smith1c931be2012-04-02 18:40:40 +00004736 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00004737 ++ASTContext::NumImplicitMoveAssignmentOperators;
4738
4739 // Likewise for the move assignment operator.
4740 if (ClassDecl->isDynamicClass())
4741 DeclareImplicitMoveAssignment(ClassDecl);
4742 }
4743
Douglas Gregor4923aa22010-07-02 20:37:36 +00004744 if (!ClassDecl->hasUserDeclaredDestructor()) {
4745 ++ASTContext::NumImplicitDestructors;
4746
4747 // If we have a dynamic class, then the destructor may be virtual, so we
4748 // have to declare the destructor immediately. This ensures that, e.g., it
4749 // shows up in the right place in the vtable and that we diagnose problems
4750 // with the implicit exception specification.
4751 if (ClassDecl->isDynamicClass())
4752 DeclareImplicitDestructor(ClassDecl);
4753 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004754}
4755
Francois Pichet8387e2a2011-04-22 22:18:13 +00004756void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4757 if (!D)
4758 return;
4759
4760 int NumParamList = D->getNumTemplateParameterLists();
4761 for (int i = 0; i < NumParamList; i++) {
4762 TemplateParameterList* Params = D->getTemplateParameterList(i);
4763 for (TemplateParameterList::iterator Param = Params->begin(),
4764 ParamEnd = Params->end();
4765 Param != ParamEnd; ++Param) {
4766 NamedDecl *Named = cast<NamedDecl>(*Param);
4767 if (Named->getDeclName()) {
4768 S->AddDecl(Named);
4769 IdResolver.AddDecl(Named);
4770 }
4771 }
4772 }
4773}
4774
John McCalld226f652010-08-21 09:40:31 +00004775void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004776 if (!D)
4777 return;
4778
4779 TemplateParameterList *Params = 0;
4780 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4781 Params = Template->getTemplateParameters();
4782 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4783 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4784 Params = PartialSpec->getTemplateParameters();
4785 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004786 return;
4787
Douglas Gregor6569d682009-05-27 23:11:45 +00004788 for (TemplateParameterList::iterator Param = Params->begin(),
4789 ParamEnd = Params->end();
4790 Param != ParamEnd; ++Param) {
4791 NamedDecl *Named = cast<NamedDecl>(*Param);
4792 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004793 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004794 IdResolver.AddDecl(Named);
4795 }
4796 }
4797}
4798
John McCalld226f652010-08-21 09:40:31 +00004799void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004800 if (!RecordD) return;
4801 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004802 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004803 PushDeclContext(S, Record);
4804}
4805
John McCalld226f652010-08-21 09:40:31 +00004806void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004807 if (!RecordD) return;
4808 PopDeclContext();
4809}
4810
Douglas Gregor72b505b2008-12-16 21:30:33 +00004811/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4812/// parsing a top-level (non-nested) C++ class, and we are now
4813/// parsing those parts of the given Method declaration that could
4814/// not be parsed earlier (C++ [class.mem]p2), such as default
4815/// arguments. This action should enter the scope of the given
4816/// Method declaration as if we had just parsed the qualified method
4817/// name. However, it should not bring the parameters into scope;
4818/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004819void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004820}
4821
4822/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4823/// C++ method declaration. We're (re-)introducing the given
4824/// function parameter into scope for use in parsing later parts of
4825/// the method declaration. For example, we could see an
4826/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004827void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004828 if (!ParamD)
4829 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004830
John McCalld226f652010-08-21 09:40:31 +00004831 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004832
4833 // If this parameter has an unparsed default argument, clear it out
4834 // to make way for the parsed default argument.
4835 if (Param->hasUnparsedDefaultArg())
4836 Param->setDefaultArg(0);
4837
John McCalld226f652010-08-21 09:40:31 +00004838 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004839 if (Param->getDeclName())
4840 IdResolver.AddDecl(Param);
4841}
4842
4843/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4844/// processing the delayed method declaration for Method. The method
4845/// declaration is now considered finished. There may be a separate
4846/// ActOnStartOfFunctionDef action later (not necessarily
4847/// immediately!) for this method, if it was also defined inside the
4848/// class body.
John McCalld226f652010-08-21 09:40:31 +00004849void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004850 if (!MethodD)
4851 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004852
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004853 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004854
John McCalld226f652010-08-21 09:40:31 +00004855 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004856
4857 // Now that we have our default arguments, check the constructor
4858 // again. It could produce additional diagnostics or affect whether
4859 // the class has implicitly-declared destructors, among other
4860 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004861 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4862 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004863
4864 // Check the default arguments, which we may have added.
4865 if (!Method->isInvalidDecl())
4866 CheckCXXDefaultArguments(Method);
4867}
4868
Douglas Gregor42a552f2008-11-05 20:51:48 +00004869/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004870/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004871/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004872/// emit diagnostics and set the invalid bit to true. In any case, the type
4873/// will be updated to reflect a well-formed type for the constructor and
4874/// returned.
4875QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004876 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004877 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004878
4879 // C++ [class.ctor]p3:
4880 // A constructor shall not be virtual (10.3) or static (9.4). A
4881 // constructor can be invoked for a const, volatile or const
4882 // volatile object. A constructor shall not be declared const,
4883 // volatile, or const volatile (9.3.2).
4884 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004885 if (!D.isInvalidType())
4886 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4887 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4888 << SourceRange(D.getIdentifierLoc());
4889 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004890 }
John McCalld931b082010-08-26 03:08:43 +00004891 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004892 if (!D.isInvalidType())
4893 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4894 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4895 << SourceRange(D.getIdentifierLoc());
4896 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004897 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004898 }
Mike Stump1eb44332009-09-09 15:08:12 +00004899
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004900 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004901 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004902 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004903 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4904 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004905 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004906 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4907 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004908 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004909 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4910 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004911 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004912 }
Mike Stump1eb44332009-09-09 15:08:12 +00004913
Douglas Gregorc938c162011-01-26 05:01:58 +00004914 // C++0x [class.ctor]p4:
4915 // A constructor shall not be declared with a ref-qualifier.
4916 if (FTI.hasRefQualifier()) {
4917 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4918 << FTI.RefQualifierIsLValueRef
4919 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4920 D.setInvalidType();
4921 }
4922
Douglas Gregor42a552f2008-11-05 20:51:48 +00004923 // Rebuild the function type "R" without any type qualifiers (in
4924 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004925 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004926 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004927 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4928 return R;
4929
4930 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4931 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004932 EPI.RefQualifier = RQ_None;
4933
Chris Lattner65401802009-04-25 08:28:21 +00004934 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004935 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004936}
4937
Douglas Gregor72b505b2008-12-16 21:30:33 +00004938/// CheckConstructor - Checks a fully-formed constructor for
4939/// well-formedness, issuing any diagnostics required. Returns true if
4940/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004941void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004942 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004943 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4944 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004945 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004946
4947 // C++ [class.copy]p3:
4948 // A declaration of a constructor for a class X is ill-formed if
4949 // its first parameter is of type (optionally cv-qualified) X and
4950 // either there are no other parameters or else all other
4951 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00004952 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004953 ((Constructor->getNumParams() == 1) ||
4954 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00004955 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4956 Constructor->getTemplateSpecializationKind()
4957 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004958 QualType ParamType = Constructor->getParamDecl(0)->getType();
4959 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4960 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00004961 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004962 const char *ConstRef
4963 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4964 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00004965 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004966 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00004967
4968 // FIXME: Rather that making the constructor invalid, we should endeavor
4969 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00004970 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004971 }
4972 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00004973}
4974
John McCall15442822010-08-04 01:04:25 +00004975/// CheckDestructor - Checks a fully-formed destructor definition for
4976/// well-formedness, issuing any diagnostics required. Returns true
4977/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004978bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00004979 CXXRecordDecl *RD = Destructor->getParent();
4980
4981 if (Destructor->isVirtual()) {
4982 SourceLocation Loc;
4983
4984 if (!Destructor->isImplicit())
4985 Loc = Destructor->getLocation();
4986 else
4987 Loc = RD->getLocation();
4988
4989 // If we have a virtual destructor, look up the deallocation function
4990 FunctionDecl *OperatorDelete = 0;
4991 DeclarationName Name =
4992 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004993 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00004994 return true;
John McCall5efd91a2010-07-03 18:33:00 +00004995
Eli Friedman5f2987c2012-02-02 03:46:19 +00004996 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00004997
4998 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00004999 }
Anders Carlsson37909802009-11-30 21:24:50 +00005000
5001 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005002}
5003
Mike Stump1eb44332009-09-09 15:08:12 +00005004static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005005FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5006 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5007 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005008 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005009}
5010
Douglas Gregor42a552f2008-11-05 20:51:48 +00005011/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5012/// the well-formednes of the destructor declarator @p D with type @p
5013/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005014/// emit diagnostics and set the declarator to invalid. Even if this happens,
5015/// will be updated to reflect a well-formed type for the destructor and
5016/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005017QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005018 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005019 // C++ [class.dtor]p1:
5020 // [...] A typedef-name that names a class is a class-name
5021 // (7.1.3); however, a typedef-name that names a class shall not
5022 // be used as the identifier in the declarator for a destructor
5023 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005024 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005025 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005026 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005027 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005028 else if (const TemplateSpecializationType *TST =
5029 DeclaratorType->getAs<TemplateSpecializationType>())
5030 if (TST->isTypeAlias())
5031 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5032 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005033
5034 // C++ [class.dtor]p2:
5035 // A destructor is used to destroy objects of its class type. A
5036 // destructor takes no parameters, and no return type can be
5037 // specified for it (not even void). The address of a destructor
5038 // shall not be taken. A destructor shall not be static. A
5039 // destructor can be invoked for a const, volatile or const
5040 // volatile object. A destructor shall not be declared const,
5041 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005042 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005043 if (!D.isInvalidType())
5044 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5045 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005046 << SourceRange(D.getIdentifierLoc())
5047 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5048
John McCalld931b082010-08-26 03:08:43 +00005049 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005050 }
Chris Lattner65401802009-04-25 08:28:21 +00005051 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005052 // Destructors don't have return types, but the parser will
5053 // happily parse something like:
5054 //
5055 // class X {
5056 // float ~X();
5057 // };
5058 //
5059 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005060 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5061 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5062 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005063 }
Mike Stump1eb44332009-09-09 15:08:12 +00005064
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005065 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005066 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005067 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005068 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5069 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005070 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005071 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5072 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005073 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005074 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5075 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005076 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005077 }
5078
Douglas Gregorc938c162011-01-26 05:01:58 +00005079 // C++0x [class.dtor]p2:
5080 // A destructor shall not be declared with a ref-qualifier.
5081 if (FTI.hasRefQualifier()) {
5082 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5083 << FTI.RefQualifierIsLValueRef
5084 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5085 D.setInvalidType();
5086 }
5087
Douglas Gregor42a552f2008-11-05 20:51:48 +00005088 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005089 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005090 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5091
5092 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005093 FTI.freeArgs();
5094 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005095 }
5096
Mike Stump1eb44332009-09-09 15:08:12 +00005097 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005098 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005099 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005100 D.setInvalidType();
5101 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005102
5103 // Rebuild the function type "R" without any type qualifiers or
5104 // parameters (in case any of the errors above fired) and with
5105 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005106 // types.
John McCalle23cf432010-12-14 08:05:40 +00005107 if (!D.isInvalidType())
5108 return R;
5109
Douglas Gregord92ec472010-07-01 05:10:53 +00005110 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005111 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5112 EPI.Variadic = false;
5113 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005114 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005115 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005116}
5117
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005118/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5119/// well-formednes of the conversion function declarator @p D with
5120/// type @p R. If there are any errors in the declarator, this routine
5121/// will emit diagnostics and return true. Otherwise, it will return
5122/// false. Either way, the type @p R will be updated to reflect a
5123/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005124void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005125 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005126 // C++ [class.conv.fct]p1:
5127 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005128 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005129 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005130 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005131 if (!D.isInvalidType())
5132 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5133 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5134 << SourceRange(D.getIdentifierLoc());
5135 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005136 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005137 }
John McCalla3f81372010-04-13 00:04:31 +00005138
5139 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5140
Chris Lattner6e475012009-04-25 08:35:12 +00005141 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005142 // Conversion functions don't have return types, but the parser will
5143 // happily parse something like:
5144 //
5145 // class X {
5146 // float operator bool();
5147 // };
5148 //
5149 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005150 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5151 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5152 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005153 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005154 }
5155
John McCalla3f81372010-04-13 00:04:31 +00005156 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5157
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005158 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005159 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005160 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5161
5162 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005163 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005164 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005165 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005166 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005167 D.setInvalidType();
5168 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005169
John McCalla3f81372010-04-13 00:04:31 +00005170 // Diagnose "&operator bool()" and other such nonsense. This
5171 // is actually a gcc extension which we don't support.
5172 if (Proto->getResultType() != ConvType) {
5173 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5174 << Proto->getResultType();
5175 D.setInvalidType();
5176 ConvType = Proto->getResultType();
5177 }
5178
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005179 // C++ [class.conv.fct]p4:
5180 // The conversion-type-id shall not represent a function type nor
5181 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005182 if (ConvType->isArrayType()) {
5183 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5184 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005185 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005186 } else if (ConvType->isFunctionType()) {
5187 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5188 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005189 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005190 }
5191
5192 // Rebuild the function type "R" without any parameters (in case any
5193 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005194 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005195 if (D.isInvalidType())
5196 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005197
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005198 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005199 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005200 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005201 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005202 diag::warn_cxx98_compat_explicit_conversion_functions :
5203 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005204 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005205}
5206
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005207/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5208/// the declaration of the given C++ conversion function. This routine
5209/// is responsible for recording the conversion function in the C++
5210/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005211Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005212 assert(Conversion && "Expected to receive a conversion function declaration");
5213
Douglas Gregor9d350972008-12-12 08:25:50 +00005214 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005215
5216 // Make sure we aren't redeclaring the conversion function.
5217 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005218
5219 // C++ [class.conv.fct]p1:
5220 // [...] A conversion function is never used to convert a
5221 // (possibly cv-qualified) object to the (possibly cv-qualified)
5222 // same object type (or a reference to it), to a (possibly
5223 // cv-qualified) base class of that type (or a reference to it),
5224 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005225 // FIXME: Suppress this warning if the conversion function ends up being a
5226 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005227 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005228 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005229 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005230 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005231 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5232 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005233 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005234 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005235 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5236 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005237 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005238 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005239 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005240 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005241 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005242 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005243 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005244 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005245 }
5246
Douglas Gregore80622f2010-09-29 04:25:11 +00005247 if (FunctionTemplateDecl *ConversionTemplate
5248 = Conversion->getDescribedFunctionTemplate())
5249 return ConversionTemplate;
5250
John McCalld226f652010-08-21 09:40:31 +00005251 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005252}
5253
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005254//===----------------------------------------------------------------------===//
5255// Namespace Handling
5256//===----------------------------------------------------------------------===//
5257
John McCallea318642010-08-26 09:15:37 +00005258
5259
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005260/// ActOnStartNamespaceDef - This is called at the start of a namespace
5261/// definition.
John McCalld226f652010-08-21 09:40:31 +00005262Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005263 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005264 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005265 SourceLocation IdentLoc,
5266 IdentifierInfo *II,
5267 SourceLocation LBrace,
5268 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005269 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5270 // For anonymous namespace, take the location of the left brace.
5271 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005272 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005273 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005274 bool IsStd = false;
5275 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005276 Scope *DeclRegionScope = NamespcScope->getParent();
5277
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005278 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005279 if (II) {
5280 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005281 // The identifier in an original-namespace-definition shall not
5282 // have been previously defined in the declarative region in
5283 // which the original-namespace-definition appears. The
5284 // identifier in an original-namespace-definition is the name of
5285 // the namespace. Subsequently in that declarative region, it is
5286 // treated as an original-namespace-name.
5287 //
5288 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005289 // look through using directives, just look for any ordinary names.
5290
5291 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005292 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5293 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005294 NamedDecl *PrevDecl = 0;
5295 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005296 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005297 R.first != R.second; ++R.first) {
5298 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5299 PrevDecl = *R.first;
5300 break;
5301 }
5302 }
5303
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005304 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5305
5306 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005307 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005308 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005309 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005310 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005311 // The user probably just forgot the 'inline', so suggest that it
5312 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005313 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005314 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5315 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005316 Diag(Loc, diag::err_inline_namespace_mismatch)
5317 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005318 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005319 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5320
5321 IsInline = PrevNS->isInline();
5322 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005323 } else if (PrevDecl) {
5324 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005325 Diag(Loc, diag::err_redefinition_different_kind)
5326 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005327 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005328 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005329 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005330 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005331 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005332 // This is the first "real" definition of the namespace "std", so update
5333 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005334 PrevNS = getStdNamespace();
5335 IsStd = true;
5336 AddToKnown = !IsInline;
5337 } else {
5338 // We've seen this namespace for the first time.
5339 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005340 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005341 } else {
John McCall9aeed322009-10-01 00:25:31 +00005342 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005343
5344 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005345 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005346 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005347 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005348 } else {
5349 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005350 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005351 }
5352
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005353 if (PrevNS && IsInline != PrevNS->isInline()) {
5354 // inline-ness must match
5355 Diag(Loc, diag::err_inline_namespace_mismatch)
5356 << IsInline;
5357 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005358
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005359 // Recover by ignoring the new namespace's inline status.
5360 IsInline = PrevNS->isInline();
5361 }
5362 }
5363
5364 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5365 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005366 if (IsInvalid)
5367 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005368
5369 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005370
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005371 // FIXME: Should we be merging attributes?
5372 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005373 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005374
5375 if (IsStd)
5376 StdNamespace = Namespc;
5377 if (AddToKnown)
5378 KnownNamespaces[Namespc] = false;
5379
5380 if (II) {
5381 PushOnScopeChains(Namespc, DeclRegionScope);
5382 } else {
5383 // Link the anonymous namespace into its parent.
5384 DeclContext *Parent = CurContext->getRedeclContext();
5385 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5386 TU->setAnonymousNamespace(Namespc);
5387 } else {
5388 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005389 }
John McCall9aeed322009-10-01 00:25:31 +00005390
Douglas Gregora4181472010-03-24 00:46:35 +00005391 CurContext->addDecl(Namespc);
5392
John McCall9aeed322009-10-01 00:25:31 +00005393 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5394 // behaves as if it were replaced by
5395 // namespace unique { /* empty body */ }
5396 // using namespace unique;
5397 // namespace unique { namespace-body }
5398 // where all occurrences of 'unique' in a translation unit are
5399 // replaced by the same identifier and this identifier differs
5400 // from all other identifiers in the entire program.
5401
5402 // We just create the namespace with an empty name and then add an
5403 // implicit using declaration, just like the standard suggests.
5404 //
5405 // CodeGen enforces the "universally unique" aspect by giving all
5406 // declarations semantically contained within an anonymous
5407 // namespace internal linkage.
5408
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005409 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005410 UsingDirectiveDecl* UD
5411 = UsingDirectiveDecl::Create(Context, CurContext,
5412 /* 'using' */ LBrace,
5413 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005414 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005415 /* identifier */ SourceLocation(),
5416 Namespc,
5417 /* Ancestor */ CurContext);
5418 UD->setImplicit();
5419 CurContext->addDecl(UD);
5420 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005421 }
5422
5423 // Although we could have an invalid decl (i.e. the namespace name is a
5424 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005425 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5426 // for the namespace has the declarations that showed up in that particular
5427 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005428 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005429 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005430}
5431
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005432/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5433/// is a namespace alias, returns the namespace it points to.
5434static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5435 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5436 return AD->getNamespace();
5437 return dyn_cast_or_null<NamespaceDecl>(D);
5438}
5439
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005440/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5441/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005442void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005443 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5444 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005445 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005446 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005447 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005448 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005449}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005450
John McCall384aff82010-08-25 07:42:41 +00005451CXXRecordDecl *Sema::getStdBadAlloc() const {
5452 return cast_or_null<CXXRecordDecl>(
5453 StdBadAlloc.get(Context.getExternalSource()));
5454}
5455
5456NamespaceDecl *Sema::getStdNamespace() const {
5457 return cast_or_null<NamespaceDecl>(
5458 StdNamespace.get(Context.getExternalSource()));
5459}
5460
Douglas Gregor66992202010-06-29 17:53:46 +00005461/// \brief Retrieve the special "std" namespace, which may require us to
5462/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005463NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005464 if (!StdNamespace) {
5465 // The "std" namespace has not yet been defined, so build one implicitly.
5466 StdNamespace = NamespaceDecl::Create(Context,
5467 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005468 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005469 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005470 &PP.getIdentifierTable().get("std"),
5471 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005472 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005473 }
5474
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005475 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005476}
5477
Sebastian Redl395e04d2012-01-17 22:49:33 +00005478bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005479 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00005480 "Looking for std::initializer_list outside of C++.");
5481
5482 // We're looking for implicit instantiations of
5483 // template <typename E> class std::initializer_list.
5484
5485 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5486 return false;
5487
Sebastian Redl84760e32012-01-17 22:49:58 +00005488 ClassTemplateDecl *Template = 0;
5489 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005490
Sebastian Redl84760e32012-01-17 22:49:58 +00005491 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005492
Sebastian Redl84760e32012-01-17 22:49:58 +00005493 ClassTemplateSpecializationDecl *Specialization =
5494 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5495 if (!Specialization)
5496 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005497
Sebastian Redl84760e32012-01-17 22:49:58 +00005498 Template = Specialization->getSpecializedTemplate();
5499 Arguments = Specialization->getTemplateArgs().data();
5500 } else if (const TemplateSpecializationType *TST =
5501 Ty->getAs<TemplateSpecializationType>()) {
5502 Template = dyn_cast_or_null<ClassTemplateDecl>(
5503 TST->getTemplateName().getAsTemplateDecl());
5504 Arguments = TST->getArgs();
5505 }
5506 if (!Template)
5507 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005508
5509 if (!StdInitializerList) {
5510 // Haven't recognized std::initializer_list yet, maybe this is it.
5511 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5512 if (TemplateClass->getIdentifier() !=
5513 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005514 !getStdNamespace()->InEnclosingNamespaceSetOf(
5515 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005516 return false;
5517 // This is a template called std::initializer_list, but is it the right
5518 // template?
5519 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005520 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005521 return false;
5522 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5523 return false;
5524
5525 // It's the right template.
5526 StdInitializerList = Template;
5527 }
5528
5529 if (Template != StdInitializerList)
5530 return false;
5531
5532 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005533 if (Element)
5534 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005535 return true;
5536}
5537
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005538static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5539 NamespaceDecl *Std = S.getStdNamespace();
5540 if (!Std) {
5541 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5542 return 0;
5543 }
5544
5545 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5546 Loc, Sema::LookupOrdinaryName);
5547 if (!S.LookupQualifiedName(Result, Std)) {
5548 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5549 return 0;
5550 }
5551 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5552 if (!Template) {
5553 Result.suppressDiagnostics();
5554 // We found something weird. Complain about the first thing we found.
5555 NamedDecl *Found = *Result.begin();
5556 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5557 return 0;
5558 }
5559
5560 // We found some template called std::initializer_list. Now verify that it's
5561 // correct.
5562 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005563 if (Params->getMinRequiredArguments() != 1 ||
5564 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005565 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5566 return 0;
5567 }
5568
5569 return Template;
5570}
5571
5572QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5573 if (!StdInitializerList) {
5574 StdInitializerList = LookupStdInitializerList(*this, Loc);
5575 if (!StdInitializerList)
5576 return QualType();
5577 }
5578
5579 TemplateArgumentListInfo Args(Loc, Loc);
5580 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5581 Context.getTrivialTypeSourceInfo(Element,
5582 Loc)));
5583 return Context.getCanonicalType(
5584 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5585}
5586
Sebastian Redl98d36062012-01-17 22:50:14 +00005587bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5588 // C++ [dcl.init.list]p2:
5589 // A constructor is an initializer-list constructor if its first parameter
5590 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5591 // std::initializer_list<E> for some type E, and either there are no other
5592 // parameters or else all other parameters have default arguments.
5593 if (Ctor->getNumParams() < 1 ||
5594 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5595 return false;
5596
5597 QualType ArgType = Ctor->getParamDecl(0)->getType();
5598 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5599 ArgType = RT->getPointeeType().getUnqualifiedType();
5600
5601 return isStdInitializerList(ArgType, 0);
5602}
5603
Douglas Gregor9172aa62011-03-26 22:25:30 +00005604/// \brief Determine whether a using statement is in a context where it will be
5605/// apply in all contexts.
5606static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5607 switch (CurContext->getDeclKind()) {
5608 case Decl::TranslationUnit:
5609 return true;
5610 case Decl::LinkageSpec:
5611 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5612 default:
5613 return false;
5614 }
5615}
5616
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005617namespace {
5618
5619// Callback to only accept typo corrections that are namespaces.
5620class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5621 public:
5622 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5623 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5624 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5625 }
5626 return false;
5627 }
5628};
5629
5630}
5631
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005632static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5633 CXXScopeSpec &SS,
5634 SourceLocation IdentLoc,
5635 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005636 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005637 R.clear();
5638 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005639 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005640 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005641 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5642 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005643 if (DeclContext *DC = S.computeDeclContext(SS, false))
5644 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5645 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5646 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5647 else
5648 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5649 << Ident << CorrectedQuotedStr
5650 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005651
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005652 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5653 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005654
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005655 R.addDecl(Corrected.getCorrectionDecl());
5656 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005657 }
5658 return false;
5659}
5660
John McCalld226f652010-08-21 09:40:31 +00005661Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005662 SourceLocation UsingLoc,
5663 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005664 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005665 SourceLocation IdentLoc,
5666 IdentifierInfo *NamespcName,
5667 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005668 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5669 assert(NamespcName && "Invalid NamespcName.");
5670 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005671
5672 // This can only happen along a recovery path.
5673 while (S->getFlags() & Scope::TemplateParamScope)
5674 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005675 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005676
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005677 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005678 NestedNameSpecifier *Qualifier = 0;
5679 if (SS.isSet())
5680 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5681
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005682 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005683 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5684 LookupParsedName(R, S, &SS);
5685 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005686 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005687
Douglas Gregor66992202010-06-29 17:53:46 +00005688 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005689 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005690 // Allow "using namespace std;" or "using namespace ::std;" even if
5691 // "std" hasn't been defined yet, for GCC compatibility.
5692 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5693 NamespcName->isStr("std")) {
5694 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005695 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005696 R.resolveKind();
5697 }
5698 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005699 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005700 }
5701
John McCallf36e02d2009-10-09 21:13:30 +00005702 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005703 NamedDecl *Named = R.getFoundDecl();
5704 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5705 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005706 // C++ [namespace.udir]p1:
5707 // A using-directive specifies that the names in the nominated
5708 // namespace can be used in the scope in which the
5709 // using-directive appears after the using-directive. During
5710 // unqualified name lookup (3.4.1), the names appear as if they
5711 // were declared in the nearest enclosing namespace which
5712 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005713 // namespace. [Note: in this context, "contains" means "contains
5714 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005715
5716 // Find enclosing context containing both using-directive and
5717 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005718 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005719 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5720 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5721 CommonAncestor = CommonAncestor->getParent();
5722
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005723 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005724 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005725 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005726
Douglas Gregor9172aa62011-03-26 22:25:30 +00005727 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005728 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005729 Diag(IdentLoc, diag::warn_using_directive_in_header);
5730 }
5731
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005732 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005733 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005734 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005735 }
5736
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005737 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005738 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005739}
5740
5741void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005742 // If the scope has an associated entity and the using directive is at
5743 // namespace or translation unit scope, add the UsingDirectiveDecl into
5744 // its lookup structure so qualified name lookup can find it.
5745 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5746 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005747 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005748 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005749 // Otherwise, it is at block sope. The using-directives will affect lookup
5750 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00005751 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005752}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005753
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005754
John McCalld226f652010-08-21 09:40:31 +00005755Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005756 AccessSpecifier AS,
5757 bool HasUsingKeyword,
5758 SourceLocation UsingLoc,
5759 CXXScopeSpec &SS,
5760 UnqualifiedId &Name,
5761 AttributeList *AttrList,
5762 bool IsTypeName,
5763 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005764 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005765
Douglas Gregor12c118a2009-11-04 16:30:06 +00005766 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005767 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005768 case UnqualifiedId::IK_Identifier:
5769 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005770 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005771 case UnqualifiedId::IK_ConversionFunctionId:
5772 break;
5773
5774 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005775 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00005776 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00005777 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005778 getLangOpts().CPlusPlus0x ?
Richard Smitha1366cb2012-04-27 19:33:05 +00005779 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
5780 // instead once inheriting constructors work.
5781 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00005782 diag::err_using_decl_constructor)
5783 << SS.getRange();
5784
David Blaikie4e4d0842012-03-11 07:00:24 +00005785 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00005786
John McCalld226f652010-08-21 09:40:31 +00005787 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005788
5789 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005790 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005791 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005792 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005793
5794 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005795 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005796 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005797 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005798 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005799
5800 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5801 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005802 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005803 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005804
John McCall60fa3cf2009-12-11 02:10:03 +00005805 // Warn about using declarations.
5806 // TODO: store that the declaration was written without 'using' and
5807 // talk about access decls instead of using decls in the
5808 // diagnostics.
5809 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005810 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00005811
5812 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005813 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005814 }
5815
Douglas Gregor56c04582010-12-16 00:46:58 +00005816 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5817 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5818 return 0;
5819
John McCall9488ea12009-11-17 05:59:44 +00005820 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005821 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005822 /* IsInstantiation */ false,
5823 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005824 if (UD)
5825 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005826
John McCalld226f652010-08-21 09:40:31 +00005827 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005828}
5829
Douglas Gregor09acc982010-07-07 23:08:52 +00005830/// \brief Determine whether a using declaration considers the given
5831/// declarations as "equivalent", e.g., if they are redeclarations of
5832/// the same entity or are both typedefs of the same type.
5833static bool
5834IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5835 bool &SuppressRedeclaration) {
5836 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5837 SuppressRedeclaration = false;
5838 return true;
5839 }
5840
Richard Smith162e1c12011-04-15 14:24:37 +00005841 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5842 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005843 SuppressRedeclaration = true;
5844 return Context.hasSameType(TD1->getUnderlyingType(),
5845 TD2->getUnderlyingType());
5846 }
5847
5848 return false;
5849}
5850
5851
John McCall9f54ad42009-12-10 09:41:52 +00005852/// Determines whether to create a using shadow decl for a particular
5853/// decl, given the set of decls existing prior to this using lookup.
5854bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5855 const LookupResult &Previous) {
5856 // Diagnose finding a decl which is not from a base class of the
5857 // current class. We do this now because there are cases where this
5858 // function will silently decide not to build a shadow decl, which
5859 // will pre-empt further diagnostics.
5860 //
5861 // We don't need to do this in C++0x because we do the check once on
5862 // the qualifier.
5863 //
5864 // FIXME: diagnose the following if we care enough:
5865 // struct A { int foo; };
5866 // struct B : A { using A::foo; };
5867 // template <class T> struct C : A {};
5868 // template <class T> struct D : C<T> { using B::foo; } // <---
5869 // This is invalid (during instantiation) in C++03 because B::foo
5870 // resolves to the using decl in B, which is not a base class of D<T>.
5871 // We can't diagnose it immediately because C<T> is an unknown
5872 // specialization. The UsingShadowDecl in D<T> then points directly
5873 // to A::foo, which will look well-formed when we instantiate.
5874 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00005875 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00005876 DeclContext *OrigDC = Orig->getDeclContext();
5877
5878 // Handle enums and anonymous structs.
5879 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5880 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5881 while (OrigRec->isAnonymousStructOrUnion())
5882 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5883
5884 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5885 if (OrigDC == CurContext) {
5886 Diag(Using->getLocation(),
5887 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005888 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005889 Diag(Orig->getLocation(), diag::note_using_decl_target);
5890 return true;
5891 }
5892
Douglas Gregordc355712011-02-25 00:36:19 +00005893 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005894 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005895 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005896 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005897 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005898 Diag(Orig->getLocation(), diag::note_using_decl_target);
5899 return true;
5900 }
5901 }
5902
5903 if (Previous.empty()) return false;
5904
5905 NamedDecl *Target = Orig;
5906 if (isa<UsingShadowDecl>(Target))
5907 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5908
John McCalld7533ec2009-12-11 02:33:26 +00005909 // If the target happens to be one of the previous declarations, we
5910 // don't have a conflict.
5911 //
5912 // FIXME: but we might be increasing its access, in which case we
5913 // should redeclare it.
5914 NamedDecl *NonTag = 0, *Tag = 0;
5915 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5916 I != E; ++I) {
5917 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005918 bool Result;
5919 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5920 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005921
5922 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5923 }
5924
John McCall9f54ad42009-12-10 09:41:52 +00005925 if (Target->isFunctionOrFunctionTemplate()) {
5926 FunctionDecl *FD;
5927 if (isa<FunctionTemplateDecl>(Target))
5928 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5929 else
5930 FD = cast<FunctionDecl>(Target);
5931
5932 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005933 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005934 case Ovl_Overload:
5935 return false;
5936
5937 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005938 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005939 break;
5940
5941 // We found a decl with the exact signature.
5942 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005943 // If we're in a record, we want to hide the target, so we
5944 // return true (without a diagnostic) to tell the caller not to
5945 // build a shadow decl.
5946 if (CurContext->isRecord())
5947 return true;
5948
5949 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00005950 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005951 break;
5952 }
5953
5954 Diag(Target->getLocation(), diag::note_using_decl_target);
5955 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5956 return true;
5957 }
5958
5959 // Target is not a function.
5960
John McCall9f54ad42009-12-10 09:41:52 +00005961 if (isa<TagDecl>(Target)) {
5962 // No conflict between a tag and a non-tag.
5963 if (!Tag) return false;
5964
John McCall41ce66f2009-12-10 19:51:03 +00005965 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005966 Diag(Target->getLocation(), diag::note_using_decl_target);
5967 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5968 return true;
5969 }
5970
5971 // No conflict between a tag and a non-tag.
5972 if (!NonTag) return false;
5973
John McCall41ce66f2009-12-10 19:51:03 +00005974 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005975 Diag(Target->getLocation(), diag::note_using_decl_target);
5976 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5977 return true;
5978}
5979
John McCall9488ea12009-11-17 05:59:44 +00005980/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00005981UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00005982 UsingDecl *UD,
5983 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00005984
5985 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00005986 NamedDecl *Target = Orig;
5987 if (isa<UsingShadowDecl>(Target)) {
5988 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5989 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00005990 }
5991
5992 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00005993 = UsingShadowDecl::Create(Context, CurContext,
5994 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00005995 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00005996
5997 Shadow->setAccess(UD->getAccess());
5998 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5999 Shadow->setInvalidDecl();
6000
John McCall9488ea12009-11-17 05:59:44 +00006001 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006002 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006003 else
John McCall604e7f12009-12-08 07:46:18 +00006004 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006005
John McCall604e7f12009-12-08 07:46:18 +00006006
John McCall9f54ad42009-12-10 09:41:52 +00006007 return Shadow;
6008}
John McCall604e7f12009-12-08 07:46:18 +00006009
John McCall9f54ad42009-12-10 09:41:52 +00006010/// Hides a using shadow declaration. This is required by the current
6011/// using-decl implementation when a resolvable using declaration in a
6012/// class is followed by a declaration which would hide or override
6013/// one or more of the using decl's targets; for example:
6014///
6015/// struct Base { void foo(int); };
6016/// struct Derived : Base {
6017/// using Base::foo;
6018/// void foo(int);
6019/// };
6020///
6021/// The governing language is C++03 [namespace.udecl]p12:
6022///
6023/// When a using-declaration brings names from a base class into a
6024/// derived class scope, member functions in the derived class
6025/// override and/or hide member functions with the same name and
6026/// parameter types in a base class (rather than conflicting).
6027///
6028/// There are two ways to implement this:
6029/// (1) optimistically create shadow decls when they're not hidden
6030/// by existing declarations, or
6031/// (2) don't create any shadow decls (or at least don't make them
6032/// visible) until we've fully parsed/instantiated the class.
6033/// The problem with (1) is that we might have to retroactively remove
6034/// a shadow decl, which requires several O(n) operations because the
6035/// decl structures are (very reasonably) not designed for removal.
6036/// (2) avoids this but is very fiddly and phase-dependent.
6037void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006038 if (Shadow->getDeclName().getNameKind() ==
6039 DeclarationName::CXXConversionFunctionName)
6040 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6041
John McCall9f54ad42009-12-10 09:41:52 +00006042 // Remove it from the DeclContext...
6043 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006044
John McCall9f54ad42009-12-10 09:41:52 +00006045 // ...and the scope, if applicable...
6046 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006047 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006048 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006049 }
6050
John McCall9f54ad42009-12-10 09:41:52 +00006051 // ...and the using decl.
6052 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6053
6054 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006055 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006056}
6057
John McCall7ba107a2009-11-18 02:36:19 +00006058/// Builds a using declaration.
6059///
6060/// \param IsInstantiation - Whether this call arises from an
6061/// instantiation of an unresolved using declaration. We treat
6062/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006063NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6064 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006065 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006066 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006067 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006068 bool IsInstantiation,
6069 bool IsTypeName,
6070 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006071 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006072 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006073 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006074
Anders Carlsson550b14b2009-08-28 05:49:21 +00006075 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006076
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006077 if (SS.isEmpty()) {
6078 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006079 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006080 }
Mike Stump1eb44332009-09-09 15:08:12 +00006081
John McCall9f54ad42009-12-10 09:41:52 +00006082 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006083 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006084 ForRedeclaration);
6085 Previous.setHideTags(false);
6086 if (S) {
6087 LookupName(Previous, S);
6088
6089 // It is really dumb that we have to do this.
6090 LookupResult::Filter F = Previous.makeFilter();
6091 while (F.hasNext()) {
6092 NamedDecl *D = F.next();
6093 if (!isDeclInScope(D, CurContext, S))
6094 F.erase();
6095 }
6096 F.done();
6097 } else {
6098 assert(IsInstantiation && "no scope in non-instantiation");
6099 assert(CurContext->isRecord() && "scope not record in instantiation");
6100 LookupQualifiedName(Previous, CurContext);
6101 }
6102
John McCall9f54ad42009-12-10 09:41:52 +00006103 // Check for invalid redeclarations.
6104 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6105 return 0;
6106
6107 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006108 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6109 return 0;
6110
John McCallaf8e6ed2009-11-12 03:15:40 +00006111 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006112 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006113 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006114 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006115 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006116 // FIXME: not all declaration name kinds are legal here
6117 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6118 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006119 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006120 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006121 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006122 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6123 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006124 }
John McCalled976492009-12-04 22:46:56 +00006125 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006126 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6127 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006128 }
John McCalled976492009-12-04 22:46:56 +00006129 D->setAccess(AS);
6130 CurContext->addDecl(D);
6131
6132 if (!LookupContext) return D;
6133 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006134
John McCall77bb1aa2010-05-01 00:40:08 +00006135 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006136 UD->setInvalidDecl();
6137 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006138 }
6139
Richard Smithc5a89a12012-04-02 01:30:27 +00006140 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006141 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006142 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006143 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006144 return UD;
6145 }
6146
6147 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006148
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006149 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006150
John McCall604e7f12009-12-08 07:46:18 +00006151 // Unlike most lookups, we don't always want to hide tag
6152 // declarations: tag names are visible through the using declaration
6153 // even if hidden by ordinary names, *except* in a dependent context
6154 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006155 if (!IsInstantiation)
6156 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006157
John McCallb9abd8722012-04-07 03:04:20 +00006158 // For the purposes of this lookup, we have a base object type
6159 // equal to that of the current context.
6160 if (CurContext->isRecord()) {
6161 R.setBaseObjectType(
6162 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6163 }
6164
John McCalla24dc2e2009-11-17 02:14:36 +00006165 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006166
John McCallf36e02d2009-10-09 21:13:30 +00006167 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006168 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006169 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006170 UD->setInvalidDecl();
6171 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006172 }
6173
John McCalled976492009-12-04 22:46:56 +00006174 if (R.isAmbiguous()) {
6175 UD->setInvalidDecl();
6176 return UD;
6177 }
Mike Stump1eb44332009-09-09 15:08:12 +00006178
John McCall7ba107a2009-11-18 02:36:19 +00006179 if (IsTypeName) {
6180 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006181 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006182 Diag(IdentLoc, diag::err_using_typename_non_type);
6183 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6184 Diag((*I)->getUnderlyingDecl()->getLocation(),
6185 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006186 UD->setInvalidDecl();
6187 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006188 }
6189 } else {
6190 // If we asked for a non-typename and we got a type, error out,
6191 // but only if this is an instantiation of an unresolved using
6192 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006193 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006194 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6195 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006196 UD->setInvalidDecl();
6197 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006198 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006199 }
6200
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006201 // C++0x N2914 [namespace.udecl]p6:
6202 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006203 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006204 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6205 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006206 UD->setInvalidDecl();
6207 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006208 }
Mike Stump1eb44332009-09-09 15:08:12 +00006209
John McCall9f54ad42009-12-10 09:41:52 +00006210 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6211 if (!CheckUsingShadowDecl(UD, *I, Previous))
6212 BuildUsingShadowDecl(S, UD, *I);
6213 }
John McCall9488ea12009-11-17 05:59:44 +00006214
6215 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006216}
6217
Sebastian Redlf677ea32011-02-05 19:23:19 +00006218/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006219bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6220 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006221
Douglas Gregordc355712011-02-25 00:36:19 +00006222 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006223 assert(SourceType &&
6224 "Using decl naming constructor doesn't have type in scope spec.");
6225 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6226
6227 // Check whether the named type is a direct base class.
6228 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6229 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6230 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6231 BaseIt != BaseE; ++BaseIt) {
6232 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6233 if (CanonicalSourceType == BaseType)
6234 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006235 if (BaseIt->getType()->isDependentType())
6236 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006237 }
6238
6239 if (BaseIt == BaseE) {
6240 // Did not find SourceType in the bases.
6241 Diag(UD->getUsingLocation(),
6242 diag::err_using_decl_constructor_not_in_direct_base)
6243 << UD->getNameInfo().getSourceRange()
6244 << QualType(SourceType, 0) << TargetClass;
6245 return true;
6246 }
6247
Richard Smithc5a89a12012-04-02 01:30:27 +00006248 if (!CurContext->isDependentContext())
6249 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006250
6251 return false;
6252}
6253
John McCall9f54ad42009-12-10 09:41:52 +00006254/// Checks that the given using declaration is not an invalid
6255/// redeclaration. Note that this is checking only for the using decl
6256/// itself, not for any ill-formedness among the UsingShadowDecls.
6257bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6258 bool isTypeName,
6259 const CXXScopeSpec &SS,
6260 SourceLocation NameLoc,
6261 const LookupResult &Prev) {
6262 // C++03 [namespace.udecl]p8:
6263 // C++0x [namespace.udecl]p10:
6264 // A using-declaration is a declaration and can therefore be used
6265 // repeatedly where (and only where) multiple declarations are
6266 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006267 //
John McCall8a726212010-11-29 18:01:58 +00006268 // That's in non-member contexts.
6269 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006270 return false;
6271
6272 NestedNameSpecifier *Qual
6273 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6274
6275 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6276 NamedDecl *D = *I;
6277
6278 bool DTypename;
6279 NestedNameSpecifier *DQual;
6280 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6281 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006282 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006283 } else if (UnresolvedUsingValueDecl *UD
6284 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6285 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006286 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006287 } else if (UnresolvedUsingTypenameDecl *UD
6288 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6289 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006290 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006291 } else continue;
6292
6293 // using decls differ if one says 'typename' and the other doesn't.
6294 // FIXME: non-dependent using decls?
6295 if (isTypeName != DTypename) continue;
6296
6297 // using decls differ if they name different scopes (but note that
6298 // template instantiation can cause this check to trigger when it
6299 // didn't before instantiation).
6300 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6301 Context.getCanonicalNestedNameSpecifier(DQual))
6302 continue;
6303
6304 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006305 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006306 return true;
6307 }
6308
6309 return false;
6310}
6311
John McCall604e7f12009-12-08 07:46:18 +00006312
John McCalled976492009-12-04 22:46:56 +00006313/// Checks that the given nested-name qualifier used in a using decl
6314/// in the current context is appropriately related to the current
6315/// scope. If an error is found, diagnoses it and returns true.
6316bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6317 const CXXScopeSpec &SS,
6318 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006319 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006320
John McCall604e7f12009-12-08 07:46:18 +00006321 if (!CurContext->isRecord()) {
6322 // C++03 [namespace.udecl]p3:
6323 // C++0x [namespace.udecl]p8:
6324 // A using-declaration for a class member shall be a member-declaration.
6325
6326 // If we weren't able to compute a valid scope, it must be a
6327 // dependent class scope.
6328 if (!NamedContext || NamedContext->isRecord()) {
6329 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6330 << SS.getRange();
6331 return true;
6332 }
6333
6334 // Otherwise, everything is known to be fine.
6335 return false;
6336 }
6337
6338 // The current scope is a record.
6339
6340 // If the named context is dependent, we can't decide much.
6341 if (!NamedContext) {
6342 // FIXME: in C++0x, we can diagnose if we can prove that the
6343 // nested-name-specifier does not refer to a base class, which is
6344 // still possible in some cases.
6345
6346 // Otherwise we have to conservatively report that things might be
6347 // okay.
6348 return false;
6349 }
6350
6351 if (!NamedContext->isRecord()) {
6352 // Ideally this would point at the last name in the specifier,
6353 // but we don't have that level of source info.
6354 Diag(SS.getRange().getBegin(),
6355 diag::err_using_decl_nested_name_specifier_is_not_class)
6356 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6357 return true;
6358 }
6359
Douglas Gregor6fb07292010-12-21 07:41:49 +00006360 if (!NamedContext->isDependentContext() &&
6361 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6362 return true;
6363
David Blaikie4e4d0842012-03-11 07:00:24 +00006364 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00006365 // C++0x [namespace.udecl]p3:
6366 // In a using-declaration used as a member-declaration, the
6367 // nested-name-specifier shall name a base class of the class
6368 // being defined.
6369
6370 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6371 cast<CXXRecordDecl>(NamedContext))) {
6372 if (CurContext == NamedContext) {
6373 Diag(NameLoc,
6374 diag::err_using_decl_nested_name_specifier_is_current_class)
6375 << SS.getRange();
6376 return true;
6377 }
6378
6379 Diag(SS.getRange().getBegin(),
6380 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6381 << (NestedNameSpecifier*) SS.getScopeRep()
6382 << cast<CXXRecordDecl>(CurContext)
6383 << SS.getRange();
6384 return true;
6385 }
6386
6387 return false;
6388 }
6389
6390 // C++03 [namespace.udecl]p4:
6391 // A using-declaration used as a member-declaration shall refer
6392 // to a member of a base class of the class being defined [etc.].
6393
6394 // Salient point: SS doesn't have to name a base class as long as
6395 // lookup only finds members from base classes. Therefore we can
6396 // diagnose here only if we can prove that that can't happen,
6397 // i.e. if the class hierarchies provably don't intersect.
6398
6399 // TODO: it would be nice if "definitely valid" results were cached
6400 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6401 // need to be repeated.
6402
6403 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00006404 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00006405
6406 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6407 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6408 Data->Bases.insert(Base);
6409 return true;
6410 }
6411
6412 bool hasDependentBases(const CXXRecordDecl *Class) {
6413 return !Class->forallBases(collect, this);
6414 }
6415
6416 /// Returns true if the base is dependent or is one of the
6417 /// accumulated base classes.
6418 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6419 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6420 return !Data->Bases.count(Base);
6421 }
6422
6423 bool mightShareBases(const CXXRecordDecl *Class) {
6424 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6425 }
6426 };
6427
6428 UserData Data;
6429
6430 // Returns false if we find a dependent base.
6431 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6432 return false;
6433
6434 // Returns false if the class has a dependent base or if it or one
6435 // of its bases is present in the base set of the current context.
6436 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6437 return false;
6438
6439 Diag(SS.getRange().getBegin(),
6440 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6441 << (NestedNameSpecifier*) SS.getScopeRep()
6442 << cast<CXXRecordDecl>(CurContext)
6443 << SS.getRange();
6444
6445 return true;
John McCalled976492009-12-04 22:46:56 +00006446}
6447
Richard Smith162e1c12011-04-15 14:24:37 +00006448Decl *Sema::ActOnAliasDeclaration(Scope *S,
6449 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006450 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006451 SourceLocation UsingLoc,
6452 UnqualifiedId &Name,
6453 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006454 // Skip up to the relevant declaration scope.
6455 while (S->getFlags() & Scope::TemplateParamScope)
6456 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006457 assert((S->getFlags() & Scope::DeclScope) &&
6458 "got alias-declaration outside of declaration scope");
6459
6460 if (Type.isInvalid())
6461 return 0;
6462
6463 bool Invalid = false;
6464 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6465 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006466 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006467
6468 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6469 return 0;
6470
6471 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006472 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006473 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006474 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6475 TInfo->getTypeLoc().getBeginLoc());
6476 }
Richard Smith162e1c12011-04-15 14:24:37 +00006477
6478 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6479 LookupName(Previous, S);
6480
6481 // Warn about shadowing the name of a template parameter.
6482 if (Previous.isSingleResult() &&
6483 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006484 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006485 Previous.clear();
6486 }
6487
6488 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6489 "name in alias declaration must be an identifier");
6490 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6491 Name.StartLocation,
6492 Name.Identifier, TInfo);
6493
6494 NewTD->setAccess(AS);
6495
6496 if (Invalid)
6497 NewTD->setInvalidDecl();
6498
Richard Smith3e4c6c42011-05-05 21:57:07 +00006499 CheckTypedefForVariablyModifiedType(S, NewTD);
6500 Invalid |= NewTD->isInvalidDecl();
6501
Richard Smith162e1c12011-04-15 14:24:37 +00006502 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006503
6504 NamedDecl *NewND;
6505 if (TemplateParamLists.size()) {
6506 TypeAliasTemplateDecl *OldDecl = 0;
6507 TemplateParameterList *OldTemplateParams = 0;
6508
6509 if (TemplateParamLists.size() != 1) {
6510 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6511 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6512 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6513 }
6514 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6515
6516 // Only consider previous declarations in the same scope.
6517 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6518 /*ExplicitInstantiationOrSpecialization*/false);
6519 if (!Previous.empty()) {
6520 Redeclaration = true;
6521
6522 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6523 if (!OldDecl && !Invalid) {
6524 Diag(UsingLoc, diag::err_redefinition_different_kind)
6525 << Name.Identifier;
6526
6527 NamedDecl *OldD = Previous.getRepresentativeDecl();
6528 if (OldD->getLocation().isValid())
6529 Diag(OldD->getLocation(), diag::note_previous_definition);
6530
6531 Invalid = true;
6532 }
6533
6534 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6535 if (TemplateParameterListsAreEqual(TemplateParams,
6536 OldDecl->getTemplateParameters(),
6537 /*Complain=*/true,
6538 TPL_TemplateMatch))
6539 OldTemplateParams = OldDecl->getTemplateParameters();
6540 else
6541 Invalid = true;
6542
6543 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6544 if (!Invalid &&
6545 !Context.hasSameType(OldTD->getUnderlyingType(),
6546 NewTD->getUnderlyingType())) {
6547 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6548 // but we can't reasonably accept it.
6549 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6550 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6551 if (OldTD->getLocation().isValid())
6552 Diag(OldTD->getLocation(), diag::note_previous_definition);
6553 Invalid = true;
6554 }
6555 }
6556 }
6557
6558 // Merge any previous default template arguments into our parameters,
6559 // and check the parameter list.
6560 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6561 TPC_TypeAliasTemplate))
6562 return 0;
6563
6564 TypeAliasTemplateDecl *NewDecl =
6565 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6566 Name.Identifier, TemplateParams,
6567 NewTD);
6568
6569 NewDecl->setAccess(AS);
6570
6571 if (Invalid)
6572 NewDecl->setInvalidDecl();
6573 else if (OldDecl)
6574 NewDecl->setPreviousDeclaration(OldDecl);
6575
6576 NewND = NewDecl;
6577 } else {
6578 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6579 NewND = NewTD;
6580 }
Richard Smith162e1c12011-04-15 14:24:37 +00006581
6582 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006583 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006584
Richard Smith3e4c6c42011-05-05 21:57:07 +00006585 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006586}
6587
John McCalld226f652010-08-21 09:40:31 +00006588Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006589 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006590 SourceLocation AliasLoc,
6591 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006592 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006593 SourceLocation IdentLoc,
6594 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006595
Anders Carlsson81c85c42009-03-28 23:53:49 +00006596 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006597 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6598 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006599
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006600 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006601 NamedDecl *PrevDecl
6602 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6603 ForRedeclaration);
6604 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6605 PrevDecl = 0;
6606
6607 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006608 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006609 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006610 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006611 // FIXME: At some point, we'll want to create the (redundant)
6612 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006613 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006614 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006615 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006616 }
Mike Stump1eb44332009-09-09 15:08:12 +00006617
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006618 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6619 diag::err_redefinition_different_kind;
6620 Diag(AliasLoc, DiagID) << Alias;
6621 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006622 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006623 }
6624
John McCalla24dc2e2009-11-17 02:14:36 +00006625 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006626 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006627
John McCallf36e02d2009-10-09 21:13:30 +00006628 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006629 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00006630 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006631 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006632 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006633 }
Mike Stump1eb44332009-09-09 15:08:12 +00006634
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006635 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006636 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006637 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006638 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006639
John McCall3dbd3d52010-02-16 06:53:13 +00006640 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006641 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006642}
6643
Douglas Gregor39957dc2010-05-01 15:04:51 +00006644namespace {
6645 /// \brief Scoped object used to handle the state changes required in Sema
6646 /// to implicitly define the body of a C++ member function;
6647 class ImplicitlyDefinedFunctionScope {
6648 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006649 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006650
6651 public:
6652 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006653 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006654 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006655 S.PushFunctionScope();
6656 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6657 }
6658
6659 ~ImplicitlyDefinedFunctionScope() {
6660 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006661 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006662 }
6663 };
6664}
6665
Sean Hunt001cad92011-05-10 00:49:42 +00006666Sema::ImplicitExceptionSpecification
6667Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006668 // C++ [except.spec]p14:
6669 // An implicitly declared special member function (Clause 12) shall have an
6670 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00006671 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006672 if (ClassDecl->isInvalidDecl())
6673 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006674
Sebastian Redl60618fa2011-03-12 11:50:43 +00006675 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006676 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6677 BEnd = ClassDecl->bases_end();
6678 B != BEnd; ++B) {
6679 if (B->isVirtual()) // Handled below.
6680 continue;
6681
Douglas Gregor18274032010-07-03 00:47:00 +00006682 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6683 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006684 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6685 // If this is a deleted function, add it anyway. This might be conformant
6686 // with the standard. This might not. I'm not sure. It might not matter.
6687 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006688 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006689 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006690 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006691
6692 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006693 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6694 BEnd = ClassDecl->vbases_end();
6695 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006696 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6697 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006698 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6699 // If this is a deleted function, add it anyway. This might be conformant
6700 // with the standard. This might not. I'm not sure. It might not matter.
6701 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006702 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006703 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006704 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006705
6706 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006707 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6708 FEnd = ClassDecl->field_end();
6709 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006710 if (F->hasInClassInitializer()) {
6711 if (Expr *E = F->getInClassInitializer())
6712 ExceptSpec.CalledExpr(E);
6713 else if (!F->isInvalidDecl())
6714 ExceptSpec.SetDelayed();
6715 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006716 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006717 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6718 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6719 // If this is a deleted function, add it anyway. This might be conformant
6720 // with the standard. This might not. I'm not sure. It might not matter.
6721 // In particular, the problem is that this function never gets called. It
6722 // might just be ill-formed because this function attempts to refer to
6723 // a deleted function here.
6724 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006725 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006726 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006727 }
John McCalle23cf432010-12-14 08:05:40 +00006728
Sean Hunt001cad92011-05-10 00:49:42 +00006729 return ExceptSpec;
6730}
6731
6732CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6733 CXXRecordDecl *ClassDecl) {
6734 // C++ [class.ctor]p5:
6735 // A default constructor for a class X is a constructor of class X
6736 // that can be called without an argument. If there is no
6737 // user-declared constructor for class X, a default constructor is
6738 // implicitly declared. An implicitly-declared default constructor
6739 // is an inline public member of its class.
6740 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6741 "Should not build implicit default constructor!");
6742
6743 ImplicitExceptionSpecification Spec =
6744 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6745 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006746
Richard Smith7756afa2012-06-10 05:43:50 +00006747 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
6748 CXXDefaultConstructor,
6749 false);
6750
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006751 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006752 CanQualType ClassType
6753 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006754 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006755 DeclarationName Name
6756 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006757 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00006758 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6759 Context, ClassDecl, ClassLoc, NameInfo,
6760 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
6761 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00006762 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006763 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006764 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006765 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006766 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006767
6768 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006769 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6770
Douglas Gregor23c94db2010-07-02 17:43:08 +00006771 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006772 PushOnScopeChains(DefaultCon, S, false);
6773 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006774
Sean Hunte16da072011-10-10 06:18:57 +00006775 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00006776 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006777
Douglas Gregor32df23e2010-07-01 22:02:46 +00006778 return DefaultCon;
6779}
6780
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006781void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6782 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006783 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006784 !Constructor->doesThisDeclarationHaveABody() &&
6785 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006786 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006787
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006788 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006789 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006790
Douglas Gregor39957dc2010-05-01 15:04:51 +00006791 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006792 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006793 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006794 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006795 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006796 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006797 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006798 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006799 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006800
6801 SourceLocation Loc = Constructor->getLocation();
6802 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6803
6804 Constructor->setUsed();
6805 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006806
6807 if (ASTMutationListener *L = getASTMutationListener()) {
6808 L->CompletedImplicitDefinition(Constructor);
6809 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006810}
6811
Richard Smith7a614d82011-06-11 17:19:42 +00006812/// Get any existing defaulted default constructor for the given class. Do not
6813/// implicitly define one if it does not exist.
6814static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6815 CXXRecordDecl *D) {
6816 ASTContext &Context = Self.Context;
6817 QualType ClassType = Context.getTypeDeclType(D);
6818 DeclarationName ConstructorName
6819 = Context.DeclarationNames.getCXXConstructorName(
6820 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6821
6822 DeclContext::lookup_const_iterator Con, ConEnd;
6823 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6824 Con != ConEnd; ++Con) {
6825 // A function template cannot be defaulted.
6826 if (isa<FunctionTemplateDecl>(*Con))
6827 continue;
6828
6829 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6830 if (Constructor->isDefaultConstructor())
6831 return Constructor->isDefaulted() ? Constructor : 0;
6832 }
6833 return 0;
6834}
6835
6836void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6837 if (!D) return;
6838 AdjustDeclIfTemplate(D);
6839
6840 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6841 CXXConstructorDecl *CtorDecl
6842 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6843
6844 if (!CtorDecl) return;
6845
6846 // Compute the exception specification for the default constructor.
6847 const FunctionProtoType *CtorTy =
6848 CtorDecl->getType()->castAs<FunctionProtoType>();
6849 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
Richard Smithe6975e92012-04-17 00:58:00 +00006850 // FIXME: Don't do this unless the exception spec is needed.
Richard Smith7a614d82011-06-11 17:19:42 +00006851 ImplicitExceptionSpecification Spec =
6852 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6853 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6854 assert(EPI.ExceptionSpecType != EST_Delayed);
6855
6856 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6857 }
6858
6859 // If the default constructor is explicitly defaulted, checking the exception
6860 // specification is deferred until now.
6861 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6862 !ClassDecl->isDependentType())
Richard Smith3003e1d2012-05-15 04:39:51 +00006863 CheckExplicitlyDefaultedSpecialMember(CtorDecl);
Richard Smith7a614d82011-06-11 17:19:42 +00006864}
6865
Sebastian Redlf677ea32011-02-05 19:23:19 +00006866void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6867 // We start with an initial pass over the base classes to collect those that
6868 // inherit constructors from. If there are none, we can forgo all further
6869 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006870 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006871 BasesVector BasesToInheritFrom;
6872 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6873 BaseE = ClassDecl->bases_end();
6874 BaseIt != BaseE; ++BaseIt) {
6875 if (BaseIt->getInheritConstructors()) {
6876 QualType Base = BaseIt->getType();
6877 if (Base->isDependentType()) {
6878 // If we inherit constructors from anything that is dependent, just
6879 // abort processing altogether. We'll get another chance for the
6880 // instantiations.
6881 return;
6882 }
6883 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6884 }
6885 }
6886 if (BasesToInheritFrom.empty())
6887 return;
6888
6889 // Now collect the constructors that we already have in the current class.
6890 // Those take precedence over inherited constructors.
6891 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6892 // unless there is a user-declared constructor with the same signature in
6893 // the class where the using-declaration appears.
6894 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6895 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6896 CtorE = ClassDecl->ctor_end();
6897 CtorIt != CtorE; ++CtorIt) {
6898 ExistingConstructors.insert(
6899 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6900 }
6901
Sebastian Redlf677ea32011-02-05 19:23:19 +00006902 DeclarationName CreatedCtorName =
6903 Context.DeclarationNames.getCXXConstructorName(
6904 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6905
6906 // Now comes the true work.
6907 // First, we keep a map from constructor types to the base that introduced
6908 // them. Needed for finding conflicting constructors. We also keep the
6909 // actually inserted declarations in there, for pretty diagnostics.
6910 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6911 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6912 ConstructorToSourceMap InheritedConstructors;
6913 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6914 BaseE = BasesToInheritFrom.end();
6915 BaseIt != BaseE; ++BaseIt) {
6916 const RecordType *Base = *BaseIt;
6917 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6918 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6919 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6920 CtorE = BaseDecl->ctor_end();
6921 CtorIt != CtorE; ++CtorIt) {
6922 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00006923 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00006924 DeclarationName Name =
6925 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00006926 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
6927 LookupQualifiedName(Result, CurContext);
6928 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006929 SourceLocation UsingLoc = UD ? UD->getLocation() :
6930 ClassDecl->getLocation();
6931
6932 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6933 // from the class X named in the using-declaration consists of actual
6934 // constructors and notional constructors that result from the
6935 // transformation of defaulted parameters as follows:
6936 // - all non-template default constructors of X, and
6937 // - for each non-template constructor of X that has at least one
6938 // parameter with a default argument, the set of constructors that
6939 // results from omitting any ellipsis parameter specification and
6940 // successively omitting parameters with a default argument from the
6941 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00006942 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006943 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6944 const FunctionProtoType *BaseCtorType =
6945 BaseCtor->getType()->getAs<FunctionProtoType>();
6946
6947 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6948 maxParams = BaseCtor->getNumParams();
6949 params <= maxParams; ++params) {
6950 // Skip default constructors. They're never inherited.
6951 if (params == 0)
6952 continue;
6953 // Skip copy and move constructors for the same reason.
6954 if (CanBeCopyOrMove && params == 1)
6955 continue;
6956
6957 // Build up a function type for this particular constructor.
6958 // FIXME: The working paper does not consider that the exception spec
6959 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006960 // source. This code doesn't yet, either. When it does, this code will
6961 // need to be delayed until after exception specifications and in-class
6962 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006963 const Type *NewCtorType;
6964 if (params == maxParams)
6965 NewCtorType = BaseCtorType;
6966 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006967 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006968 for (unsigned i = 0; i < params; ++i) {
6969 Args.push_back(BaseCtorType->getArgType(i));
6970 }
6971 FunctionProtoType::ExtProtoInfo ExtInfo =
6972 BaseCtorType->getExtProtoInfo();
6973 ExtInfo.Variadic = false;
6974 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6975 Args.data(), params, ExtInfo)
6976 .getTypePtr();
6977 }
6978 const Type *CanonicalNewCtorType =
6979 Context.getCanonicalType(NewCtorType);
6980
6981 // Now that we have the type, first check if the class already has a
6982 // constructor with this signature.
6983 if (ExistingConstructors.count(CanonicalNewCtorType))
6984 continue;
6985
6986 // Then we check if we have already declared an inherited constructor
6987 // with this signature.
6988 std::pair<ConstructorToSourceMap::iterator, bool> result =
6989 InheritedConstructors.insert(std::make_pair(
6990 CanonicalNewCtorType,
6991 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6992 if (!result.second) {
6993 // Already in the map. If it came from a different class, that's an
6994 // error. Not if it's from the same.
6995 CanQualType PreviousBase = result.first->second.first;
6996 if (CanonicalBase != PreviousBase) {
6997 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6998 const CXXConstructorDecl *PrevBaseCtor =
6999 PrevCtor->getInheritedConstructor();
7000 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7001
7002 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7003 Diag(BaseCtor->getLocation(),
7004 diag::note_using_decl_constructor_conflict_current_ctor);
7005 Diag(PrevBaseCtor->getLocation(),
7006 diag::note_using_decl_constructor_conflict_previous_ctor);
7007 Diag(PrevCtor->getLocation(),
7008 diag::note_using_decl_constructor_conflict_previous_using);
7009 }
7010 continue;
7011 }
7012
7013 // OK, we're there, now add the constructor.
7014 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007015 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007016 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7017 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007018 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7019 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007020 /*ImplicitlyDeclared=*/true,
7021 // FIXME: Due to a defect in the standard, we treat inherited
7022 // constructors as constexpr even if that makes them ill-formed.
7023 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007024 NewCtor->setAccess(BaseCtor->getAccess());
7025
7026 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007027 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007028 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007029 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7030 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007031 /*IdentifierInfo=*/0,
7032 BaseCtorType->getArgType(i),
7033 /*TInfo=*/0, SC_None,
7034 SC_None, /*DefaultArg=*/0));
7035 }
David Blaikie4278c652011-09-21 18:16:56 +00007036 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007037 NewCtor->setInheritedConstructor(BaseCtor);
7038
Sebastian Redlf677ea32011-02-05 19:23:19 +00007039 ClassDecl->addDecl(NewCtor);
7040 result.first->second.second = NewCtor;
7041 }
7042 }
7043 }
7044}
7045
Sean Huntcb45a0f2011-05-12 22:46:25 +00007046Sema::ImplicitExceptionSpecification
7047Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007048 // C++ [except.spec]p14:
7049 // An implicitly declared special member function (Clause 12) shall have
7050 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007051 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007052 if (ClassDecl->isInvalidDecl())
7053 return ExceptSpec;
7054
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007055 // Direct base-class destructors.
7056 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7057 BEnd = ClassDecl->bases_end();
7058 B != BEnd; ++B) {
7059 if (B->isVirtual()) // Handled below.
7060 continue;
7061
7062 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007063 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007064 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007065 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007066
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007067 // Virtual base-class destructors.
7068 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7069 BEnd = ClassDecl->vbases_end();
7070 B != BEnd; ++B) {
7071 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007072 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007073 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007074 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007075
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007076 // Field destructors.
7077 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7078 FEnd = ClassDecl->field_end();
7079 F != FEnd; ++F) {
7080 if (const RecordType *RecordTy
7081 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007082 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007083 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007084 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007085
Sean Huntcb45a0f2011-05-12 22:46:25 +00007086 return ExceptSpec;
7087}
7088
7089CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7090 // C++ [class.dtor]p2:
7091 // If a class has no user-declared destructor, a destructor is
7092 // declared implicitly. An implicitly-declared destructor is an
7093 // inline public member of its class.
7094
7095 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007096 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007097 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7098
Douglas Gregor4923aa22010-07-02 20:37:36 +00007099 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007100 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007101
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007102 CanQualType ClassType
7103 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007104 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007105 DeclarationName Name
7106 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007107 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007108 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007109 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7110 /*isInline=*/true,
7111 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007112 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007113 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007114 Destructor->setImplicit();
7115 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007116
7117 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007118 ++ASTContext::NumImplicitDestructorsDeclared;
7119
7120 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007121 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007122 PushOnScopeChains(Destructor, S, false);
7123 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007124
7125 // This could be uniqued if it ever proves significant.
7126 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007127
Richard Smith9a561d52012-02-26 09:11:52 +00007128 AddOverriddenMethods(ClassDecl, Destructor);
7129
Richard Smith7d5088a2012-02-18 02:02:13 +00007130 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Sean Huntcb45a0f2011-05-12 22:46:25 +00007131 Destructor->setDeletedAsWritten();
Richard Smith9a561d52012-02-26 09:11:52 +00007132
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007133 return Destructor;
7134}
7135
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007136void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007137 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007138 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007139 !Destructor->doesThisDeclarationHaveABody() &&
7140 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007141 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007142 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007143 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007144
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007145 if (Destructor->isInvalidDecl())
7146 return;
7147
Douglas Gregor39957dc2010-05-01 15:04:51 +00007148 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007149
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007150 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007151 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7152 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007153
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007154 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007155 Diag(CurrentLocation, diag::note_member_synthesized_at)
7156 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7157
7158 Destructor->setInvalidDecl();
7159 return;
7160 }
7161
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007162 SourceLocation Loc = Destructor->getLocation();
7163 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007164 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007165 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007166 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007167
7168 if (ASTMutationListener *L = getASTMutationListener()) {
7169 L->CompletedImplicitDefinition(Destructor);
7170 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007171}
7172
Richard Smitha4156b82012-04-21 18:42:51 +00007173/// \brief Perform any semantic analysis which needs to be delayed until all
7174/// pending class member declarations have been parsed.
7175void Sema::ActOnFinishCXXMemberDecls() {
7176 // Now we have parsed all exception specifications, determine the implicit
7177 // exception specifications for destructors.
7178 for (unsigned i = 0, e = DelayedDestructorExceptionSpecs.size();
7179 i != e; ++i) {
7180 CXXDestructorDecl *Dtor = DelayedDestructorExceptionSpecs[i];
7181 AdjustDestructorExceptionSpec(Dtor->getParent(), Dtor, true);
7182 }
7183 DelayedDestructorExceptionSpecs.clear();
7184
7185 // Perform any deferred checking of exception specifications for virtual
7186 // destructors.
7187 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7188 i != e; ++i) {
7189 const CXXDestructorDecl *Dtor =
7190 DelayedDestructorExceptionSpecChecks[i].first;
7191 assert(!Dtor->getParent()->isDependentType() &&
7192 "Should not ever add destructors of templates into the list.");
7193 CheckOverridingFunctionExceptionSpec(Dtor,
7194 DelayedDestructorExceptionSpecChecks[i].second);
7195 }
7196 DelayedDestructorExceptionSpecChecks.clear();
7197}
7198
Sebastian Redl0ee33912011-05-19 05:13:44 +00007199void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
Richard Smitha4156b82012-04-21 18:42:51 +00007200 CXXDestructorDecl *destructor,
7201 bool WasDelayed) {
Sebastian Redl0ee33912011-05-19 05:13:44 +00007202 // C++11 [class.dtor]p3:
7203 // A declaration of a destructor that does not have an exception-
7204 // specification is implicitly considered to have the same exception-
7205 // specification as an implicit declaration.
7206 const FunctionProtoType *dtorType = destructor->getType()->
7207 getAs<FunctionProtoType>();
Richard Smitha4156b82012-04-21 18:42:51 +00007208 if (!WasDelayed && dtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007209 return;
7210
7211 ImplicitExceptionSpecification exceptSpec =
7212 ComputeDefaultedDtorExceptionSpec(classDecl);
7213
Chandler Carruth3f224b22011-09-20 04:55:26 +00007214 // Replace the destructor's type, building off the existing one. Fortunately,
7215 // the only thing of interest in the destructor type is its extended info.
7216 // The return and arguments are fixed.
7217 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007218 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7219 epi.NumExceptions = exceptSpec.size();
7220 epi.Exceptions = exceptSpec.data();
7221 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7222
7223 destructor->setType(ty);
7224
Richard Smitha4156b82012-04-21 18:42:51 +00007225 // If we can't compute the exception specification for this destructor yet
7226 // (because it depends on an exception specification which we have not parsed
7227 // yet), make a note that we need to try again when the class is complete.
7228 if (epi.ExceptionSpecType == EST_Delayed) {
7229 assert(!WasDelayed && "couldn't compute destructor exception spec");
7230 DelayedDestructorExceptionSpecs.push_back(destructor);
7231 }
7232
Sebastian Redl0ee33912011-05-19 05:13:44 +00007233 // FIXME: If the destructor has a body that could throw, and the newly created
7234 // spec doesn't allow exceptions, we should emit a warning, because this
7235 // change in behavior can break conforming C++03 programs at runtime.
7236 // However, we don't have a body yet, so it needs to be done somewhere else.
7237}
7238
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007239/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007240/// \c To.
7241///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007242/// This routine is used to copy/move the members of a class with an
7243/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007244/// copied are arrays, this routine builds for loops to copy them.
7245///
7246/// \param S The Sema object used for type-checking.
7247///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007248/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007249///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007250/// \param T The type of the expressions being copied/moved. Both expressions
7251/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007252///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007253/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007254///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007255/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007256///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007257/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007258/// Otherwise, it's a non-static member subobject.
7259///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007260/// \param Copying Whether we're copying or moving.
7261///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007262/// \param Depth Internal parameter recording the depth of the recursion.
7263///
7264/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007265static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007266BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007267 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007268 bool CopyingBaseSubobject, bool Copying,
7269 unsigned Depth = 0) {
7270 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007271 // Each subobject is assigned in the manner appropriate to its type:
7272 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007273 // - if the subobject is of class type, as if by a call to operator= with
7274 // the subobject as the object expression and the corresponding
7275 // subobject of x as a single function argument (as if by explicit
7276 // qualification; that is, ignoring any possible virtual overriding
7277 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007278 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7279 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7280
7281 // Look for operator=.
7282 DeclarationName Name
7283 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7284 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7285 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7286
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007287 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007288 LookupResult::Filter F = OpLookup.makeFilter();
7289 while (F.hasNext()) {
7290 NamedDecl *D = F.next();
7291 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Richard Smith1c931be2012-04-02 18:40:40 +00007292 if (Method->isCopyAssignmentOperator() ||
7293 (!Copying && Method->isMoveAssignmentOperator()))
Douglas Gregor06a9f362010-05-01 20:49:11 +00007294 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007295
Douglas Gregor06a9f362010-05-01 20:49:11 +00007296 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007297 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007298 F.done();
7299
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007300 // Suppress the protected check (C++ [class.protected]) for each of the
7301 // assignment operators we found. This strange dance is required when
7302 // we're assigning via a base classes's copy-assignment operator. To
7303 // ensure that we're getting the right base class subobject (without
7304 // ambiguities), we need to cast "this" to that subobject type; to
7305 // ensure that we don't go through the virtual call mechanism, we need
7306 // to qualify the operator= name with the base class (see below). However,
7307 // this means that if the base class has a protected copy assignment
7308 // operator, the protected member access check will fail. So, we
7309 // rewrite "protected" access to "public" access in this case, since we
7310 // know by construction that we're calling from a derived class.
7311 if (CopyingBaseSubobject) {
7312 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7313 L != LEnd; ++L) {
7314 if (L.getAccess() == AS_protected)
7315 L.setAccess(AS_public);
7316 }
7317 }
7318
Douglas Gregor06a9f362010-05-01 20:49:11 +00007319 // Create the nested-name-specifier that will be used to qualify the
7320 // reference to operator=; this is required to suppress the virtual
7321 // call mechanism.
7322 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007323 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007324 SS.MakeTrivial(S.Context,
7325 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007326 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007327 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007328
7329 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007330 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007331 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007332 /*TemplateKWLoc=*/SourceLocation(),
7333 /*FirstQualifierInScope=*/0,
7334 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007335 /*TemplateArgs=*/0,
7336 /*SuppressQualifierCheck=*/true);
7337 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007338 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007339
7340 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007341
John McCall60d7b3a2010-08-24 06:29:42 +00007342 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007343 OpEqualRef.takeAs<Expr>(),
7344 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007345 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007346 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007347
7348 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007349 }
John McCallb0207482010-03-16 06:11:48 +00007350
Douglas Gregor06a9f362010-05-01 20:49:11 +00007351 // - if the subobject is of scalar type, the built-in assignment
7352 // operator is used.
7353 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7354 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007355 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007356 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007357 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007358
7359 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007360 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007361
7362 // - if the subobject is an array, each element is assigned, in the
7363 // manner appropriate to the element type;
7364
7365 // Construct a loop over the array bounds, e.g.,
7366 //
7367 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7368 //
7369 // that will copy each of the array elements.
7370 QualType SizeType = S.Context.getSizeType();
7371
7372 // Create the iteration variable.
7373 IdentifierInfo *IterationVarName = 0;
7374 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007375 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007376 llvm::raw_svector_ostream OS(Str);
7377 OS << "__i" << Depth;
7378 IterationVarName = &S.Context.Idents.get(OS.str());
7379 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007380 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007381 IterationVarName, SizeType,
7382 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007383 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007384
7385 // Initialize the iteration variable to zero.
7386 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007387 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007388
7389 // Create a reference to the iteration variable; we'll use this several
7390 // times throughout.
7391 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007392 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007393 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007394 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7395 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7396
Douglas Gregor06a9f362010-05-01 20:49:11 +00007397 // Create the DeclStmt that holds the iteration variable.
7398 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7399
7400 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007401 llvm::APInt Upper
7402 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007403 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007404 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007405 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7406 BO_NE, S.Context.BoolTy,
7407 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007408
7409 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007410 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007411 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7412 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007413
7414 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007415 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007416 IterationVarRefRVal,
7417 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007418 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007419 IterationVarRefRVal,
7420 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007421 if (!Copying) // Cast to rvalue
7422 From = CastForMoving(S, From);
7423
7424 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007425 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7426 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007427 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007428 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007429 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007430
7431 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007432 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007433 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007434 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007435 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007436}
7437
Sean Hunt30de05c2011-05-14 05:23:20 +00007438std::pair<Sema::ImplicitExceptionSpecification, bool>
7439Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7440 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007441 if (ClassDecl->isInvalidDecl())
Richard Smith3003e1d2012-05-15 04:39:51 +00007442 return std::make_pair(ImplicitExceptionSpecification(*this), true);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007443
Douglas Gregord3c35902010-07-01 16:36:15 +00007444 // C++ [class.copy]p10:
7445 // If the class definition does not explicitly declare a copy
7446 // assignment operator, one is declared implicitly.
7447 // The implicitly-defined copy assignment operator for a class X
7448 // will have the form
7449 //
7450 // X& X::operator=(const X&)
7451 //
7452 // if
7453 bool HasConstCopyAssignment = true;
7454
7455 // -- each direct base class B of X has a copy assignment operator
7456 // whose parameter is of type const B&, const volatile B& or B,
7457 // and
7458 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7459 BaseEnd = ClassDecl->bases_end();
7460 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007461 // We'll handle this below
7462 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7463 continue;
7464
Douglas Gregord3c35902010-07-01 16:36:15 +00007465 assert(!Base->getType()->isDependentType() &&
7466 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007467 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smith704c8f72012-04-20 18:46:14 +00007468 HasConstCopyAssignment &=
7469 (bool)LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7470 false, 0);
Sean Hunt661c67a2011-06-21 23:42:56 +00007471 }
7472
Richard Smithebaf0e62011-10-18 20:49:44 +00007473 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007474 if (LangOpts.CPlusPlus0x) {
7475 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7476 BaseEnd = ClassDecl->vbases_end();
7477 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7478 assert(!Base->getType()->isDependentType() &&
7479 "Cannot generate implicit members for class with dependent bases.");
7480 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smith704c8f72012-04-20 18:46:14 +00007481 HasConstCopyAssignment &=
7482 (bool)LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7483 false, 0);
Sean Hunt661c67a2011-06-21 23:42:56 +00007484 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007485 }
7486
7487 // -- for all the nonstatic data members of X that are of a class
7488 // type M (or array thereof), each such class type has a copy
7489 // assignment operator whose parameter is of type const M&,
7490 // const volatile M& or M.
7491 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7492 FieldEnd = ClassDecl->field_end();
7493 HasConstCopyAssignment && Field != FieldEnd;
7494 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007495 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007496 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith704c8f72012-04-20 18:46:14 +00007497 HasConstCopyAssignment &=
7498 (bool)LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const,
7499 false, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00007500 }
7501 }
7502
7503 // Otherwise, the implicitly declared copy assignment operator will
7504 // have the form
7505 //
7506 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007507
Douglas Gregorb87786f2010-07-01 17:48:08 +00007508 // C++ [except.spec]p14:
7509 // An implicitly declared special member function (Clause 12) shall have an
7510 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007511
7512 // It is unspecified whether or not an implicit copy assignment operator
7513 // attempts to deduplicate calls to assignment operators of virtual bases are
7514 // made. As such, this exception specification is effectively unspecified.
7515 // Based on a similar decision made for constness in C++0x, we're erring on
7516 // the side of assuming such calls to be made regardless of whether they
7517 // actually happen.
Richard Smithe6975e92012-04-17 00:58:00 +00007518 ImplicitExceptionSpecification ExceptSpec(*this);
Sean Hunt661c67a2011-06-21 23:42:56 +00007519 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007520 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7521 BaseEnd = ClassDecl->bases_end();
7522 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007523 if (Base->isVirtual())
7524 continue;
7525
Douglas Gregora376d102010-07-02 21:50:04 +00007526 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007527 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007528 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7529 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007530 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00007531 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007532
7533 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7534 BaseEnd = ClassDecl->vbases_end();
7535 Base != BaseEnd; ++Base) {
7536 CXXRecordDecl *BaseClassDecl
7537 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7538 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7539 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007540 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00007541 }
7542
Douglas Gregorb87786f2010-07-01 17:48:08 +00007543 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7544 FieldEnd = ClassDecl->field_end();
7545 Field != FieldEnd;
7546 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007547 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007548 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7549 if (CXXMethodDecl *CopyAssign =
7550 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007551 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007552 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007553 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007554
Sean Hunt30de05c2011-05-14 05:23:20 +00007555 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7556}
7557
7558CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7559 // Note: The following rules are largely analoguous to the copy
7560 // constructor rules. Note that virtual bases are not taken into account
7561 // for determining the argument type of the operator. Note also that
7562 // operators taking an object instead of a reference are allowed.
7563
Richard Smithe6975e92012-04-17 00:58:00 +00007564 ImplicitExceptionSpecification Spec(*this);
Sean Hunt30de05c2011-05-14 05:23:20 +00007565 bool Const;
7566 llvm::tie(Spec, Const) =
7567 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7568
7569 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7570 QualType RetType = Context.getLValueReferenceType(ArgType);
7571 if (Const)
7572 ArgType = ArgType.withConst();
7573 ArgType = Context.getLValueReferenceType(ArgType);
7574
Douglas Gregord3c35902010-07-01 16:36:15 +00007575 // An implicitly-declared copy assignment operator is an inline public
7576 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007577 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007578 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007579 SourceLocation ClassLoc = ClassDecl->getLocation();
7580 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007581 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007582 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007583 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007584 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007585 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007586 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007587 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007588 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007589 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007590 CopyAssignment->setImplicit();
7591 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007592
7593 // Add the parameter to the operator.
7594 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007595 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007596 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007597 SC_None,
7598 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007599 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007600
Douglas Gregora376d102010-07-02 21:50:04 +00007601 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007602 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007603
Douglas Gregor23c94db2010-07-02 17:43:08 +00007604 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007605 PushOnScopeChains(CopyAssignment, S, false);
7606 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007607
Nico Weberafcc96a2012-01-23 03:19:29 +00007608 // C++0x [class.copy]p19:
7609 // .... If the class definition does not explicitly declare a copy
7610 // assignment operator, there is no user-declared move constructor, and
7611 // there is no user-declared move assignment operator, a copy assignment
7612 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00007613 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007614 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00007615
Douglas Gregord3c35902010-07-01 16:36:15 +00007616 AddOverriddenMethods(ClassDecl, CopyAssignment);
7617 return CopyAssignment;
7618}
7619
Douglas Gregor06a9f362010-05-01 20:49:11 +00007620void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7621 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007622 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007623 CopyAssignOperator->isOverloadedOperator() &&
7624 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00007625 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7626 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007627 "DefineImplicitCopyAssignment called for wrong function");
7628
7629 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7630
7631 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7632 CopyAssignOperator->setInvalidDecl();
7633 return;
7634 }
7635
7636 CopyAssignOperator->setUsed();
7637
7638 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007639 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007640
7641 // C++0x [class.copy]p30:
7642 // The implicitly-defined or explicitly-defaulted copy assignment operator
7643 // for a non-union class X performs memberwise copy assignment of its
7644 // subobjects. The direct base classes of X are assigned first, in the
7645 // order of their declaration in the base-specifier-list, and then the
7646 // immediate non-static data members of X are assigned, in the order in
7647 // which they were declared in the class definition.
7648
7649 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007650 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007651
7652 // The parameter for the "other" object, which we are copying from.
7653 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7654 Qualifiers OtherQuals = Other->getType().getQualifiers();
7655 QualType OtherRefType = Other->getType();
7656 if (const LValueReferenceType *OtherRef
7657 = OtherRefType->getAs<LValueReferenceType>()) {
7658 OtherRefType = OtherRef->getPointeeType();
7659 OtherQuals = OtherRefType.getQualifiers();
7660 }
7661
7662 // Our location for everything implicitly-generated.
7663 SourceLocation Loc = CopyAssignOperator->getLocation();
7664
7665 // Construct a reference to the "other" object. We'll be using this
7666 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007667 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007668 assert(OtherRef && "Reference to parameter cannot fail!");
7669
7670 // Construct the "this" pointer. We'll be using this throughout the generated
7671 // ASTs.
7672 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7673 assert(This && "Reference to this cannot fail!");
7674
7675 // Assign base classes.
7676 bool Invalid = false;
7677 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7678 E = ClassDecl->bases_end(); Base != E; ++Base) {
7679 // Form the assignment:
7680 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7681 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007682 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007683 Invalid = true;
7684 continue;
7685 }
7686
John McCallf871d0c2010-08-07 06:22:56 +00007687 CXXCastPath BasePath;
7688 BasePath.push_back(Base);
7689
Douglas Gregor06a9f362010-05-01 20:49:11 +00007690 // Construct the "from" expression, which is an implicit cast to the
7691 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007692 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007693 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7694 CK_UncheckedDerivedToBase,
7695 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007696
7697 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007698 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007699
7700 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007701 To = ImpCastExprToType(To.take(),
7702 Context.getCVRQualifiedType(BaseType,
7703 CopyAssignOperator->getTypeQualifiers()),
7704 CK_UncheckedDerivedToBase,
7705 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007706
7707 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007708 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007709 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007710 /*CopyingBaseSubobject=*/true,
7711 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007712 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007713 Diag(CurrentLocation, diag::note_member_synthesized_at)
7714 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7715 CopyAssignOperator->setInvalidDecl();
7716 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007717 }
7718
7719 // Success! Record the copy.
7720 Statements.push_back(Copy.takeAs<Expr>());
7721 }
7722
7723 // \brief Reference to the __builtin_memcpy function.
7724 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007725 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007726 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007727
7728 // Assign non-static members.
7729 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7730 FieldEnd = ClassDecl->field_end();
7731 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007732 if (Field->isUnnamedBitfield())
7733 continue;
7734
Douglas Gregor06a9f362010-05-01 20:49:11 +00007735 // Check for members of reference type; we can't copy those.
7736 if (Field->getType()->isReferenceType()) {
7737 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7738 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7739 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007740 Diag(CurrentLocation, diag::note_member_synthesized_at)
7741 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007742 Invalid = true;
7743 continue;
7744 }
7745
7746 // Check for members of const-qualified, non-class type.
7747 QualType BaseType = Context.getBaseElementType(Field->getType());
7748 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7749 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7750 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7751 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007752 Diag(CurrentLocation, diag::note_member_synthesized_at)
7753 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007754 Invalid = true;
7755 continue;
7756 }
John McCallb77115d2011-06-17 00:18:42 +00007757
7758 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007759 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7760 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007761
7762 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007763 if (FieldType->isIncompleteArrayType()) {
7764 assert(ClassDecl->hasFlexibleArrayMember() &&
7765 "Incomplete array type is not valid");
7766 continue;
7767 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007768
7769 // Build references to the field in the object we're copying from and to.
7770 CXXScopeSpec SS; // Intentionally empty
7771 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7772 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00007773 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007774 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007775 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007776 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007777 SS, SourceLocation(), 0,
7778 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007779 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007780 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007781 SS, SourceLocation(), 0,
7782 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007783 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7784 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7785
7786 // If the field should be copied with __builtin_memcpy rather than via
7787 // explicit assignments, do so. This optimization only applies for arrays
7788 // of scalars and arrays of class type with trivial copy-assignment
7789 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007790 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007791 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007792 // Compute the size of the memory buffer to be copied.
7793 QualType SizeType = Context.getSizeType();
7794 llvm::APInt Size(Context.getTypeSize(SizeType),
7795 Context.getTypeSizeInChars(BaseType).getQuantity());
7796 for (const ConstantArrayType *Array
7797 = Context.getAsConstantArrayType(FieldType);
7798 Array;
7799 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007800 llvm::APInt ArraySize
7801 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007802 Size *= ArraySize;
7803 }
7804
7805 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007806 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7807 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007808
7809 bool NeedsCollectableMemCpy =
7810 (BaseType->isRecordType() &&
7811 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7812
7813 if (NeedsCollectableMemCpy) {
7814 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007815 // Create a reference to the __builtin_objc_memmove_collectable function.
7816 LookupResult R(*this,
7817 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007818 Loc, LookupOrdinaryName);
7819 LookupName(R, TUScope, true);
7820
7821 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7822 if (!CollectableMemCpy) {
7823 // Something went horribly wrong earlier, and we will have
7824 // complained about it.
7825 Invalid = true;
7826 continue;
7827 }
7828
7829 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7830 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007831 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007832 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7833 }
7834 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007835 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007836 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007837 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7838 LookupOrdinaryName);
7839 LookupName(R, TUScope, true);
7840
7841 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7842 if (!BuiltinMemCpy) {
7843 // Something went horribly wrong earlier, and we will have complained
7844 // about it.
7845 Invalid = true;
7846 continue;
7847 }
7848
7849 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7850 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007851 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007852 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7853 }
7854
John McCallca0408f2010-08-23 06:44:23 +00007855 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007856 CallArgs.push_back(To.takeAs<Expr>());
7857 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007858 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007859 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007860 if (NeedsCollectableMemCpy)
7861 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007862 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007863 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007864 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007865 else
7866 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007867 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007868 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007869 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007870
Douglas Gregor06a9f362010-05-01 20:49:11 +00007871 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7872 Statements.push_back(Call.takeAs<Expr>());
7873 continue;
7874 }
7875
7876 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007877 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007878 To.get(), From.get(),
7879 /*CopyingBaseSubobject=*/false,
7880 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007881 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007882 Diag(CurrentLocation, diag::note_member_synthesized_at)
7883 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7884 CopyAssignOperator->setInvalidDecl();
7885 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007886 }
7887
7888 // Success! Record the copy.
7889 Statements.push_back(Copy.takeAs<Stmt>());
7890 }
7891
7892 if (!Invalid) {
7893 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007894 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007895
John McCall60d7b3a2010-08-24 06:29:42 +00007896 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007897 if (Return.isInvalid())
7898 Invalid = true;
7899 else {
7900 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007901
7902 if (Trap.hasErrorOccurred()) {
7903 Diag(CurrentLocation, diag::note_member_synthesized_at)
7904 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7905 Invalid = true;
7906 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007907 }
7908 }
7909
7910 if (Invalid) {
7911 CopyAssignOperator->setInvalidDecl();
7912 return;
7913 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007914
7915 StmtResult Body;
7916 {
7917 CompoundScopeRAII CompoundScope(*this);
7918 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7919 /*isStmtExpr=*/false);
7920 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7921 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007922 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007923
7924 if (ASTMutationListener *L = getASTMutationListener()) {
7925 L->CompletedImplicitDefinition(CopyAssignOperator);
7926 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007927}
7928
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007929Sema::ImplicitExceptionSpecification
7930Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
Richard Smithe6975e92012-04-17 00:58:00 +00007931 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007932
7933 if (ClassDecl->isInvalidDecl())
7934 return ExceptSpec;
7935
7936 // C++0x [except.spec]p14:
7937 // An implicitly declared special member function (Clause 12) shall have an
7938 // exception-specification. [...]
7939
7940 // It is unspecified whether or not an implicit move assignment operator
7941 // attempts to deduplicate calls to assignment operators of virtual bases are
7942 // made. As such, this exception specification is effectively unspecified.
7943 // Based on a similar decision made for constness in C++0x, we're erring on
7944 // the side of assuming such calls to be made regardless of whether they
7945 // actually happen.
7946 // Note that a move constructor is not implicitly declared when there are
7947 // virtual bases, but it can still be user-declared and explicitly defaulted.
7948 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7949 BaseEnd = ClassDecl->bases_end();
7950 Base != BaseEnd; ++Base) {
7951 if (Base->isVirtual())
7952 continue;
7953
7954 CXXRecordDecl *BaseClassDecl
7955 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7956 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7957 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007958 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007959 }
7960
7961 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7962 BaseEnd = ClassDecl->vbases_end();
7963 Base != BaseEnd; ++Base) {
7964 CXXRecordDecl *BaseClassDecl
7965 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7966 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7967 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007968 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007969 }
7970
7971 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7972 FieldEnd = ClassDecl->field_end();
7973 Field != FieldEnd;
7974 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007975 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007976 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7977 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
7978 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007979 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007980 }
7981 }
7982
7983 return ExceptSpec;
7984}
7985
Richard Smith1c931be2012-04-02 18:40:40 +00007986/// Determine whether the class type has any direct or indirect virtual base
7987/// classes which have a non-trivial move assignment operator.
7988static bool
7989hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
7990 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7991 BaseEnd = ClassDecl->vbases_end();
7992 Base != BaseEnd; ++Base) {
7993 CXXRecordDecl *BaseClass =
7994 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7995
7996 // Try to declare the move assignment. If it would be deleted, then the
7997 // class does not have a non-trivial move assignment.
7998 if (BaseClass->needsImplicitMoveAssignment())
7999 S.DeclareImplicitMoveAssignment(BaseClass);
8000
8001 // If the class has both a trivial move assignment and a non-trivial move
8002 // assignment, hasTrivialMoveAssignment() is false.
8003 if (BaseClass->hasDeclaredMoveAssignment() &&
8004 !BaseClass->hasTrivialMoveAssignment())
8005 return true;
8006 }
8007
8008 return false;
8009}
8010
8011/// Determine whether the given type either has a move constructor or is
8012/// trivially copyable.
8013static bool
8014hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8015 Type = S.Context.getBaseElementType(Type);
8016
8017 // FIXME: Technically, non-trivially-copyable non-class types, such as
8018 // reference types, are supposed to return false here, but that appears
8019 // to be a standard defect.
8020 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Richard Smith5d59b792012-04-25 18:28:49 +00008021 if (!ClassDecl || !ClassDecl->getDefinition())
Richard Smith1c931be2012-04-02 18:40:40 +00008022 return true;
8023
8024 if (Type.isTriviallyCopyableType(S.Context))
8025 return true;
8026
8027 if (IsConstructor) {
8028 if (ClassDecl->needsImplicitMoveConstructor())
8029 S.DeclareImplicitMoveConstructor(ClassDecl);
8030 return ClassDecl->hasDeclaredMoveConstructor();
8031 }
8032
8033 if (ClassDecl->needsImplicitMoveAssignment())
8034 S.DeclareImplicitMoveAssignment(ClassDecl);
8035 return ClassDecl->hasDeclaredMoveAssignment();
8036}
8037
8038/// Determine whether all non-static data members and direct or virtual bases
8039/// of class \p ClassDecl have either a move operation, or are trivially
8040/// copyable.
8041static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8042 bool IsConstructor) {
8043 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8044 BaseEnd = ClassDecl->bases_end();
8045 Base != BaseEnd; ++Base) {
8046 if (Base->isVirtual())
8047 continue;
8048
8049 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8050 return false;
8051 }
8052
8053 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8054 BaseEnd = ClassDecl->vbases_end();
8055 Base != BaseEnd; ++Base) {
8056 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8057 return false;
8058 }
8059
8060 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8061 FieldEnd = ClassDecl->field_end();
8062 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008063 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008064 return false;
8065 }
8066
8067 return true;
8068}
8069
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008070CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008071 // C++11 [class.copy]p20:
8072 // If the definition of a class X does not explicitly declare a move
8073 // assignment operator, one will be implicitly declared as defaulted
8074 // if and only if:
8075 //
8076 // - [first 4 bullets]
8077 assert(ClassDecl->needsImplicitMoveAssignment());
8078
8079 // [Checked after we build the declaration]
8080 // - the move assignment operator would not be implicitly defined as
8081 // deleted,
8082
8083 // [DR1402]:
8084 // - X has no direct or indirect virtual base class with a non-trivial
8085 // move assignment operator, and
8086 // - each of X's non-static data members and direct or virtual base classes
8087 // has a type that either has a move assignment operator or is trivially
8088 // copyable.
8089 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8090 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8091 ClassDecl->setFailedImplicitMoveAssignment();
8092 return 0;
8093 }
8094
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008095 // Note: The following rules are largely analoguous to the move
8096 // constructor rules.
8097
8098 ImplicitExceptionSpecification Spec(
8099 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8100
8101 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8102 QualType RetType = Context.getLValueReferenceType(ArgType);
8103 ArgType = Context.getRValueReferenceType(ArgType);
8104
8105 // An implicitly-declared move assignment operator is an inline public
8106 // member of its class.
8107 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8108 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8109 SourceLocation ClassLoc = ClassDecl->getLocation();
8110 DeclarationNameInfo NameInfo(Name, ClassLoc);
8111 CXXMethodDecl *MoveAssignment
8112 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8113 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8114 /*TInfo=*/0, /*isStatic=*/false,
8115 /*StorageClassAsWritten=*/SC_None,
8116 /*isInline=*/true,
8117 /*isConstexpr=*/false,
8118 SourceLocation());
8119 MoveAssignment->setAccess(AS_public);
8120 MoveAssignment->setDefaulted();
8121 MoveAssignment->setImplicit();
8122 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8123
8124 // Add the parameter to the operator.
8125 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8126 ClassLoc, ClassLoc, /*Id=*/0,
8127 ArgType, /*TInfo=*/0,
8128 SC_None,
8129 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008130 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008131
8132 // Note that we have added this copy-assignment operator.
8133 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8134
8135 // C++0x [class.copy]p9:
8136 // If the definition of a class X does not explicitly declare a move
8137 // assignment operator, one will be implicitly declared as defaulted if and
8138 // only if:
8139 // [...]
8140 // - the move assignment operator would not be implicitly defined as
8141 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008142 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008143 // Cache this result so that we don't try to generate this over and over
8144 // on every lookup, leaking memory and wasting time.
8145 ClassDecl->setFailedImplicitMoveAssignment();
8146 return 0;
8147 }
8148
8149 if (Scope *S = getScopeForContext(ClassDecl))
8150 PushOnScopeChains(MoveAssignment, S, false);
8151 ClassDecl->addDecl(MoveAssignment);
8152
8153 AddOverriddenMethods(ClassDecl, MoveAssignment);
8154 return MoveAssignment;
8155}
8156
8157void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8158 CXXMethodDecl *MoveAssignOperator) {
8159 assert((MoveAssignOperator->isDefaulted() &&
8160 MoveAssignOperator->isOverloadedOperator() &&
8161 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008162 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8163 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008164 "DefineImplicitMoveAssignment called for wrong function");
8165
8166 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8167
8168 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8169 MoveAssignOperator->setInvalidDecl();
8170 return;
8171 }
8172
8173 MoveAssignOperator->setUsed();
8174
8175 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8176 DiagnosticErrorTrap Trap(Diags);
8177
8178 // C++0x [class.copy]p28:
8179 // The implicitly-defined or move assignment operator for a non-union class
8180 // X performs memberwise move assignment of its subobjects. The direct base
8181 // classes of X are assigned first, in the order of their declaration in the
8182 // base-specifier-list, and then the immediate non-static data members of X
8183 // are assigned, in the order in which they were declared in the class
8184 // definition.
8185
8186 // The statements that form the synthesized function body.
8187 ASTOwningVector<Stmt*> Statements(*this);
8188
8189 // The parameter for the "other" object, which we are move from.
8190 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8191 QualType OtherRefType = Other->getType()->
8192 getAs<RValueReferenceType>()->getPointeeType();
8193 assert(OtherRefType.getQualifiers() == 0 &&
8194 "Bad argument type of defaulted move assignment");
8195
8196 // Our location for everything implicitly-generated.
8197 SourceLocation Loc = MoveAssignOperator->getLocation();
8198
8199 // Construct a reference to the "other" object. We'll be using this
8200 // throughout the generated ASTs.
8201 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8202 assert(OtherRef && "Reference to parameter cannot fail!");
8203 // Cast to rvalue.
8204 OtherRef = CastForMoving(*this, OtherRef);
8205
8206 // Construct the "this" pointer. We'll be using this throughout the generated
8207 // ASTs.
8208 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8209 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008210
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008211 // Assign base classes.
8212 bool Invalid = false;
8213 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8214 E = ClassDecl->bases_end(); Base != E; ++Base) {
8215 // Form the assignment:
8216 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8217 QualType BaseType = Base->getType().getUnqualifiedType();
8218 if (!BaseType->isRecordType()) {
8219 Invalid = true;
8220 continue;
8221 }
8222
8223 CXXCastPath BasePath;
8224 BasePath.push_back(Base);
8225
8226 // Construct the "from" expression, which is an implicit cast to the
8227 // appropriately-qualified base type.
8228 Expr *From = OtherRef;
8229 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008230 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008231
8232 // Dereference "this".
8233 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8234
8235 // Implicitly cast "this" to the appropriately-qualified base type.
8236 To = ImpCastExprToType(To.take(),
8237 Context.getCVRQualifiedType(BaseType,
8238 MoveAssignOperator->getTypeQualifiers()),
8239 CK_UncheckedDerivedToBase,
8240 VK_LValue, &BasePath);
8241
8242 // Build the move.
8243 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8244 To.get(), From,
8245 /*CopyingBaseSubobject=*/true,
8246 /*Copying=*/false);
8247 if (Move.isInvalid()) {
8248 Diag(CurrentLocation, diag::note_member_synthesized_at)
8249 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8250 MoveAssignOperator->setInvalidDecl();
8251 return;
8252 }
8253
8254 // Success! Record the move.
8255 Statements.push_back(Move.takeAs<Expr>());
8256 }
8257
8258 // \brief Reference to the __builtin_memcpy function.
8259 Expr *BuiltinMemCpyRef = 0;
8260 // \brief Reference to the __builtin_objc_memmove_collectable function.
8261 Expr *CollectableMemCpyRef = 0;
8262
8263 // Assign non-static members.
8264 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8265 FieldEnd = ClassDecl->field_end();
8266 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008267 if (Field->isUnnamedBitfield())
8268 continue;
8269
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008270 // Check for members of reference type; we can't move those.
8271 if (Field->getType()->isReferenceType()) {
8272 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8273 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8274 Diag(Field->getLocation(), diag::note_declared_at);
8275 Diag(CurrentLocation, diag::note_member_synthesized_at)
8276 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8277 Invalid = true;
8278 continue;
8279 }
8280
8281 // Check for members of const-qualified, non-class type.
8282 QualType BaseType = Context.getBaseElementType(Field->getType());
8283 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8284 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8285 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8286 Diag(Field->getLocation(), diag::note_declared_at);
8287 Diag(CurrentLocation, diag::note_member_synthesized_at)
8288 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8289 Invalid = true;
8290 continue;
8291 }
8292
8293 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008294 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8295 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008296
8297 QualType FieldType = Field->getType().getNonReferenceType();
8298 if (FieldType->isIncompleteArrayType()) {
8299 assert(ClassDecl->hasFlexibleArrayMember() &&
8300 "Incomplete array type is not valid");
8301 continue;
8302 }
8303
8304 // Build references to the field in the object we're copying from and to.
8305 CXXScopeSpec SS; // Intentionally empty
8306 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8307 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008308 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008309 MemberLookup.resolveKind();
8310 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8311 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008312 SS, SourceLocation(), 0,
8313 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008314 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8315 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008316 SS, SourceLocation(), 0,
8317 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008318 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8319 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8320
8321 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8322 "Member reference with rvalue base must be rvalue except for reference "
8323 "members, which aren't allowed for move assignment.");
8324
8325 // If the field should be copied with __builtin_memcpy rather than via
8326 // explicit assignments, do so. This optimization only applies for arrays
8327 // of scalars and arrays of class type with trivial move-assignment
8328 // operators.
8329 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8330 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8331 // Compute the size of the memory buffer to be copied.
8332 QualType SizeType = Context.getSizeType();
8333 llvm::APInt Size(Context.getTypeSize(SizeType),
8334 Context.getTypeSizeInChars(BaseType).getQuantity());
8335 for (const ConstantArrayType *Array
8336 = Context.getAsConstantArrayType(FieldType);
8337 Array;
8338 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8339 llvm::APInt ArraySize
8340 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8341 Size *= ArraySize;
8342 }
8343
Douglas Gregor45d3d712011-09-01 02:09:07 +00008344 // Take the address of the field references for "from" and "to". We
8345 // directly construct UnaryOperators here because semantic analysis
8346 // does not permit us to take the address of an xvalue.
8347 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8348 Context.getPointerType(From.get()->getType()),
8349 VK_RValue, OK_Ordinary, Loc);
8350 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8351 Context.getPointerType(To.get()->getType()),
8352 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008353
8354 bool NeedsCollectableMemCpy =
8355 (BaseType->isRecordType() &&
8356 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8357
8358 if (NeedsCollectableMemCpy) {
8359 if (!CollectableMemCpyRef) {
8360 // Create a reference to the __builtin_objc_memmove_collectable function.
8361 LookupResult R(*this,
8362 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8363 Loc, LookupOrdinaryName);
8364 LookupName(R, TUScope, true);
8365
8366 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8367 if (!CollectableMemCpy) {
8368 // Something went horribly wrong earlier, and we will have
8369 // complained about it.
8370 Invalid = true;
8371 continue;
8372 }
8373
8374 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8375 CollectableMemCpy->getType(),
8376 VK_LValue, Loc, 0).take();
8377 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8378 }
8379 }
8380 // Create a reference to the __builtin_memcpy builtin function.
8381 else if (!BuiltinMemCpyRef) {
8382 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8383 LookupOrdinaryName);
8384 LookupName(R, TUScope, true);
8385
8386 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8387 if (!BuiltinMemCpy) {
8388 // Something went horribly wrong earlier, and we will have complained
8389 // about it.
8390 Invalid = true;
8391 continue;
8392 }
8393
8394 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8395 BuiltinMemCpy->getType(),
8396 VK_LValue, Loc, 0).take();
8397 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8398 }
8399
8400 ASTOwningVector<Expr*> CallArgs(*this);
8401 CallArgs.push_back(To.takeAs<Expr>());
8402 CallArgs.push_back(From.takeAs<Expr>());
8403 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8404 ExprResult Call = ExprError();
8405 if (NeedsCollectableMemCpy)
8406 Call = ActOnCallExpr(/*Scope=*/0,
8407 CollectableMemCpyRef,
8408 Loc, move_arg(CallArgs),
8409 Loc);
8410 else
8411 Call = ActOnCallExpr(/*Scope=*/0,
8412 BuiltinMemCpyRef,
8413 Loc, move_arg(CallArgs),
8414 Loc);
8415
8416 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8417 Statements.push_back(Call.takeAs<Expr>());
8418 continue;
8419 }
8420
8421 // Build the move of this field.
8422 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8423 To.get(), From.get(),
8424 /*CopyingBaseSubobject=*/false,
8425 /*Copying=*/false);
8426 if (Move.isInvalid()) {
8427 Diag(CurrentLocation, diag::note_member_synthesized_at)
8428 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8429 MoveAssignOperator->setInvalidDecl();
8430 return;
8431 }
8432
8433 // Success! Record the copy.
8434 Statements.push_back(Move.takeAs<Stmt>());
8435 }
8436
8437 if (!Invalid) {
8438 // Add a "return *this;"
8439 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8440
8441 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8442 if (Return.isInvalid())
8443 Invalid = true;
8444 else {
8445 Statements.push_back(Return.takeAs<Stmt>());
8446
8447 if (Trap.hasErrorOccurred()) {
8448 Diag(CurrentLocation, diag::note_member_synthesized_at)
8449 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8450 Invalid = true;
8451 }
8452 }
8453 }
8454
8455 if (Invalid) {
8456 MoveAssignOperator->setInvalidDecl();
8457 return;
8458 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008459
8460 StmtResult Body;
8461 {
8462 CompoundScopeRAII CompoundScope(*this);
8463 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8464 /*isStmtExpr=*/false);
8465 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8466 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008467 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8468
8469 if (ASTMutationListener *L = getASTMutationListener()) {
8470 L->CompletedImplicitDefinition(MoveAssignOperator);
8471 }
8472}
8473
Sean Hunt49634cf2011-05-13 06:10:58 +00008474std::pair<Sema::ImplicitExceptionSpecification, bool>
8475Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008476 if (ClassDecl->isInvalidDecl())
Richard Smith3003e1d2012-05-15 04:39:51 +00008477 return std::make_pair(ImplicitExceptionSpecification(*this), true);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008478
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008479 // C++ [class.copy]p5:
8480 // The implicitly-declared copy constructor for a class X will
8481 // have the form
8482 //
8483 // X::X(const X&)
8484 //
8485 // if
Sean Huntc530d172011-06-10 04:44:37 +00008486 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008487 bool HasConstCopyConstructor = true;
8488
8489 // -- each direct or virtual base class B of X has a copy
8490 // constructor whose first parameter is of type const B& or
8491 // const volatile B&, and
8492 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8493 BaseEnd = ClassDecl->bases_end();
8494 HasConstCopyConstructor && Base != BaseEnd;
8495 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008496 // Virtual bases are handled below.
8497 if (Base->isVirtual())
8498 continue;
8499
Douglas Gregor22584312010-07-02 23:41:54 +00008500 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008501 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smith704c8f72012-04-20 18:46:14 +00008502 HasConstCopyConstructor &=
8503 (bool)LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const);
Douglas Gregor598a8542010-07-01 18:27:03 +00008504 }
8505
8506 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8507 BaseEnd = ClassDecl->vbases_end();
8508 HasConstCopyConstructor && Base != BaseEnd;
8509 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008510 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008511 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smith704c8f72012-04-20 18:46:14 +00008512 HasConstCopyConstructor &=
8513 (bool)LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008514 }
8515
8516 // -- for all the nonstatic data members of X that are of a
8517 // class type M (or array thereof), each such class type
8518 // has a copy constructor whose first parameter is of type
8519 // const M& or const volatile M&.
8520 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8521 FieldEnd = ClassDecl->field_end();
8522 HasConstCopyConstructor && Field != FieldEnd;
8523 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008524 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008525 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith704c8f72012-04-20 18:46:14 +00008526 HasConstCopyConstructor &=
8527 (bool)LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008528 }
8529 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008530 // Otherwise, the implicitly declared copy constructor will have
8531 // the form
8532 //
8533 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008534
Douglas Gregor0d405db2010-07-01 20:59:04 +00008535 // C++ [except.spec]p14:
8536 // An implicitly declared special member function (Clause 12) shall have an
8537 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00008538 ImplicitExceptionSpecification ExceptSpec(*this);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008539 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8540 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8541 BaseEnd = ClassDecl->bases_end();
8542 Base != BaseEnd;
8543 ++Base) {
8544 // Virtual bases are handled below.
8545 if (Base->isVirtual())
8546 continue;
8547
Douglas Gregor22584312010-07-02 23:41:54 +00008548 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008549 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008550 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008551 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008552 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008553 }
8554 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8555 BaseEnd = ClassDecl->vbases_end();
8556 Base != BaseEnd;
8557 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008558 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008559 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008560 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008561 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008562 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008563 }
8564 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8565 FieldEnd = ClassDecl->field_end();
8566 Field != FieldEnd;
8567 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008568 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008569 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8570 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008571 LookupCopyingConstructor(FieldClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008572 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008573 }
8574 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008575
Sean Hunt49634cf2011-05-13 06:10:58 +00008576 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8577}
8578
8579CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8580 CXXRecordDecl *ClassDecl) {
8581 // C++ [class.copy]p4:
8582 // If the class definition does not explicitly declare a copy
8583 // constructor, one is declared implicitly.
8584
Richard Smithe6975e92012-04-17 00:58:00 +00008585 ImplicitExceptionSpecification Spec(*this);
Sean Hunt49634cf2011-05-13 06:10:58 +00008586 bool Const;
8587 llvm::tie(Spec, Const) =
8588 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8589
8590 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8591 QualType ArgType = ClassType;
8592 if (Const)
8593 ArgType = ArgType.withConst();
8594 ArgType = Context.getLValueReferenceType(ArgType);
8595
8596 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8597
Richard Smith7756afa2012-06-10 05:43:50 +00008598 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8599 CXXCopyConstructor,
8600 Const);
8601
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008602 DeclarationName Name
8603 = Context.DeclarationNames.getCXXConstructorName(
8604 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008605 SourceLocation ClassLoc = ClassDecl->getLocation();
8606 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008607
8608 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008609 // member of its class.
8610 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8611 Context, ClassDecl, ClassLoc, NameInfo,
8612 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8613 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008614 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008615 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008616 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008617 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008618
Douglas Gregor22584312010-07-02 23:41:54 +00008619 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008620 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8621
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008622 // Add the parameter to the constructor.
8623 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008624 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008625 /*IdentifierInfo=*/0,
8626 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008627 SC_None,
8628 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008629 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008630
Douglas Gregor23c94db2010-07-02 17:43:08 +00008631 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008632 PushOnScopeChains(CopyConstructor, S, false);
8633 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008634
Nico Weberafcc96a2012-01-23 03:19:29 +00008635 // C++11 [class.copy]p8:
8636 // ... If the class definition does not explicitly declare a copy
8637 // constructor, there is no user-declared move constructor, and there is no
8638 // user-declared move assignment operator, a copy constructor is implicitly
8639 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008640 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008641 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008642
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008643 return CopyConstructor;
8644}
8645
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008646void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008647 CXXConstructorDecl *CopyConstructor) {
8648 assert((CopyConstructor->isDefaulted() &&
8649 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008650 !CopyConstructor->doesThisDeclarationHaveABody() &&
8651 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008652 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008653
Anders Carlsson63010a72010-04-23 16:24:12 +00008654 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008655 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008656
Douglas Gregor39957dc2010-05-01 15:04:51 +00008657 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008658 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008659
Sean Huntcbb67482011-01-08 20:30:50 +00008660 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008661 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008662 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008663 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008664 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008665 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008666 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008667 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8668 CopyConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008669 MultiStmtArg(*this, 0, 0),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008670 /*isStmtExpr=*/false)
8671 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008672 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008673 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008674
8675 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008676 if (ASTMutationListener *L = getASTMutationListener()) {
8677 L->CompletedImplicitDefinition(CopyConstructor);
8678 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008679}
8680
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008681Sema::ImplicitExceptionSpecification
8682Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8683 // C++ [except.spec]p14:
8684 // An implicitly declared special member function (Clause 12) shall have an
8685 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00008686 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008687 if (ClassDecl->isInvalidDecl())
8688 return ExceptSpec;
8689
8690 // Direct base-class constructors.
8691 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8692 BEnd = ClassDecl->bases_end();
8693 B != BEnd; ++B) {
8694 if (B->isVirtual()) // Handled below.
8695 continue;
8696
8697 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8698 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8699 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8700 // If this is a deleted function, add it anyway. This might be conformant
8701 // with the standard. This might not. I'm not sure. It might not matter.
8702 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008703 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008704 }
8705 }
8706
8707 // Virtual base-class constructors.
8708 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8709 BEnd = ClassDecl->vbases_end();
8710 B != BEnd; ++B) {
8711 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8712 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8713 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8714 // If this is a deleted function, add it anyway. This might be conformant
8715 // with the standard. This might not. I'm not sure. It might not matter.
8716 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008717 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008718 }
8719 }
8720
8721 // Field constructors.
8722 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8723 FEnd = ClassDecl->field_end();
8724 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008725 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008726 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8727 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8728 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8729 // If this is a deleted function, add it anyway. This might be conformant
8730 // with the standard. This might not. I'm not sure. It might not matter.
8731 // In particular, the problem is that this function never gets called. It
8732 // might just be ill-formed because this function attempts to refer to
8733 // a deleted function here.
8734 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008735 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008736 }
8737 }
8738
8739 return ExceptSpec;
8740}
8741
8742CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8743 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008744 // C++11 [class.copy]p9:
8745 // If the definition of a class X does not explicitly declare a move
8746 // constructor, one will be implicitly declared as defaulted if and only if:
8747 //
8748 // - [first 4 bullets]
8749 assert(ClassDecl->needsImplicitMoveConstructor());
8750
8751 // [Checked after we build the declaration]
8752 // - the move assignment operator would not be implicitly defined as
8753 // deleted,
8754
8755 // [DR1402]:
8756 // - each of X's non-static data members and direct or virtual base classes
8757 // has a type that either has a move constructor or is trivially copyable.
8758 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8759 ClassDecl->setFailedImplicitMoveConstructor();
8760 return 0;
8761 }
8762
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008763 ImplicitExceptionSpecification Spec(
8764 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8765
8766 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8767 QualType ArgType = Context.getRValueReferenceType(ClassType);
8768
8769 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8770
Richard Smith7756afa2012-06-10 05:43:50 +00008771 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8772 CXXMoveConstructor,
8773 false);
8774
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008775 DeclarationName Name
8776 = Context.DeclarationNames.getCXXConstructorName(
8777 Context.getCanonicalType(ClassType));
8778 SourceLocation ClassLoc = ClassDecl->getLocation();
8779 DeclarationNameInfo NameInfo(Name, ClassLoc);
8780
8781 // C++0x [class.copy]p11:
8782 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008783 // member of its class.
8784 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8785 Context, ClassDecl, ClassLoc, NameInfo,
8786 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8787 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008788 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008789 MoveConstructor->setAccess(AS_public);
8790 MoveConstructor->setDefaulted();
8791 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008792
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008793 // Add the parameter to the constructor.
8794 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8795 ClassLoc, ClassLoc,
8796 /*IdentifierInfo=*/0,
8797 ArgType, /*TInfo=*/0,
8798 SC_None,
8799 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008800 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008801
8802 // C++0x [class.copy]p9:
8803 // If the definition of a class X does not explicitly declare a move
8804 // constructor, one will be implicitly declared as defaulted if and only if:
8805 // [...]
8806 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008807 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008808 // Cache this result so that we don't try to generate this over and over
8809 // on every lookup, leaking memory and wasting time.
8810 ClassDecl->setFailedImplicitMoveConstructor();
8811 return 0;
8812 }
8813
8814 // Note that we have declared this constructor.
8815 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8816
8817 if (Scope *S = getScopeForContext(ClassDecl))
8818 PushOnScopeChains(MoveConstructor, S, false);
8819 ClassDecl->addDecl(MoveConstructor);
8820
8821 return MoveConstructor;
8822}
8823
8824void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8825 CXXConstructorDecl *MoveConstructor) {
8826 assert((MoveConstructor->isDefaulted() &&
8827 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008828 !MoveConstructor->doesThisDeclarationHaveABody() &&
8829 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008830 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8831
8832 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8833 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8834
8835 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8836 DiagnosticErrorTrap Trap(Diags);
8837
8838 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8839 Trap.hasErrorOccurred()) {
8840 Diag(CurrentLocation, diag::note_member_synthesized_at)
8841 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8842 MoveConstructor->setInvalidDecl();
8843 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008844 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008845 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8846 MoveConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008847 MultiStmtArg(*this, 0, 0),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008848 /*isStmtExpr=*/false)
8849 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008850 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008851 }
8852
8853 MoveConstructor->setUsed();
8854
8855 if (ASTMutationListener *L = getASTMutationListener()) {
8856 L->CompletedImplicitDefinition(MoveConstructor);
8857 }
8858}
8859
Douglas Gregore4e68d42012-02-15 19:33:52 +00008860bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8861 return FD->isDeleted() &&
8862 (FD->isDefaulted() || FD->isImplicit()) &&
8863 isa<CXXMethodDecl>(FD);
8864}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008865
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008866/// \brief Mark the call operator of the given lambda closure type as "used".
8867static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8868 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00008869 = cast<CXXMethodDecl>(
8870 *Lambda->lookup(
8871 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008872 CallOperator->setReferenced();
8873 CallOperator->setUsed();
8874}
8875
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008876void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8877 SourceLocation CurrentLocation,
8878 CXXConversionDecl *Conv)
8879{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008880 CXXRecordDecl *Lambda = Conv->getParent();
8881
8882 // Make sure that the lambda call operator is marked used.
8883 markLambdaCallOperatorUsed(*this, Lambda);
8884
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008885 Conv->setUsed();
8886
8887 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8888 DiagnosticErrorTrap Trap(Diags);
8889
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008890 // Return the address of the __invoke function.
8891 DeclarationName InvokeName = &Context.Idents.get("__invoke");
8892 CXXMethodDecl *Invoke
8893 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8894 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8895 VK_LValue, Conv->getLocation()).take();
8896 assert(FunctionRef && "Can't refer to __invoke function?");
8897 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8898 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8899 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008900 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008901
8902 // Fill in the __invoke function with a dummy implementation. IR generation
8903 // will fill in the actual details.
8904 Invoke->setUsed();
8905 Invoke->setReferenced();
8906 Invoke->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocation(),
8907 Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008908
8909 if (ASTMutationListener *L = getASTMutationListener()) {
8910 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008911 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008912 }
8913}
8914
8915void Sema::DefineImplicitLambdaToBlockPointerConversion(
8916 SourceLocation CurrentLocation,
8917 CXXConversionDecl *Conv)
8918{
8919 Conv->setUsed();
8920
8921 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8922 DiagnosticErrorTrap Trap(Diags);
8923
Douglas Gregorac1303e2012-02-22 05:02:47 +00008924 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008925 Expr *This = ActOnCXXThis(CurrentLocation).take();
8926 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008927
Eli Friedman23f02672012-03-01 04:01:32 +00008928 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8929 Conv->getLocation(),
8930 Conv, DerefThis);
8931
8932 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8933 // behavior. Note that only the general conversion function does this
8934 // (since it's unusable otherwise); in the case where we inline the
8935 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00008936 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00008937 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
8938 CK_CopyAndAutoreleaseBlockObject,
8939 BuildBlock.get(), 0, VK_RValue);
8940
8941 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008942 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00008943 Conv->setInvalidDecl();
8944 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008945 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00008946
Douglas Gregorac1303e2012-02-22 05:02:47 +00008947 // Create the return statement that returns the block from the conversion
8948 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00008949 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00008950 if (Return.isInvalid()) {
8951 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
8952 Conv->setInvalidDecl();
8953 return;
8954 }
8955
8956 // Set the body of the conversion function.
8957 Stmt *ReturnS = Return.take();
8958 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
8959 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008960 Conv->getLocation()));
8961
Douglas Gregorac1303e2012-02-22 05:02:47 +00008962 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008963 if (ASTMutationListener *L = getASTMutationListener()) {
8964 L->CompletedImplicitDefinition(Conv);
8965 }
8966}
8967
Douglas Gregorf52757d2012-03-10 06:53:13 +00008968/// \brief Determine whether the given list arguments contains exactly one
8969/// "real" (non-default) argument.
8970static bool hasOneRealArgument(MultiExprArg Args) {
8971 switch (Args.size()) {
8972 case 0:
8973 return false;
8974
8975 default:
8976 if (!Args.get()[1]->isDefaultArgument())
8977 return false;
8978
8979 // fall through
8980 case 1:
8981 return !Args.get()[0]->isDefaultArgument();
8982 }
8983
8984 return false;
8985}
8986
John McCall60d7b3a2010-08-24 06:29:42 +00008987ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008988Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008989 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008990 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008991 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008992 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008993 unsigned ConstructKind,
8994 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008995 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008996
Douglas Gregor2f599792010-04-02 18:24:57 +00008997 // C++0x [class.copy]p34:
8998 // When certain criteria are met, an implementation is allowed to
8999 // omit the copy/move construction of a class object, even if the
9000 // copy/move constructor and/or destructor for the object have
9001 // side effects. [...]
9002 // - when a temporary class object that has not been bound to a
9003 // reference (12.2) would be copied/moved to a class object
9004 // with the same cv-unqualified type, the copy/move operation
9005 // can be omitted by constructing the temporary object
9006 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009007 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009008 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Douglas Gregor2f599792010-04-02 18:24:57 +00009009 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00009010 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009011 }
Mike Stump1eb44332009-09-09 15:08:12 +00009012
9013 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009014 Elidable, move(ExprArgs), HadMultipleCandidates,
9015 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009016}
9017
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009018/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9019/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009020ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009021Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9022 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009023 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009024 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009025 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009026 unsigned ConstructKind,
9027 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00009028 unsigned NumExprs = ExprArgs.size();
9029 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00009030
Eli Friedman5f2987c2012-02-02 03:46:19 +00009031 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009032 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009033 Constructor, Elidable, Exprs, NumExprs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009034 HadMultipleCandidates, /*FIXME*/false,
9035 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009036 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9037 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009038}
9039
Mike Stump1eb44332009-09-09 15:08:12 +00009040bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009041 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009042 MultiExprArg Exprs,
9043 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009044 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009045 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009046 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009047 move(Exprs), HadMultipleCandidates, false,
9048 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009049 if (TempResult.isInvalid())
9050 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009051
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009052 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009053 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009054 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009055 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009056 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009057
Anders Carlssonfe2de492009-08-25 05:18:00 +00009058 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009059}
9060
John McCall68c6c9a2010-02-02 09:10:11 +00009061void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009062 if (VD->isInvalidDecl()) return;
9063
John McCall68c6c9a2010-02-02 09:10:11 +00009064 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009065 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009066 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009067 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009068
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009069 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009070 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009071 CheckDestructorAccess(VD->getLocation(), Destructor,
9072 PDiag(diag::err_access_dtor_var)
9073 << VD->getDeclName()
9074 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009075 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009076
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009077 if (!VD->hasGlobalStorage()) return;
9078
9079 // Emit warning for non-trivial dtor in global scope (a real global,
9080 // class-static, function-static).
9081 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9082
9083 // TODO: this should be re-enabled for static locals by !CXAAtExit
9084 if (!VD->isStaticLocal())
9085 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009086}
9087
Douglas Gregor39da0b82009-09-09 23:08:42 +00009088/// \brief Given a constructor and the set of arguments provided for the
9089/// constructor, convert the arguments and add any required default arguments
9090/// to form a proper call to this constructor.
9091///
9092/// \returns true if an error occurred, false otherwise.
9093bool
9094Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9095 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009096 SourceLocation Loc,
Douglas Gregored878af2012-02-24 23:56:31 +00009097 ASTOwningVector<Expr*> &ConvertedArgs,
9098 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009099 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9100 unsigned NumArgs = ArgsPtr.size();
9101 Expr **Args = (Expr **)ArgsPtr.get();
9102
9103 const FunctionProtoType *Proto
9104 = Constructor->getType()->getAs<FunctionProtoType>();
9105 assert(Proto && "Constructor without a prototype?");
9106 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009107
9108 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009109 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009110 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009111 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009112 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009113
9114 VariadicCallType CallType =
9115 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009116 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009117 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9118 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009119 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009120 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009121
9122 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9123
Richard Smith831421f2012-06-25 20:30:08 +00009124 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9125 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009126
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009127 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009128}
9129
Anders Carlsson20d45d22009-12-12 00:32:00 +00009130static inline bool
9131CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9132 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009133 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009134 if (isa<NamespaceDecl>(DC)) {
9135 return SemaRef.Diag(FnDecl->getLocation(),
9136 diag::err_operator_new_delete_declared_in_namespace)
9137 << FnDecl->getDeclName();
9138 }
9139
9140 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009141 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009142 return SemaRef.Diag(FnDecl->getLocation(),
9143 diag::err_operator_new_delete_declared_static)
9144 << FnDecl->getDeclName();
9145 }
9146
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009147 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009148}
9149
Anders Carlsson156c78e2009-12-13 17:53:43 +00009150static inline bool
9151CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9152 CanQualType ExpectedResultType,
9153 CanQualType ExpectedFirstParamType,
9154 unsigned DependentParamTypeDiag,
9155 unsigned InvalidParamTypeDiag) {
9156 QualType ResultType =
9157 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9158
9159 // Check that the result type is not dependent.
9160 if (ResultType->isDependentType())
9161 return SemaRef.Diag(FnDecl->getLocation(),
9162 diag::err_operator_new_delete_dependent_result_type)
9163 << FnDecl->getDeclName() << ExpectedResultType;
9164
9165 // Check that the result type is what we expect.
9166 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9167 return SemaRef.Diag(FnDecl->getLocation(),
9168 diag::err_operator_new_delete_invalid_result_type)
9169 << FnDecl->getDeclName() << ExpectedResultType;
9170
9171 // A function template must have at least 2 parameters.
9172 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9173 return SemaRef.Diag(FnDecl->getLocation(),
9174 diag::err_operator_new_delete_template_too_few_parameters)
9175 << FnDecl->getDeclName();
9176
9177 // The function decl must have at least 1 parameter.
9178 if (FnDecl->getNumParams() == 0)
9179 return SemaRef.Diag(FnDecl->getLocation(),
9180 diag::err_operator_new_delete_too_few_parameters)
9181 << FnDecl->getDeclName();
9182
9183 // Check the the first parameter type is not dependent.
9184 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9185 if (FirstParamType->isDependentType())
9186 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9187 << FnDecl->getDeclName() << ExpectedFirstParamType;
9188
9189 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009190 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009191 ExpectedFirstParamType)
9192 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9193 << FnDecl->getDeclName() << ExpectedFirstParamType;
9194
9195 return false;
9196}
9197
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009198static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009199CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009200 // C++ [basic.stc.dynamic.allocation]p1:
9201 // A program is ill-formed if an allocation function is declared in a
9202 // namespace scope other than global scope or declared static in global
9203 // scope.
9204 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9205 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009206
9207 CanQualType SizeTy =
9208 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9209
9210 // C++ [basic.stc.dynamic.allocation]p1:
9211 // The return type shall be void*. The first parameter shall have type
9212 // std::size_t.
9213 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9214 SizeTy,
9215 diag::err_operator_new_dependent_param_type,
9216 diag::err_operator_new_param_type))
9217 return true;
9218
9219 // C++ [basic.stc.dynamic.allocation]p1:
9220 // The first parameter shall not have an associated default argument.
9221 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009222 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009223 diag::err_operator_new_default_arg)
9224 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9225
9226 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009227}
9228
9229static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009230CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9231 // C++ [basic.stc.dynamic.deallocation]p1:
9232 // A program is ill-formed if deallocation functions are declared in a
9233 // namespace scope other than global scope or declared static in global
9234 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009235 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9236 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009237
9238 // C++ [basic.stc.dynamic.deallocation]p2:
9239 // Each deallocation function shall return void and its first parameter
9240 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009241 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9242 SemaRef.Context.VoidPtrTy,
9243 diag::err_operator_delete_dependent_param_type,
9244 diag::err_operator_delete_param_type))
9245 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009246
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009247 return false;
9248}
9249
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009250/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9251/// of this overloaded operator is well-formed. If so, returns false;
9252/// otherwise, emits appropriate diagnostics and returns true.
9253bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009254 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009255 "Expected an overloaded operator declaration");
9256
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009257 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9258
Mike Stump1eb44332009-09-09 15:08:12 +00009259 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009260 // The allocation and deallocation functions, operator new,
9261 // operator new[], operator delete and operator delete[], are
9262 // described completely in 3.7.3. The attributes and restrictions
9263 // found in the rest of this subclause do not apply to them unless
9264 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009265 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009266 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009267
Anders Carlssona3ccda52009-12-12 00:26:23 +00009268 if (Op == OO_New || Op == OO_Array_New)
9269 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009270
9271 // C++ [over.oper]p6:
9272 // An operator function shall either be a non-static member
9273 // function or be a non-member function and have at least one
9274 // parameter whose type is a class, a reference to a class, an
9275 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009276 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9277 if (MethodDecl->isStatic())
9278 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009279 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009280 } else {
9281 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009282 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9283 ParamEnd = FnDecl->param_end();
9284 Param != ParamEnd; ++Param) {
9285 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009286 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9287 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009288 ClassOrEnumParam = true;
9289 break;
9290 }
9291 }
9292
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009293 if (!ClassOrEnumParam)
9294 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009295 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009296 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009297 }
9298
9299 // C++ [over.oper]p8:
9300 // An operator function cannot have default arguments (8.3.6),
9301 // except where explicitly stated below.
9302 //
Mike Stump1eb44332009-09-09 15:08:12 +00009303 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009304 // (C++ [over.call]p1).
9305 if (Op != OO_Call) {
9306 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9307 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009308 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009309 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009310 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009311 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009312 }
9313 }
9314
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009315 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9316 { false, false, false }
9317#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9318 , { Unary, Binary, MemberOnly }
9319#include "clang/Basic/OperatorKinds.def"
9320 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009321
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009322 bool CanBeUnaryOperator = OperatorUses[Op][0];
9323 bool CanBeBinaryOperator = OperatorUses[Op][1];
9324 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009325
9326 // C++ [over.oper]p8:
9327 // [...] Operator functions cannot have more or fewer parameters
9328 // than the number required for the corresponding operator, as
9329 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009330 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009331 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009332 if (Op != OO_Call &&
9333 ((NumParams == 1 && !CanBeUnaryOperator) ||
9334 (NumParams == 2 && !CanBeBinaryOperator) ||
9335 (NumParams < 1) || (NumParams > 2))) {
9336 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009337 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009338 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009339 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009340 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009341 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009342 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009343 assert(CanBeBinaryOperator &&
9344 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009345 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009346 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009347
Chris Lattner416e46f2008-11-21 07:57:12 +00009348 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009349 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009350 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009351
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009352 // Overloaded operators other than operator() cannot be variadic.
9353 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009354 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009355 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009356 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009357 }
9358
9359 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009360 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9361 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009362 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009363 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009364 }
9365
9366 // C++ [over.inc]p1:
9367 // The user-defined function called operator++ implements the
9368 // prefix and postfix ++ operator. If this function is a member
9369 // function with no parameters, or a non-member function with one
9370 // parameter of class or enumeration type, it defines the prefix
9371 // increment operator ++ for objects of that type. If the function
9372 // is a member function with one parameter (which shall be of type
9373 // int) or a non-member function with two parameters (the second
9374 // of which shall be of type int), it defines the postfix
9375 // increment operator ++ for objects of that type.
9376 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9377 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9378 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009379 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009380 ParamIsInt = BT->getKind() == BuiltinType::Int;
9381
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009382 if (!ParamIsInt)
9383 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009384 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009385 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009386 }
9387
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009388 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009389}
Chris Lattner5a003a42008-12-17 07:09:26 +00009390
Sean Hunta6c058d2010-01-13 09:01:02 +00009391/// CheckLiteralOperatorDeclaration - Check whether the declaration
9392/// of this literal operator function is well-formed. If so, returns
9393/// false; otherwise, emits appropriate diagnostics and returns true.
9394bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009395 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009396 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9397 << FnDecl->getDeclName();
9398 return true;
9399 }
9400
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009401 if (FnDecl->isExternC()) {
9402 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9403 return true;
9404 }
9405
Sean Hunta6c058d2010-01-13 09:01:02 +00009406 bool Valid = false;
9407
Richard Smith36f5cfe2012-03-09 08:00:36 +00009408 // This might be the definition of a literal operator template.
9409 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9410 // This might be a specialization of a literal operator template.
9411 if (!TpDecl)
9412 TpDecl = FnDecl->getPrimaryTemplate();
9413
Sean Hunt216c2782010-04-07 23:11:06 +00009414 // template <char...> type operator "" name() is the only valid template
9415 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009416 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009417 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009418 // Must have only one template parameter
9419 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9420 if (Params->size() == 1) {
9421 NonTypeTemplateParmDecl *PmDecl =
9422 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009423
Sean Hunt216c2782010-04-07 23:11:06 +00009424 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009425 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9426 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9427 Valid = true;
9428 }
9429 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009430 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009431 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009432 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9433
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009434 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009435
Sean Hunt30019c02010-04-07 22:57:35 +00009436 // unsigned long long int, long double, and any character type are allowed
9437 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009438 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9439 Context.hasSameType(T, Context.LongDoubleTy) ||
9440 Context.hasSameType(T, Context.CharTy) ||
9441 Context.hasSameType(T, Context.WCharTy) ||
9442 Context.hasSameType(T, Context.Char16Ty) ||
9443 Context.hasSameType(T, Context.Char32Ty)) {
9444 if (++Param == FnDecl->param_end())
9445 Valid = true;
9446 goto FinishedParams;
9447 }
9448
Sean Hunt30019c02010-04-07 22:57:35 +00009449 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009450 const PointerType *PT = T->getAs<PointerType>();
9451 if (!PT)
9452 goto FinishedParams;
9453 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009454 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009455 goto FinishedParams;
9456 T = T.getUnqualifiedType();
9457
9458 // Move on to the second parameter;
9459 ++Param;
9460
9461 // If there is no second parameter, the first must be a const char *
9462 if (Param == FnDecl->param_end()) {
9463 if (Context.hasSameType(T, Context.CharTy))
9464 Valid = true;
9465 goto FinishedParams;
9466 }
9467
9468 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9469 // are allowed as the first parameter to a two-parameter function
9470 if (!(Context.hasSameType(T, Context.CharTy) ||
9471 Context.hasSameType(T, Context.WCharTy) ||
9472 Context.hasSameType(T, Context.Char16Ty) ||
9473 Context.hasSameType(T, Context.Char32Ty)))
9474 goto FinishedParams;
9475
9476 // The second and final parameter must be an std::size_t
9477 T = (*Param)->getType().getUnqualifiedType();
9478 if (Context.hasSameType(T, Context.getSizeType()) &&
9479 ++Param == FnDecl->param_end())
9480 Valid = true;
9481 }
9482
9483 // FIXME: This diagnostic is absolutely terrible.
9484FinishedParams:
9485 if (!Valid) {
9486 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9487 << FnDecl->getDeclName();
9488 return true;
9489 }
9490
Richard Smitha9e88b22012-03-09 08:16:22 +00009491 // A parameter-declaration-clause containing a default argument is not
9492 // equivalent to any of the permitted forms.
9493 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9494 ParamEnd = FnDecl->param_end();
9495 Param != ParamEnd; ++Param) {
9496 if ((*Param)->hasDefaultArg()) {
9497 Diag((*Param)->getDefaultArgRange().getBegin(),
9498 diag::err_literal_operator_default_argument)
9499 << (*Param)->getDefaultArgRange();
9500 break;
9501 }
9502 }
9503
Richard Smith2fb4ae32012-03-08 02:39:21 +00009504 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +00009505 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9506 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +00009507 // C++11 [usrlit.suffix]p1:
9508 // Literal suffix identifiers that do not start with an underscore
9509 // are reserved for future standardization.
9510 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +00009511 }
Richard Smith2fb4ae32012-03-08 02:39:21 +00009512
Sean Hunta6c058d2010-01-13 09:01:02 +00009513 return false;
9514}
9515
Douglas Gregor074149e2009-01-05 19:45:36 +00009516/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9517/// linkage specification, including the language and (if present)
9518/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9519/// the location of the language string literal, which is provided
9520/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9521/// the '{' brace. Otherwise, this linkage specification does not
9522/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009523Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9524 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009525 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009526 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009527 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009528 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009529 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009530 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009531 Language = LinkageSpecDecl::lang_cxx;
9532 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009533 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009534 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009535 }
Mike Stump1eb44332009-09-09 15:08:12 +00009536
Chris Lattnercc98eac2008-12-17 07:13:27 +00009537 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009538
Douglas Gregor074149e2009-01-05 19:45:36 +00009539 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009540 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009541 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009542 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009543 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009544}
9545
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009546/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009547/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9548/// valid, it's the position of the closing '}' brace in a linkage
9549/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009550Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009551 Decl *LinkageSpec,
9552 SourceLocation RBraceLoc) {
9553 if (LinkageSpec) {
9554 if (RBraceLoc.isValid()) {
9555 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9556 LSDecl->setRBraceLoc(RBraceLoc);
9557 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009558 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009559 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009560 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009561}
9562
Douglas Gregord308e622009-05-18 20:51:54 +00009563/// \brief Perform semantic analysis for the variable declaration that
9564/// occurs within a C++ catch clause, returning the newly-created
9565/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009566VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009567 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009568 SourceLocation StartLoc,
9569 SourceLocation Loc,
9570 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009571 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009572 QualType ExDeclType = TInfo->getType();
9573
Sebastian Redl4b07b292008-12-22 19:15:10 +00009574 // Arrays and functions decay.
9575 if (ExDeclType->isArrayType())
9576 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9577 else if (ExDeclType->isFunctionType())
9578 ExDeclType = Context.getPointerType(ExDeclType);
9579
9580 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9581 // The exception-declaration shall not denote a pointer or reference to an
9582 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009583 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009584 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009585 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009586 Invalid = true;
9587 }
Douglas Gregord308e622009-05-18 20:51:54 +00009588
Sebastian Redl4b07b292008-12-22 19:15:10 +00009589 QualType BaseType = ExDeclType;
9590 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009591 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009592 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009593 BaseType = Ptr->getPointeeType();
9594 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009595 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009596 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009597 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009598 BaseType = Ref->getPointeeType();
9599 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009600 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009601 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009602 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009603 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009604 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009605
Mike Stump1eb44332009-09-09 15:08:12 +00009606 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009607 RequireNonAbstractType(Loc, ExDeclType,
9608 diag::err_abstract_type_in_decl,
9609 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009610 Invalid = true;
9611
John McCall5a180392010-07-24 00:37:23 +00009612 // Only the non-fragile NeXT runtime currently supports C++ catches
9613 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +00009614 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +00009615 QualType T = ExDeclType;
9616 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9617 T = RT->getPointeeType();
9618
9619 if (T->isObjCObjectType()) {
9620 Diag(Loc, diag::err_objc_object_catch);
9621 Invalid = true;
9622 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +00009623 // FIXME: should this be a test for macosx-fragile specifically?
9624 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009625 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009626 }
9627 }
9628
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009629 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9630 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009631 ExDecl->setExceptionVariable(true);
9632
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009633 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00009634 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009635 Invalid = true;
9636
Douglas Gregorc41b8782011-07-06 18:14:43 +00009637 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009638 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009639 // C++ [except.handle]p16:
9640 // The object declared in an exception-declaration or, if the
9641 // exception-declaration does not specify a name, a temporary (12.2) is
9642 // copy-initialized (8.5) from the exception object. [...]
9643 // The object is destroyed when the handler exits, after the destruction
9644 // of any automatic objects initialized within the handler.
9645 //
9646 // We just pretend to initialize the object with itself, then make sure
9647 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009648 QualType initType = ExDeclType;
9649
9650 InitializedEntity entity =
9651 InitializedEntity::InitializeVariable(ExDecl);
9652 InitializationKind initKind =
9653 InitializationKind::CreateCopy(Loc, SourceLocation());
9654
9655 Expr *opaqueValue =
9656 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9657 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9658 ExprResult result = sequence.Perform(*this, entity, initKind,
9659 MultiExprArg(&opaqueValue, 1));
9660 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009661 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009662 else {
9663 // If the constructor used was non-trivial, set this as the
9664 // "initializer".
9665 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9666 if (!construct->getConstructor()->isTrivial()) {
9667 Expr *init = MaybeCreateExprWithCleanups(construct);
9668 ExDecl->setInit(init);
9669 }
9670
9671 // And make sure it's destructable.
9672 FinalizeVarWithDestructor(ExDecl, recordType);
9673 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009674 }
9675 }
9676
Douglas Gregord308e622009-05-18 20:51:54 +00009677 if (Invalid)
9678 ExDecl->setInvalidDecl();
9679
9680 return ExDecl;
9681}
9682
9683/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9684/// handler.
John McCalld226f652010-08-21 09:40:31 +00009685Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009686 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009687 bool Invalid = D.isInvalidType();
9688
9689 // Check for unexpanded parameter packs.
9690 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9691 UPPC_ExceptionType)) {
9692 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9693 D.getIdentifierLoc());
9694 Invalid = true;
9695 }
9696
Sebastian Redl4b07b292008-12-22 19:15:10 +00009697 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009698 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009699 LookupOrdinaryName,
9700 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009701 // The scope should be freshly made just for us. There is just no way
9702 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009703 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009704 if (PrevDecl->isTemplateParameter()) {
9705 // Maybe we will complain about the shadowed template parameter.
9706 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009707 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009708 }
9709 }
9710
Chris Lattnereaaebc72009-04-25 08:06:05 +00009711 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009712 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9713 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009714 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009715 }
9716
Douglas Gregor83cb9422010-09-09 17:09:21 +00009717 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009718 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009719 D.getIdentifierLoc(),
9720 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009721 if (Invalid)
9722 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009723
Sebastian Redl4b07b292008-12-22 19:15:10 +00009724 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009725 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009726 PushOnScopeChains(ExDecl, S);
9727 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009728 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009729
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009730 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009731 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009732}
Anders Carlssonfb311762009-03-14 00:25:26 +00009733
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009734Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009735 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009736 Expr *AssertMessageExpr_,
9737 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009738 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009739
Anders Carlssonc3082412009-03-14 00:33:21 +00009740 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smith282e7e62012-02-04 09:53:13 +00009741 // In a static_assert-declaration, the constant-expression shall be a
9742 // constant expression that can be contextually converted to bool.
9743 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9744 if (Converted.isInvalid())
9745 return 0;
9746
Richard Smithdaaefc52011-12-14 23:32:26 +00009747 llvm::APSInt Cond;
Richard Smith282e7e62012-02-04 09:53:13 +00009748 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009749 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +00009750 /*AllowFold=*/false).isInvalid())
John McCalld226f652010-08-21 09:40:31 +00009751 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009752
Richard Smith0cc323c2012-03-05 23:20:05 +00009753 if (!Cond) {
9754 llvm::SmallString<256> MsgBuffer;
9755 llvm::raw_svector_ostream Msg(MsgBuffer);
9756 AssertMessage->printPretty(Msg, Context, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009757 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +00009758 << Msg.str() << AssertExpr->getSourceRange();
9759 }
Anders Carlssonc3082412009-03-14 00:33:21 +00009760 }
Mike Stump1eb44332009-09-09 15:08:12 +00009761
Douglas Gregor399ad972010-12-15 23:55:21 +00009762 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9763 return 0;
9764
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009765 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9766 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009767
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009768 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009769 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009770}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009771
Douglas Gregor1d869352010-04-07 16:53:43 +00009772/// \brief Perform semantic analysis of the given friend type declaration.
9773///
9774/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009775FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9776 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009777 TypeSourceInfo *TSInfo) {
9778 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9779
9780 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009781 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009782
Richard Smith6b130222011-10-18 21:39:00 +00009783 // C++03 [class.friend]p2:
9784 // An elaborated-type-specifier shall be used in a friend declaration
9785 // for a class.*
9786 //
9787 // * The class-key of the elaborated-type-specifier is required.
9788 if (!ActiveTemplateInstantiations.empty()) {
9789 // Do not complain about the form of friend template types during
9790 // template instantiation; we will already have complained when the
9791 // template was declared.
9792 } else if (!T->isElaboratedTypeSpecifier()) {
9793 // If we evaluated the type to a record type, suggest putting
9794 // a tag in front.
9795 if (const RecordType *RT = T->getAs<RecordType>()) {
9796 RecordDecl *RD = RT->getDecl();
9797
9798 std::string InsertionText = std::string(" ") + RD->getKindName();
9799
9800 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +00009801 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009802 diag::warn_cxx98_compat_unelaborated_friend_type :
9803 diag::ext_unelaborated_friend_type)
9804 << (unsigned) RD->getTagKind()
9805 << T
9806 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9807 InsertionText);
9808 } else {
9809 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009810 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009811 diag::warn_cxx98_compat_nonclass_type_friend :
9812 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009813 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009814 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009815 }
Richard Smith6b130222011-10-18 21:39:00 +00009816 } else if (T->getAs<EnumType>()) {
9817 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009818 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009819 diag::warn_cxx98_compat_enum_friend :
9820 diag::ext_enum_friend)
9821 << T
9822 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009823 }
9824
Douglas Gregor06245bf2010-04-07 17:57:12 +00009825 // C++0x [class.friend]p3:
9826 // If the type specifier in a friend declaration designates a (possibly
9827 // cv-qualified) class type, that class is declared as a friend; otherwise,
9828 // the friend declaration is ignored.
9829
9830 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9831 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009832
Abramo Bagnara0216df82011-10-29 20:52:52 +00009833 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009834}
9835
John McCall9a34edb2010-10-19 01:40:49 +00009836/// Handle a friend tag declaration where the scope specifier was
9837/// templated.
9838Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9839 unsigned TagSpec, SourceLocation TagLoc,
9840 CXXScopeSpec &SS,
9841 IdentifierInfo *Name, SourceLocation NameLoc,
9842 AttributeList *Attr,
9843 MultiTemplateParamsArg TempParamLists) {
9844 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9845
9846 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009847 bool Invalid = false;
9848
9849 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009850 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009851 TempParamLists.get(),
9852 TempParamLists.size(),
9853 /*friend*/ true,
9854 isExplicitSpecialization,
9855 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009856 if (TemplateParams->size() > 0) {
9857 // This is a declaration of a class template.
9858 if (Invalid)
9859 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009860
Eric Christopher4110e132011-07-21 05:34:24 +00009861 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9862 SS, Name, NameLoc, Attr,
9863 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009864 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009865 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009866 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009867 } else {
9868 // The "template<>" header is extraneous.
9869 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9870 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9871 isExplicitSpecialization = true;
9872 }
9873 }
9874
9875 if (Invalid) return 0;
9876
John McCall9a34edb2010-10-19 01:40:49 +00009877 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009878 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009879 if (TempParamLists.get()[I]->size()) {
9880 isAllExplicitSpecializations = false;
9881 break;
9882 }
9883 }
9884
9885 // FIXME: don't ignore attributes.
9886
9887 // If it's explicit specializations all the way down, just forget
9888 // about the template header and build an appropriate non-templated
9889 // friend. TODO: for source fidelity, remember the headers.
9890 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009891 if (SS.isEmpty()) {
9892 bool Owned = false;
9893 bool IsDependent = false;
9894 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9895 Attr, AS_public,
9896 /*ModulePrivateLoc=*/SourceLocation(),
9897 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009898 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009899 /*ScopedEnumUsesClassTag=*/false,
9900 /*UnderlyingType=*/TypeResult());
9901 }
9902
Douglas Gregor2494dd02011-03-01 01:34:45 +00009903 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009904 ElaboratedTypeKeyword Keyword
9905 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009906 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009907 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009908 if (T.isNull())
9909 return 0;
9910
9911 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9912 if (isa<DependentNameType>(T)) {
9913 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009914 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009915 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009916 TL.setNameLoc(NameLoc);
9917 } else {
9918 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009919 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009920 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009921 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9922 }
9923
9924 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9925 TSI, FriendLoc);
9926 Friend->setAccess(AS_public);
9927 CurContext->addDecl(Friend);
9928 return Friend;
9929 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009930
9931 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9932
9933
John McCall9a34edb2010-10-19 01:40:49 +00009934
9935 // Handle the case of a templated-scope friend class. e.g.
9936 // template <class T> class A<T>::B;
9937 // FIXME: we don't support these right now.
9938 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9939 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9940 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9941 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009942 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009943 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009944 TL.setNameLoc(NameLoc);
9945
9946 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9947 TSI, FriendLoc);
9948 Friend->setAccess(AS_public);
9949 Friend->setUnsupportedFriend(true);
9950 CurContext->addDecl(Friend);
9951 return Friend;
9952}
9953
9954
John McCalldd4a3b02009-09-16 22:47:08 +00009955/// Handle a friend type declaration. This works in tandem with
9956/// ActOnTag.
9957///
9958/// Notes on friend class templates:
9959///
9960/// We generally treat friend class declarations as if they were
9961/// declaring a class. So, for example, the elaborated type specifier
9962/// in a friend declaration is required to obey the restrictions of a
9963/// class-head (i.e. no typedefs in the scope chain), template
9964/// parameters are required to match up with simple template-ids, &c.
9965/// However, unlike when declaring a template specialization, it's
9966/// okay to refer to a template specialization without an empty
9967/// template parameter declaration, e.g.
9968/// friend class A<T>::B<unsigned>;
9969/// We permit this as a special case; if there are any template
9970/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +00009971/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00009972Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00009973 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009974 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +00009975
9976 assert(DS.isFriendSpecified());
9977 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9978
John McCalldd4a3b02009-09-16 22:47:08 +00009979 // Try to convert the decl specifier to a type. This works for
9980 // friend templates because ActOnTag never produces a ClassTemplateDecl
9981 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00009982 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00009983 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9984 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00009985 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00009986 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009987
Douglas Gregor6ccab972010-12-16 01:14:37 +00009988 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9989 return 0;
9990
John McCalldd4a3b02009-09-16 22:47:08 +00009991 // This is definitely an error in C++98. It's probably meant to
9992 // be forbidden in C++0x, too, but the specification is just
9993 // poorly written.
9994 //
9995 // The problem is with declarations like the following:
9996 // template <T> friend A<T>::foo;
9997 // where deciding whether a class C is a friend or not now hinges
9998 // on whether there exists an instantiation of A that causes
9999 // 'foo' to equal C. There are restrictions on class-heads
10000 // (which we declare (by fiat) elaborated friend declarations to
10001 // be) that makes this tractable.
10002 //
10003 // FIXME: handle "template <> friend class A<T>;", which
10004 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010005 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010006 Diag(Loc, diag::err_tagless_friend_type_template)
10007 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010008 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010009 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010010
John McCall02cace72009-08-28 07:59:38 +000010011 // C++98 [class.friend]p1: A friend of a class is a function
10012 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010013 // This is fixed in DR77, which just barely didn't make the C++03
10014 // deadline. It's also a very silly restriction that seriously
10015 // affects inner classes and which nobody else seems to implement;
10016 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010017 //
10018 // But note that we could warn about it: it's always useless to
10019 // friend one of your own members (it's not, however, worthless to
10020 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010021
John McCalldd4a3b02009-09-16 22:47:08 +000010022 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010023 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010024 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010025 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010026 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010027 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010028 DS.getFriendSpecLoc());
10029 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010030 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010031
10032 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010033 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010034
John McCalldd4a3b02009-09-16 22:47:08 +000010035 D->setAccess(AS_public);
10036 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010037
John McCalld226f652010-08-21 09:40:31 +000010038 return D;
John McCall02cace72009-08-28 07:59:38 +000010039}
10040
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010041Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010042 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010043 const DeclSpec &DS = D.getDeclSpec();
10044
10045 assert(DS.isFriendSpecified());
10046 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10047
10048 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010049 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010050
10051 // C++ [class.friend]p1
10052 // A friend of a class is a function or class....
10053 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010054 // It *doesn't* see through dependent types, which is correct
10055 // according to [temp.arg.type]p3:
10056 // If a declaration acquires a function type through a
10057 // type dependent on a template-parameter and this causes
10058 // a declaration that does not use the syntactic form of a
10059 // function declarator to have a function type, the program
10060 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010061 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010062 Diag(Loc, diag::err_unexpected_friend);
10063
10064 // It might be worthwhile to try to recover by creating an
10065 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010066 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010067 }
10068
10069 // C++ [namespace.memdef]p3
10070 // - If a friend declaration in a non-local class first declares a
10071 // class or function, the friend class or function is a member
10072 // of the innermost enclosing namespace.
10073 // - The name of the friend is not found by simple name lookup
10074 // until a matching declaration is provided in that namespace
10075 // scope (either before or after the class declaration granting
10076 // friendship).
10077 // - If a friend function is called, its name may be found by the
10078 // name lookup that considers functions from namespaces and
10079 // classes associated with the types of the function arguments.
10080 // - When looking for a prior declaration of a class or a function
10081 // declared as a friend, scopes outside the innermost enclosing
10082 // namespace scope are not considered.
10083
John McCall337ec3d2010-10-12 23:13:28 +000010084 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010085 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10086 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010087 assert(Name);
10088
Douglas Gregor6ccab972010-12-16 01:14:37 +000010089 // Check for unexpanded parameter packs.
10090 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10091 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10092 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10093 return 0;
10094
John McCall67d1a672009-08-06 02:15:43 +000010095 // The context we found the declaration in, or in which we should
10096 // create the declaration.
10097 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010098 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010099 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010100 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010101
John McCall337ec3d2010-10-12 23:13:28 +000010102 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010103
John McCall337ec3d2010-10-12 23:13:28 +000010104 // There are four cases here.
10105 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010106 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010107 // there as appropriate.
10108 // Recover from invalid scope qualifiers as if they just weren't there.
10109 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010110 // C++0x [namespace.memdef]p3:
10111 // If the name in a friend declaration is neither qualified nor
10112 // a template-id and the declaration is a function or an
10113 // elaborated-type-specifier, the lookup to determine whether
10114 // the entity has been previously declared shall not consider
10115 // any scopes outside the innermost enclosing namespace.
10116 // C++0x [class.friend]p11:
10117 // If a friend declaration appears in a local class and the name
10118 // specified is an unqualified name, a prior declaration is
10119 // looked up without considering scopes that are outside the
10120 // innermost enclosing non-class scope. For a friend function
10121 // declaration, if there is no prior declaration, the program is
10122 // ill-formed.
10123 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010124 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010125
John McCall29ae6e52010-10-13 05:45:15 +000010126 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010127 DC = CurContext;
10128 while (true) {
10129 // Skip class contexts. If someone can cite chapter and verse
10130 // for this behavior, that would be nice --- it's what GCC and
10131 // EDG do, and it seems like a reasonable intent, but the spec
10132 // really only says that checks for unqualified existing
10133 // declarations should stop at the nearest enclosing namespace,
10134 // not that they should only consider the nearest enclosing
10135 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010136 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010137 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010138
John McCall68263142009-11-18 22:49:29 +000010139 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010140
10141 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010142 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010143 break;
John McCall29ae6e52010-10-13 05:45:15 +000010144
John McCall8a407372010-10-14 22:22:28 +000010145 if (isTemplateId) {
10146 if (isa<TranslationUnitDecl>(DC)) break;
10147 } else {
10148 if (DC->isFileContext()) break;
10149 }
John McCall67d1a672009-08-06 02:15:43 +000010150 DC = DC->getParent();
10151 }
10152
10153 // C++ [class.friend]p1: A friend of a class is a function or
10154 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010155 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010156 // Most C++ 98 compilers do seem to give an error here, so
10157 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010158 if (!Previous.empty() && DC->Equals(CurContext))
10159 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010160 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010161 diag::warn_cxx98_compat_friend_is_member :
10162 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010163
John McCall380aaa42010-10-13 06:22:15 +000010164 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010165
Douglas Gregor883af832011-10-10 01:11:59 +000010166 // C++ [class.friend]p6:
10167 // A function can be defined in a friend declaration of a class if and
10168 // only if the class is a non-local class (9.8), the function name is
10169 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010170 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010171 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10172 }
10173
John McCall337ec3d2010-10-12 23:13:28 +000010174 // - There's a non-dependent scope specifier, in which case we
10175 // compute it and do a previous lookup there for a function
10176 // or function template.
10177 } else if (!SS.getScopeRep()->isDependent()) {
10178 DC = computeDeclContext(SS);
10179 if (!DC) return 0;
10180
10181 if (RequireCompleteDeclContext(SS, DC)) return 0;
10182
10183 LookupQualifiedName(Previous, DC);
10184
10185 // Ignore things found implicitly in the wrong scope.
10186 // TODO: better diagnostics for this case. Suggesting the right
10187 // qualified scope would be nice...
10188 LookupResult::Filter F = Previous.makeFilter();
10189 while (F.hasNext()) {
10190 NamedDecl *D = F.next();
10191 if (!DC->InEnclosingNamespaceSetOf(
10192 D->getDeclContext()->getRedeclContext()))
10193 F.erase();
10194 }
10195 F.done();
10196
10197 if (Previous.empty()) {
10198 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010199 Diag(Loc, diag::err_qualified_friend_not_found)
10200 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010201 return 0;
10202 }
10203
10204 // C++ [class.friend]p1: A friend of a class is a function or
10205 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010206 if (DC->Equals(CurContext))
10207 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010208 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010209 diag::warn_cxx98_compat_friend_is_member :
10210 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010211
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010212 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010213 // C++ [class.friend]p6:
10214 // A function can be defined in a friend declaration of a class if and
10215 // only if the class is a non-local class (9.8), the function name is
10216 // unqualified, and the function has namespace scope.
10217 SemaDiagnosticBuilder DB
10218 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10219
10220 DB << SS.getScopeRep();
10221 if (DC->isFileContext())
10222 DB << FixItHint::CreateRemoval(SS.getRange());
10223 SS.clear();
10224 }
John McCall337ec3d2010-10-12 23:13:28 +000010225
10226 // - There's a scope specifier that does not match any template
10227 // parameter lists, in which case we use some arbitrary context,
10228 // create a method or method template, and wait for instantiation.
10229 // - There's a scope specifier that does match some template
10230 // parameter lists, which we don't handle right now.
10231 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010232 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010233 // C++ [class.friend]p6:
10234 // A function can be defined in a friend declaration of a class if and
10235 // only if the class is a non-local class (9.8), the function name is
10236 // unqualified, and the function has namespace scope.
10237 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10238 << SS.getScopeRep();
10239 }
10240
John McCall337ec3d2010-10-12 23:13:28 +000010241 DC = CurContext;
10242 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010243 }
Douglas Gregor883af832011-10-10 01:11:59 +000010244
John McCall29ae6e52010-10-13 05:45:15 +000010245 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010246 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010247 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10248 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10249 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010250 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010251 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10252 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010253 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010254 }
John McCall67d1a672009-08-06 02:15:43 +000010255 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010256
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010257 // FIXME: This is an egregious hack to cope with cases where the scope stack
10258 // does not contain the declaration context, i.e., in an out-of-line
10259 // definition of a class.
10260 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10261 if (!DCScope) {
10262 FakeDCScope.setEntity(DC);
10263 DCScope = &FakeDCScope;
10264 }
10265
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010266 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010267 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10268 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010269 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010270
Douglas Gregor182ddf02009-09-28 00:08:27 +000010271 assert(ND->getDeclContext() == DC);
10272 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010273
John McCallab88d972009-08-31 22:39:49 +000010274 // Add the function declaration to the appropriate lookup tables,
10275 // adjusting the redeclarations list as necessary. We don't
10276 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010277 //
John McCallab88d972009-08-31 22:39:49 +000010278 // Also update the scope-based lookup if the target context's
10279 // lookup context is in lexical scope.
10280 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010281 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010282 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010283 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010284 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010285 }
John McCall02cace72009-08-28 07:59:38 +000010286
10287 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010288 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010289 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010290 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010291 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010292
John McCall337ec3d2010-10-12 23:13:28 +000010293 if (ND->isInvalidDecl())
10294 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010295 else {
10296 FunctionDecl *FD;
10297 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10298 FD = FTD->getTemplatedDecl();
10299 else
10300 FD = cast<FunctionDecl>(ND);
10301
10302 // Mark templated-scope function declarations as unsupported.
10303 if (FD->getNumTemplateParameterLists())
10304 FrD->setUnsupportedFriend(true);
10305 }
John McCall337ec3d2010-10-12 23:13:28 +000010306
John McCalld226f652010-08-21 09:40:31 +000010307 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010308}
10309
John McCalld226f652010-08-21 09:40:31 +000010310void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10311 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010312
Sebastian Redl50de12f2009-03-24 22:27:57 +000010313 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10314 if (!Fn) {
10315 Diag(DelLoc, diag::err_deleted_non_function);
10316 return;
10317 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010318 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010319 Diag(DelLoc, diag::err_deleted_decl_not_first);
10320 Diag(Prev->getLocation(), diag::note_previous_declaration);
10321 // If the declaration wasn't the first, we delete the function anyway for
10322 // recovery.
10323 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010324 Fn->setDeletedAsWritten();
Richard Smithe653ba22012-02-26 00:31:33 +000010325
10326 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10327 if (!MD)
10328 return;
10329
10330 // A deleted special member function is trivial if the corresponding
10331 // implicitly-declared function would have been.
10332 switch (getSpecialMember(MD)) {
10333 case CXXInvalid:
10334 break;
10335 case CXXDefaultConstructor:
10336 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10337 break;
10338 case CXXCopyConstructor:
10339 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10340 break;
10341 case CXXMoveConstructor:
10342 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10343 break;
10344 case CXXCopyAssignment:
10345 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10346 break;
10347 case CXXMoveAssignment:
10348 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10349 break;
10350 case CXXDestructor:
10351 MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10352 break;
10353 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010354}
Sebastian Redl13e88542009-04-27 21:33:24 +000010355
Sean Hunte4246a62011-05-12 06:15:49 +000010356void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10357 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10358
10359 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010360 if (MD->getParent()->isDependentType()) {
10361 MD->setDefaulted();
10362 MD->setExplicitlyDefaulted();
10363 return;
10364 }
10365
Sean Hunte4246a62011-05-12 06:15:49 +000010366 CXXSpecialMember Member = getSpecialMember(MD);
10367 if (Member == CXXInvalid) {
10368 Diag(DefaultLoc, diag::err_default_special_members);
10369 return;
10370 }
10371
10372 MD->setDefaulted();
10373 MD->setExplicitlyDefaulted();
10374
Sean Huntcd10dec2011-05-23 23:14:04 +000010375 // If this definition appears within the record, do the checking when
10376 // the record is complete.
10377 const FunctionDecl *Primary = MD;
10378 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10379 // Find the uninstantiated declaration that actually had the '= default'
10380 // on it.
10381 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10382
10383 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010384 return;
10385
10386 switch (Member) {
10387 case CXXDefaultConstructor: {
10388 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Richard Smith3003e1d2012-05-15 04:39:51 +000010389 CheckExplicitlyDefaultedSpecialMember(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010390 if (!CD->isInvalidDecl())
10391 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10392 break;
10393 }
10394
10395 case CXXCopyConstructor: {
10396 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Richard Smith3003e1d2012-05-15 04:39:51 +000010397 CheckExplicitlyDefaultedSpecialMember(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010398 if (!CD->isInvalidDecl())
10399 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010400 break;
10401 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010402
Sean Hunt2b188082011-05-14 05:23:28 +000010403 case CXXCopyAssignment: {
Richard Smith3003e1d2012-05-15 04:39:51 +000010404 CheckExplicitlyDefaultedSpecialMember(MD);
Sean Hunt2b188082011-05-14 05:23:28 +000010405 if (!MD->isInvalidDecl())
10406 DefineImplicitCopyAssignment(DefaultLoc, MD);
10407 break;
10408 }
10409
Sean Huntcb45a0f2011-05-12 22:46:25 +000010410 case CXXDestructor: {
10411 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Richard Smith3003e1d2012-05-15 04:39:51 +000010412 CheckExplicitlyDefaultedSpecialMember(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010413 if (!DD->isInvalidDecl())
10414 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010415 break;
10416 }
10417
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010418 case CXXMoveConstructor: {
10419 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Richard Smith3003e1d2012-05-15 04:39:51 +000010420 CheckExplicitlyDefaultedSpecialMember(CD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010421 if (!CD->isInvalidDecl())
10422 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010423 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010424 }
Sean Hunt82713172011-05-25 23:16:36 +000010425
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010426 case CXXMoveAssignment: {
Richard Smith3003e1d2012-05-15 04:39:51 +000010427 CheckExplicitlyDefaultedSpecialMember(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010428 if (!MD->isInvalidDecl())
10429 DefineImplicitMoveAssignment(DefaultLoc, MD);
10430 break;
10431 }
10432
10433 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010434 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010435 }
10436 } else {
10437 Diag(DefaultLoc, diag::err_default_special_members);
10438 }
10439}
10440
Sebastian Redl13e88542009-04-27 21:33:24 +000010441static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010442 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010443 Stmt *SubStmt = *CI;
10444 if (!SubStmt)
10445 continue;
10446 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010447 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010448 diag::err_return_in_constructor_handler);
10449 if (!isa<Expr>(SubStmt))
10450 SearchForReturnInStmt(Self, SubStmt);
10451 }
10452}
10453
10454void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10455 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10456 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10457 SearchForReturnInStmt(*this, Handler);
10458 }
10459}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010460
Mike Stump1eb44332009-09-09 15:08:12 +000010461bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010462 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010463 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10464 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010465
Chandler Carruth73857792010-02-15 11:53:20 +000010466 if (Context.hasSameType(NewTy, OldTy) ||
10467 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010468 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010469
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010470 // Check if the return types are covariant
10471 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010472
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010473 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010474 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10475 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010476 NewClassTy = NewPT->getPointeeType();
10477 OldClassTy = OldPT->getPointeeType();
10478 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010479 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10480 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10481 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10482 NewClassTy = NewRT->getPointeeType();
10483 OldClassTy = OldRT->getPointeeType();
10484 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010485 }
10486 }
Mike Stump1eb44332009-09-09 15:08:12 +000010487
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010488 // The return types aren't either both pointers or references to a class type.
10489 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010490 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010491 diag::err_different_return_type_for_overriding_virtual_function)
10492 << New->getDeclName() << NewTy << OldTy;
10493 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010494
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010495 return true;
10496 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010497
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010498 // C++ [class.virtual]p6:
10499 // If the return type of D::f differs from the return type of B::f, the
10500 // class type in the return type of D::f shall be complete at the point of
10501 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010502 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10503 if (!RT->isBeingDefined() &&
10504 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000010505 diag::err_covariant_return_incomplete,
10506 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010507 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010508 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010509
Douglas Gregora4923eb2009-11-16 21:35:15 +000010510 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010511 // Check if the new class derives from the old class.
10512 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10513 Diag(New->getLocation(),
10514 diag::err_covariant_return_not_derived)
10515 << New->getDeclName() << NewTy << OldTy;
10516 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10517 return true;
10518 }
Mike Stump1eb44332009-09-09 15:08:12 +000010519
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010520 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010521 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010522 diag::err_covariant_return_inaccessible_base,
10523 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10524 // FIXME: Should this point to the return type?
10525 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010526 // FIXME: this note won't trigger for delayed access control
10527 // diagnostics, and it's impossible to get an undelayed error
10528 // here from access control during the original parse because
10529 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010530 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10531 return true;
10532 }
10533 }
Mike Stump1eb44332009-09-09 15:08:12 +000010534
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010535 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010536 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010537 Diag(New->getLocation(),
10538 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010539 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010540 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10541 return true;
10542 };
Mike Stump1eb44332009-09-09 15:08:12 +000010543
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010544
10545 // The new class type must have the same or less qualifiers as the old type.
10546 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10547 Diag(New->getLocation(),
10548 diag::err_covariant_return_type_class_type_more_qualified)
10549 << New->getDeclName() << NewTy << OldTy;
10550 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10551 return true;
10552 };
Mike Stump1eb44332009-09-09 15:08:12 +000010553
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010554 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010555}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010556
Douglas Gregor4ba31362009-12-01 17:24:26 +000010557/// \brief Mark the given method pure.
10558///
10559/// \param Method the method to be marked pure.
10560///
10561/// \param InitRange the source range that covers the "0" initializer.
10562bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010563 SourceLocation EndLoc = InitRange.getEnd();
10564 if (EndLoc.isValid())
10565 Method->setRangeEnd(EndLoc);
10566
Douglas Gregor4ba31362009-12-01 17:24:26 +000010567 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10568 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010569 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010570 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010571
10572 if (!Method->isInvalidDecl())
10573 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10574 << Method->getDeclName() << InitRange;
10575 return true;
10576}
10577
Douglas Gregor552e2992012-02-21 02:22:07 +000010578/// \brief Determine whether the given declaration is a static data member.
10579static bool isStaticDataMember(Decl *D) {
10580 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10581 if (!Var)
10582 return false;
10583
10584 return Var->isStaticDataMember();
10585}
John McCall731ad842009-12-19 09:28:58 +000010586/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10587/// an initializer for the out-of-line declaration 'Dcl'. The scope
10588/// is a fresh scope pushed for just this purpose.
10589///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010590/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10591/// static data member of class X, names should be looked up in the scope of
10592/// class X.
John McCalld226f652010-08-21 09:40:31 +000010593void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010594 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010595 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010596
John McCall731ad842009-12-19 09:28:58 +000010597 // We should only get called for declarations with scope specifiers, like:
10598 // int foo::bar;
10599 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010600 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000010601
10602 // If we are parsing the initializer for a static data member, push a
10603 // new expression evaluation context that is associated with this static
10604 // data member.
10605 if (isStaticDataMember(D))
10606 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010607}
10608
10609/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010610/// initializer for the out-of-line declaration 'D'.
10611void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010612 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010613 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010614
Douglas Gregor552e2992012-02-21 02:22:07 +000010615 if (isStaticDataMember(D))
10616 PopExpressionEvaluationContext();
10617
John McCall731ad842009-12-19 09:28:58 +000010618 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010619 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010620}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010621
10622/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10623/// C++ if/switch/while/for statement.
10624/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010625DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010626 // C++ 6.4p2:
10627 // The declarator shall not specify a function or an array.
10628 // The type-specifier-seq shall not contain typedef and shall not declare a
10629 // new class or enumeration.
10630 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10631 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010632
10633 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010634 if (!Dcl)
10635 return true;
10636
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010637 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10638 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010639 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010640 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010641 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010642
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010643 return Dcl;
10644}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010645
Douglas Gregordfe65432011-07-28 19:11:31 +000010646void Sema::LoadExternalVTableUses() {
10647 if (!ExternalSource)
10648 return;
10649
10650 SmallVector<ExternalVTableUse, 4> VTables;
10651 ExternalSource->ReadUsedVTables(VTables);
10652 SmallVector<VTableUse, 4> NewUses;
10653 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10654 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10655 = VTablesUsed.find(VTables[I].Record);
10656 // Even if a definition wasn't required before, it may be required now.
10657 if (Pos != VTablesUsed.end()) {
10658 if (!Pos->second && VTables[I].DefinitionRequired)
10659 Pos->second = true;
10660 continue;
10661 }
10662
10663 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10664 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10665 }
10666
10667 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10668}
10669
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010670void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10671 bool DefinitionRequired) {
10672 // Ignore any vtable uses in unevaluated operands or for classes that do
10673 // not have a vtable.
10674 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10675 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010676 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010677 return;
10678
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010679 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010680 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010681 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10682 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10683 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10684 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010685 // If we already had an entry, check to see if we are promoting this vtable
10686 // to required a definition. If so, we need to reappend to the VTableUses
10687 // list, since we may have already processed the first entry.
10688 if (DefinitionRequired && !Pos.first->second) {
10689 Pos.first->second = true;
10690 } else {
10691 // Otherwise, we can early exit.
10692 return;
10693 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010694 }
10695
10696 // Local classes need to have their virtual members marked
10697 // immediately. For all other classes, we mark their virtual members
10698 // at the end of the translation unit.
10699 if (Class->isLocalClass())
10700 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010701 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010702 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010703}
10704
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010705bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010706 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010707 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010708 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010709
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010710 // Note: The VTableUses vector could grow as a result of marking
10711 // the members of a class as "used", so we check the size each
10712 // time through the loop and prefer indices (with are stable) to
10713 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010714 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010715 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010716 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010717 if (!Class)
10718 continue;
10719
10720 SourceLocation Loc = VTableUses[I].second;
10721
10722 // If this class has a key function, but that key function is
10723 // defined in another translation unit, we don't need to emit the
10724 // vtable even though we're using it.
10725 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010726 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010727 switch (KeyFunction->getTemplateSpecializationKind()) {
10728 case TSK_Undeclared:
10729 case TSK_ExplicitSpecialization:
10730 case TSK_ExplicitInstantiationDeclaration:
10731 // The key function is in another translation unit.
10732 continue;
10733
10734 case TSK_ExplicitInstantiationDefinition:
10735 case TSK_ImplicitInstantiation:
10736 // We will be instantiating the key function.
10737 break;
10738 }
10739 } else if (!KeyFunction) {
10740 // If we have a class with no key function that is the subject
10741 // of an explicit instantiation declaration, suppress the
10742 // vtable; it will live with the explicit instantiation
10743 // definition.
10744 bool IsExplicitInstantiationDeclaration
10745 = Class->getTemplateSpecializationKind()
10746 == TSK_ExplicitInstantiationDeclaration;
10747 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10748 REnd = Class->redecls_end();
10749 R != REnd; ++R) {
10750 TemplateSpecializationKind TSK
10751 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10752 if (TSK == TSK_ExplicitInstantiationDeclaration)
10753 IsExplicitInstantiationDeclaration = true;
10754 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10755 IsExplicitInstantiationDeclaration = false;
10756 break;
10757 }
10758 }
10759
10760 if (IsExplicitInstantiationDeclaration)
10761 continue;
10762 }
10763
10764 // Mark all of the virtual members of this class as referenced, so
10765 // that we can build a vtable. Then, tell the AST consumer that a
10766 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010767 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010768 MarkVirtualMembersReferenced(Loc, Class);
10769 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10770 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10771
10772 // Optionally warn if we're emitting a weak vtable.
10773 if (Class->getLinkage() == ExternalLinkage &&
10774 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010775 const FunctionDecl *KeyFunctionDef = 0;
10776 if (!KeyFunction ||
10777 (KeyFunction->hasBody(KeyFunctionDef) &&
10778 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010779 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10780 TSK_ExplicitInstantiationDefinition
10781 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10782 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010783 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010784 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010785 VTableUses.clear();
10786
Douglas Gregor78844032011-04-22 22:25:37 +000010787 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010788}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010789
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010790void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10791 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010792 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10793 e = RD->method_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +000010794 CXXMethodDecl *MD = *i;
Anders Carlssond6a637f2009-12-07 08:24:59 +000010795
10796 // C++ [basic.def.odr]p2:
10797 // [...] A virtual member function is used if it is not pure. [...]
10798 if (MD->isVirtual() && !MD->isPure())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010799 MarkFunctionReferenced(Loc, MD);
Anders Carlssond6a637f2009-12-07 08:24:59 +000010800 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010801
10802 // Only classes that have virtual bases need a VTT.
10803 if (RD->getNumVBases() == 0)
10804 return;
10805
10806 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10807 e = RD->bases_end(); i != e; ++i) {
10808 const CXXRecordDecl *Base =
10809 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010810 if (Base->getNumVBases() == 0)
10811 continue;
10812 MarkVirtualMembersReferenced(Loc, Base);
10813 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010814}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010815
10816/// SetIvarInitializers - This routine builds initialization ASTs for the
10817/// Objective-C implementation whose ivars need be initialized.
10818void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000010819 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010820 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010821 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010822 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010823 CollectIvarsToConstructOrDestruct(OID, ivars);
10824 if (ivars.empty())
10825 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010826 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010827 for (unsigned i = 0; i < ivars.size(); i++) {
10828 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010829 if (Field->isInvalidDecl())
10830 continue;
10831
Sean Huntcbb67482011-01-08 20:30:50 +000010832 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010833 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10834 InitializationKind InitKind =
10835 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10836
10837 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010838 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010839 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010840 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010841 // Note, MemberInit could actually come back empty if no initialization
10842 // is required (e.g., because it would call a trivial default constructor)
10843 if (!MemberInit.get() || MemberInit.isInvalid())
10844 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010845
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010846 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010847 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10848 SourceLocation(),
10849 MemberInit.takeAs<Expr>(),
10850 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010851 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010852
10853 // Be sure that the destructor is accessible and is marked as referenced.
10854 if (const RecordType *RecordTy
10855 = Context.getBaseElementType(Field->getType())
10856 ->getAs<RecordType>()) {
10857 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010858 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010859 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010860 CheckDestructorAccess(Field->getLocation(), Destructor,
10861 PDiag(diag::err_access_dtor_ivar)
10862 << Context.getBaseElementType(Field->getType()));
10863 }
10864 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010865 }
10866 ObjCImplementation->setIvarInitializers(Context,
10867 AllToInit.data(), AllToInit.size());
10868 }
10869}
Sean Huntfe57eef2011-05-04 05:57:24 +000010870
Sean Huntebcbe1d2011-05-04 23:29:54 +000010871static
10872void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10873 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10874 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10875 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10876 Sema &S) {
10877 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10878 CE = Current.end();
10879 if (Ctor->isInvalidDecl())
10880 return;
10881
10882 const FunctionDecl *FNTarget = 0;
10883 CXXConstructorDecl *Target;
10884
10885 // We ignore the result here since if we don't have a body, Target will be
10886 // null below.
10887 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10888 Target
10889= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10890
10891 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10892 // Avoid dereferencing a null pointer here.
10893 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10894
10895 if (!Current.insert(Canonical))
10896 return;
10897
10898 // We know that beyond here, we aren't chaining into a cycle.
10899 if (!Target || !Target->isDelegatingConstructor() ||
10900 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10901 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10902 Valid.insert(*CI);
10903 Current.clear();
10904 // We've hit a cycle.
10905 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10906 Current.count(TCanonical)) {
10907 // If we haven't diagnosed this cycle yet, do so now.
10908 if (!Invalid.count(TCanonical)) {
10909 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010910 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010911 << Ctor;
10912
10913 // Don't add a note for a function delegating directo to itself.
10914 if (TCanonical != Canonical)
10915 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10916
10917 CXXConstructorDecl *C = Target;
10918 while (C->getCanonicalDecl() != Canonical) {
10919 (void)C->getTargetConstructor()->hasBody(FNTarget);
10920 assert(FNTarget && "Ctor cycle through bodiless function");
10921
10922 C
10923 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10924 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10925 }
10926 }
10927
10928 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10929 Invalid.insert(*CI);
10930 Current.clear();
10931 } else {
10932 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10933 }
10934}
10935
10936
Sean Huntfe57eef2011-05-04 05:57:24 +000010937void Sema::CheckDelegatingCtorCycles() {
10938 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10939
Sean Huntebcbe1d2011-05-04 23:29:54 +000010940 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10941 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010942
Douglas Gregor0129b562011-07-27 21:57:17 +000010943 for (DelegatingCtorDeclsType::iterator
10944 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010945 E = DelegatingCtorDecls.end();
10946 I != E; ++I) {
10947 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010948 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010949
10950 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10951 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010952}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000010953
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010954namespace {
10955 /// \brief AST visitor that finds references to the 'this' expression.
10956 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
10957 Sema &S;
10958
10959 public:
10960 explicit FindCXXThisExpr(Sema &S) : S(S) { }
10961
10962 bool VisitCXXThisExpr(CXXThisExpr *E) {
10963 S.Diag(E->getLocation(), diag::err_this_static_member_func)
10964 << E->isImplicit();
10965 return false;
10966 }
10967 };
10968}
10969
10970bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
10971 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
10972 if (!TSInfo)
10973 return false;
10974
10975 TypeLoc TL = TSInfo->getTypeLoc();
10976 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
10977 if (!ProtoTL)
10978 return false;
10979
10980 // C++11 [expr.prim.general]p3:
10981 // [The expression this] shall not appear before the optional
10982 // cv-qualifier-seq and it shall not appear within the declaration of a
10983 // static member function (although its type and value category are defined
10984 // within a static member function as they are within a non-static member
10985 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000010986 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010987 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
10988 FindCXXThisExpr Finder(*this);
10989
10990 // If the return type came after the cv-qualifier-seq, check it now.
10991 if (Proto->hasTrailingReturn() &&
10992 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
10993 return true;
10994
10995 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000010996 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
10997 return true;
10998
10999 return checkThisInStaticMemberFunctionAttributes(Method);
11000}
11001
11002bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11003 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11004 if (!TSInfo)
11005 return false;
11006
11007 TypeLoc TL = TSInfo->getTypeLoc();
11008 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11009 if (!ProtoTL)
11010 return false;
11011
11012 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11013 FindCXXThisExpr Finder(*this);
11014
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011015 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011016 case EST_Uninstantiated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011017 case EST_BasicNoexcept:
11018 case EST_Delayed:
11019 case EST_DynamicNone:
11020 case EST_MSAny:
11021 case EST_None:
11022 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011023
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011024 case EST_ComputedNoexcept:
11025 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11026 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011027
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011028 case EST_Dynamic:
11029 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011030 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011031 E != EEnd; ++E) {
11032 if (!Finder.TraverseType(*E))
11033 return true;
11034 }
11035 break;
11036 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011037
11038 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011039}
11040
11041bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11042 FindCXXThisExpr Finder(*this);
11043
11044 // Check attributes.
11045 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11046 A != AEnd; ++A) {
11047 // FIXME: This should be emitted by tblgen.
11048 Expr *Arg = 0;
11049 ArrayRef<Expr *> Args;
11050 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11051 Arg = G->getArg();
11052 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11053 Arg = G->getArg();
11054 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11055 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11056 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11057 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11058 else if (ExclusiveLockFunctionAttr *ELF
11059 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11060 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11061 else if (SharedLockFunctionAttr *SLF
11062 = dyn_cast<SharedLockFunctionAttr>(*A))
11063 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11064 else if (ExclusiveTrylockFunctionAttr *ETLF
11065 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11066 Arg = ETLF->getSuccessValue();
11067 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11068 } else if (SharedTrylockFunctionAttr *STLF
11069 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11070 Arg = STLF->getSuccessValue();
11071 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11072 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11073 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11074 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11075 Arg = LR->getArg();
11076 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11077 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11078 else if (ExclusiveLocksRequiredAttr *ELR
11079 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11080 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11081 else if (SharedLocksRequiredAttr *SLR
11082 = dyn_cast<SharedLocksRequiredAttr>(*A))
11083 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11084
11085 if (Arg && !Finder.TraverseStmt(Arg))
11086 return true;
11087
11088 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11089 if (!Finder.TraverseStmt(Args[I]))
11090 return true;
11091 }
11092 }
11093
11094 return false;
11095}
11096
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011097void
11098Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11099 ArrayRef<ParsedType> DynamicExceptions,
11100 ArrayRef<SourceRange> DynamicExceptionRanges,
11101 Expr *NoexceptExpr,
11102 llvm::SmallVectorImpl<QualType> &Exceptions,
11103 FunctionProtoType::ExtProtoInfo &EPI) {
11104 Exceptions.clear();
11105 EPI.ExceptionSpecType = EST;
11106 if (EST == EST_Dynamic) {
11107 Exceptions.reserve(DynamicExceptions.size());
11108 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11109 // FIXME: Preserve type source info.
11110 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11111
11112 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11113 collectUnexpandedParameterPacks(ET, Unexpanded);
11114 if (!Unexpanded.empty()) {
11115 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11116 UPPC_ExceptionType,
11117 Unexpanded);
11118 continue;
11119 }
11120
11121 // Check that the type is valid for an exception spec, and
11122 // drop it if not.
11123 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11124 Exceptions.push_back(ET);
11125 }
11126 EPI.NumExceptions = Exceptions.size();
11127 EPI.Exceptions = Exceptions.data();
11128 return;
11129 }
11130
11131 if (EST == EST_ComputedNoexcept) {
11132 // If an error occurred, there's no expression here.
11133 if (NoexceptExpr) {
11134 assert((NoexceptExpr->isTypeDependent() ||
11135 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11136 Context.BoolTy) &&
11137 "Parser should have made sure that the expression is boolean");
11138 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11139 EPI.ExceptionSpecType = EST_BasicNoexcept;
11140 return;
11141 }
11142
11143 if (!NoexceptExpr->isValueDependent())
11144 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011145 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011146 /*AllowFold*/ false).take();
11147 EPI.NoexceptExpr = NoexceptExpr;
11148 }
11149 return;
11150 }
11151}
11152
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011153/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11154Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11155 // Implicitly declared functions (e.g. copy constructors) are
11156 // __host__ __device__
11157 if (D->isImplicit())
11158 return CFT_HostDevice;
11159
11160 if (D->hasAttr<CUDAGlobalAttr>())
11161 return CFT_Global;
11162
11163 if (D->hasAttr<CUDADeviceAttr>()) {
11164 if (D->hasAttr<CUDAHostAttr>())
11165 return CFT_HostDevice;
11166 else
11167 return CFT_Device;
11168 }
11169
11170 return CFT_Host;
11171}
11172
11173bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11174 CUDAFunctionTarget CalleeTarget) {
11175 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11176 // Callable from the device only."
11177 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11178 return true;
11179
11180 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11181 // Callable from the host only."
11182 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11183 // Callable from the host only."
11184 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11185 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11186 return true;
11187
11188 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11189 return true;
11190
11191 return false;
11192}