blob: 059c3720d67ba427ae52435e070e36f8aca52c79 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000040#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000041#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000042
43using namespace clang;
44
Chris Lattner8123a952008-04-10 02:22:51 +000045//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
Chris Lattner9e979552008-04-12 23:52:44 +000049namespace {
50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51 /// the default argument of a parameter to determine whether it
52 /// contains any ill-formed subexpressions. For example, this will
53 /// diagnose the use of local variables or parameters within the
54 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000055 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000056 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000057 Expr *DefaultArg;
58 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 public:
Mike Stump1eb44332009-09-09 15:08:12 +000061 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000062 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000063
Chris Lattner9e979552008-04-12 23:52:44 +000064 bool VisitExpr(Expr *Node);
65 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000066 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000067 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000068 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000069 };
Chris Lattner8123a952008-04-10 02:22:51 +000070
Chris Lattner9e979552008-04-12 23:52:44 +000071 /// VisitExpr - Visit all of the children of this expression.
72 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
73 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000074 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000075 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000076 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000077 }
78
Chris Lattner9e979552008-04-12 23:52:44 +000079 /// VisitDeclRefExpr - Visit a reference to a declaration, to
80 /// determine whether this declaration can be used in the default
81 /// argument expression.
82 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000083 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000084 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
85 // C++ [dcl.fct.default]p9
86 // Default arguments are evaluated each time the function is
87 // called. The order of evaluation of function arguments is
88 // unspecified. Consequently, parameters of a function shall not
89 // be used in default argument expressions, even if they are not
90 // evaluated. Parameters of a function declared before a default
91 // argument expression are in scope and can hide namespace and
92 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000093 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000094 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000095 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000096 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000097 // C++ [dcl.fct.default]p7
98 // Local variables shall not be used in default argument
99 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000100 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000101 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000102 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000103 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000104 }
Chris Lattner8123a952008-04-10 02:22:51 +0000105
Douglas Gregor3996f232008-11-04 13:41:56 +0000106 return false;
107 }
Chris Lattner9e979552008-04-12 23:52:44 +0000108
Douglas Gregor796da182008-11-04 14:32:21 +0000109 /// VisitCXXThisExpr - Visit a C++ "this" expression.
110 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
111 // C++ [dcl.fct.default]p8:
112 // The keyword this shall not be used in a default argument of a
113 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000114 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000115 diag::err_param_default_argument_references_this)
116 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000117 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000118
John McCall045d2522013-04-09 01:56:28 +0000119 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
120 bool Invalid = false;
121 for (PseudoObjectExpr::semantics_iterator
122 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
123 Expr *E = *i;
124
125 // Look through bindings.
126 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
127 E = OVE->getSourceExpr();
128 assert(E && "pseudo-object binding without source expression?");
129 }
130
131 Invalid |= Visit(E);
132 }
133 return Invalid;
134 }
135
Douglas Gregorf0459f82012-02-10 23:30:22 +0000136 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
137 // C++11 [expr.lambda.prim]p13:
138 // A lambda-expression appearing in a default argument shall not
139 // implicitly or explicitly capture any entity.
140 if (Lambda->capture_begin() == Lambda->capture_end())
141 return false;
142
143 return S->Diag(Lambda->getLocStart(),
144 diag::err_lambda_capture_default_arg);
145 }
Chris Lattner8123a952008-04-10 02:22:51 +0000146}
147
Richard Smith0b0ca472013-04-10 06:11:48 +0000148void
149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
150 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000151 // If we have an MSAny spec already, don't bother.
152 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000153 return;
154
155 const FunctionProtoType *Proto
156 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000157 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
158 if (!Proto)
159 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000160
161 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
162
163 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000164 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000165 ClearExceptions();
166 ComputedEST = EST;
167 return;
168 }
169
Richard Smith7a614d82011-06-11 17:19:42 +0000170 // FIXME: If the call to this decl is using any of its default arguments, we
171 // need to search them for potentially-throwing calls.
172
Sean Hunt001cad92011-05-10 00:49:42 +0000173 // If this function has a basic noexcept, it doesn't affect the outcome.
174 if (EST == EST_BasicNoexcept)
175 return;
176
177 // If we have a throw-all spec at this point, ignore the function.
178 if (ComputedEST == EST_None)
179 return;
180
181 // If we're still at noexcept(true) and there's a nothrow() callee,
182 // change to that specification.
183 if (EST == EST_DynamicNone) {
184 if (ComputedEST == EST_BasicNoexcept)
185 ComputedEST = EST_DynamicNone;
186 return;
187 }
188
189 // Check out noexcept specs.
190 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000191 FunctionProtoType::NoexceptResult NR =
192 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000193 assert(NR != FunctionProtoType::NR_NoNoexcept &&
194 "Must have noexcept result for EST_ComputedNoexcept.");
195 assert(NR != FunctionProtoType::NR_Dependent &&
196 "Should not generate implicit declarations for dependent cases, "
197 "and don't know how to handle them anyway.");
198
199 // noexcept(false) -> no spec on the new function
200 if (NR == FunctionProtoType::NR_Throw) {
201 ClearExceptions();
202 ComputedEST = EST_None;
203 }
204 // noexcept(true) won't change anything either.
205 return;
206 }
207
208 assert(EST == EST_Dynamic && "EST case not considered earlier.");
209 assert(ComputedEST != EST_None &&
210 "Shouldn't collect exceptions when throw-all is guaranteed.");
211 ComputedEST = EST_Dynamic;
212 // Record the exceptions in this function's exception specification.
213 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
214 EEnd = Proto->exception_end();
215 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000217 Exceptions.push_back(*E);
218}
219
Richard Smith7a614d82011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithe6975e92012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssoned961f92009-08-25 02:29:20 +0000249bool
John McCall9ae2f072010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000271 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000273
Richard Smith6c3af3d2013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Anders Carlssoned961f92009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson9351c172009-08-25 03:18:48 +0000292 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000293}
294
Chris Lattner8123a952008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000298void
John McCalld226f652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000302 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCalld226f652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner3d1cee32008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6f526752010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlsson66e30672009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
John McCall9ae2f072010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000329}
330
Douglas Gregor61366e92008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCalld226f652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param)
343 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Anders Carlsson5e300d12009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000346}
347
Douglas Gregor72b505b2008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCalld226f652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Anders Carlsson5e300d12009-06-12 16:51:40 +0000356 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Anders Carlsson5e300d12009-06-12 16:51:40 +0000358 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000359}
360
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000361/// CheckExtraCXXDefaultArguments - Check for any extra default
362/// arguments in the declarator, which is not a function declaration
363/// or definition and therefore is not permitted to have default
364/// arguments. This routine should be invoked for every declarator
365/// that is not a function declaration or definition.
366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367 // C++ [dcl.fct.default]p3
368 // A default argument expression shall be specified only in the
369 // parameter-declaration-clause of a function declaration or in a
370 // template-parameter (14.1). It shall not be specified for a
371 // parameter pack. If it is specified in a
372 // parameter-declaration-clause, it shall not occur within a
373 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000374 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000376 DeclaratorChunk &chunk = D.getTypeObject(i);
377 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000378 if (MightBeFunction) {
379 // This is a function declaration. It can have default arguments, but
380 // keep looking in case its return type is a function type with default
381 // arguments.
382 MightBeFunction = false;
383 continue;
384 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000385 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
386 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000387 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000388 if (Param->hasUnparsedDefaultArg()) {
389 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000391 << SourceRange((*Toks)[1].getLocation(),
392 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000393 delete Toks;
394 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000395 } else if (Param->getDefaultArg()) {
396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397 << Param->getDefaultArg()->getSourceRange();
398 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000399 }
400 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000401 } else if (chunk.Kind != DeclaratorChunk::Paren) {
402 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000403 }
404 }
405}
406
Craig Topper1a6eac82012-09-21 04:33:26 +0000407/// MergeCXXFunctionDecl - Merge two declarations of the same C++
408/// function, once we already know that they have the same
409/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
410/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000411bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
412 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000413 bool Invalid = false;
414
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000416 // For non-template functions, default arguments can be added in
417 // later declarations of a function in the same
418 // scope. Declarations in different scopes have completely
419 // distinct sets of default arguments. That is, declarations in
420 // inner scopes do not acquire default arguments from
421 // declarations in outer scopes, and vice versa. In a given
422 // function declaration, all parameters subsequent to a
423 // parameter with a default argument shall have default
424 // arguments supplied in this or previous declarations. A
425 // default argument shall not be redefined by a later
426 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000427 //
428 // C++ [dcl.fct.default]p6:
429 // Except for member functions of class templates, the default arguments
430 // in a member function definition that appears outside of the class
431 // definition are added to the set of default arguments provided by the
432 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000433 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
434 ParmVarDecl *OldParam = Old->getParamDecl(p);
435 ParmVarDecl *NewParam = New->getParamDecl(p);
436
James Molloy9cda03f2012-03-13 08:55:35 +0000437 bool OldParamHasDfl = OldParam->hasDefaultArg();
438 bool NewParamHasDfl = NewParam->hasDefaultArg();
439
440 NamedDecl *ND = Old;
441 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
442 // Ignore default parameters of old decl if they are not in
443 // the same scope.
444 OldParamHasDfl = false;
445
446 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000447
Francois Pichet8d051e02011-04-10 03:03:52 +0000448 unsigned DiagDefaultParamID =
449 diag::err_param_default_argument_redefinition;
450
451 // MSVC accepts that default parameters be redefined for member functions
452 // of template class. The new default parameter's value is ignored.
453 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000454 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000455 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
456 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000457 // Merge the old default argument into the new parameter.
458 NewParam->setHasInheritedDefaultArg();
459 if (OldParam->hasUninstantiatedDefaultArg())
460 NewParam->setUninstantiatedDefaultArg(
461 OldParam->getUninstantiatedDefaultArg());
462 else
463 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000464 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000465 Invalid = false;
466 }
467 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000468
Francois Pichet8cf90492011-04-10 04:58:30 +0000469 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
470 // hint here. Alternatively, we could walk the type-source information
471 // for NewParam to find the last source location in the type... but it
472 // isn't worth the effort right now. This is the kind of test case that
473 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000474 // int f(int);
475 // void g(int (*fp)(int) = f);
476 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000477 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000478 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000479
480 // Look for the function declaration where the default argument was
481 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000482 for (FunctionDecl *Older = Old->getPreviousDecl();
483 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000484 if (!Older->getParamDecl(p)->hasDefaultArg())
485 break;
486
487 OldParam = Older->getParamDecl(p);
488 }
489
490 Diag(OldParam->getLocation(), diag::note_previous_definition)
491 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000492 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000493 // Merge the old default argument into the new parameter.
494 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000495 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000496 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000497 if (OldParam->hasUninstantiatedDefaultArg())
498 NewParam->setUninstantiatedDefaultArg(
499 OldParam->getUninstantiatedDefaultArg());
500 else
John McCall3d6c1782010-05-04 01:53:42 +0000501 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000502 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000503 if (New->getDescribedFunctionTemplate()) {
504 // Paragraph 4, quoted above, only applies to non-template functions.
505 Diag(NewParam->getLocation(),
506 diag::err_param_default_argument_template_redecl)
507 << NewParam->getDefaultArgRange();
508 Diag(Old->getLocation(), diag::note_template_prev_declaration)
509 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000510 } else if (New->getTemplateSpecializationKind()
511 != TSK_ImplicitInstantiation &&
512 New->getTemplateSpecializationKind() != TSK_Undeclared) {
513 // C++ [temp.expr.spec]p21:
514 // Default function arguments shall not be specified in a declaration
515 // or a definition for one of the following explicit specializations:
516 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000517 // - the explicit specialization of a member function template;
518 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000519 // template where the class template specialization to which the
520 // member function specialization belongs is implicitly
521 // instantiated.
522 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
523 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
524 << New->getDeclName()
525 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000526 } else if (New->getDeclContext()->isDependentContext()) {
527 // C++ [dcl.fct.default]p6 (DR217):
528 // Default arguments for a member function of a class template shall
529 // be specified on the initial declaration of the member function
530 // within the class template.
531 //
532 // Reading the tea leaves a bit in DR217 and its reference to DR205
533 // leads me to the conclusion that one cannot add default function
534 // arguments for an out-of-line definition of a member function of a
535 // dependent type.
536 int WhichKind = 2;
537 if (CXXRecordDecl *Record
538 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
539 if (Record->getDescribedClassTemplate())
540 WhichKind = 0;
541 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
542 WhichKind = 1;
543 else
544 WhichKind = 2;
545 }
546
547 Diag(NewParam->getLocation(),
548 diag::err_param_default_argument_member_template_redecl)
549 << WhichKind
550 << NewParam->getDefaultArgRange();
551 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000552 }
553 }
554
Richard Smithb8abff62012-11-28 03:45:24 +0000555 // DR1344: If a default argument is added outside a class definition and that
556 // default argument makes the function a special member function, the program
557 // is ill-formed. This can only happen for constructors.
558 if (isa<CXXConstructorDecl>(New) &&
559 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
560 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
561 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
562 if (NewSM != OldSM) {
563 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
564 assert(NewParam->hasDefaultArg());
565 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
566 << NewParam->getDefaultArgRange() << NewSM;
567 Diag(Old->getLocation(), diag::note_previous_declaration);
568 }
569 }
570
Richard Smithff234882012-02-20 23:28:05 +0000571 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000572 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000573 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000574 if (New->isConstexpr() != Old->isConstexpr()) {
575 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
576 << New << New->isConstexpr();
577 Diag(Old->getLocation(), diag::note_previous_declaration);
578 Invalid = true;
579 }
580
Douglas Gregore13ad832010-02-12 07:32:17 +0000581 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000582 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000583
Douglas Gregorcda9c672009-02-16 17:45:42 +0000584 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000585}
586
Sebastian Redl60618fa2011-03-12 11:50:43 +0000587/// \brief Merge the exception specifications of two variable declarations.
588///
589/// This is called when there's a redeclaration of a VarDecl. The function
590/// checks if the redeclaration might have an exception specification and
591/// validates compatibility and merges the specs if necessary.
592void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
593 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000594 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000595 return;
596
597 assert(Context.hasSameType(New->getType(), Old->getType()) &&
598 "Should only be called if types are otherwise the same.");
599
600 QualType NewType = New->getType();
601 QualType OldType = Old->getType();
602
603 // We're only interested in pointers and references to functions, as well
604 // as pointers to member functions.
605 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
606 NewType = R->getPointeeType();
607 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
608 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
609 NewType = P->getPointeeType();
610 OldType = OldType->getAs<PointerType>()->getPointeeType();
611 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
612 NewType = M->getPointeeType();
613 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
614 }
615
616 if (!NewType->isFunctionProtoType())
617 return;
618
619 // There's lots of special cases for functions. For function pointers, system
620 // libraries are hopefully not as broken so that we don't need these
621 // workarounds.
622 if (CheckEquivalentExceptionSpec(
623 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
624 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
625 New->setInvalidDecl();
626 }
627}
628
Chris Lattner3d1cee32008-04-08 05:04:30 +0000629/// CheckCXXDefaultArguments - Verify that the default arguments for a
630/// function declaration are well-formed according to C++
631/// [dcl.fct.default].
632void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
633 unsigned NumParams = FD->getNumParams();
634 unsigned p;
635
636 // Find first parameter with a default argument
637 for (p = 0; p < NumParams; ++p) {
638 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000639 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000640 break;
641 }
642
643 // C++ [dcl.fct.default]p4:
644 // In a given function declaration, all parameters
645 // subsequent to a parameter with a default argument shall
646 // have default arguments supplied in this or previous
647 // declarations. A default argument shall not be redefined
648 // by a later declaration (not even to the same value).
649 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000650 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000651 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000652 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000653 if (Param->isInvalidDecl())
654 /* We already complained about this parameter. */;
655 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000656 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000657 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000658 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000659 else
Mike Stump1eb44332009-09-09 15:08:12 +0000660 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000661 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Chris Lattner3d1cee32008-04-08 05:04:30 +0000663 LastMissingDefaultArg = p;
664 }
665 }
666
667 if (LastMissingDefaultArg > 0) {
668 // Some default arguments were missing. Clear out all of the
669 // default arguments up to (and including) the last missing
670 // default argument, so that we leave the function parameters
671 // in a semantically valid state.
672 for (p = 0; p <= LastMissingDefaultArg; ++p) {
673 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000674 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000675 Param->setDefaultArg(0);
676 }
677 }
678 }
679}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000680
Richard Smith9f569cc2011-10-01 02:31:28 +0000681// CheckConstexprParameterTypes - Check whether a function's parameter types
682// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000683// diagnostic and return false.
684static bool CheckConstexprParameterTypes(Sema &SemaRef,
685 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000686 unsigned ArgIndex = 0;
687 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
688 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
689 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
690 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
691 SourceLocation ParamLoc = PD->getLocation();
692 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000693 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000694 diag::err_constexpr_non_literal_param,
695 ArgIndex+1, PD->getSourceRange(),
696 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000697 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000698 }
Joao Matos17d35c32012-08-31 22:18:20 +0000699 return true;
700}
701
702/// \brief Get diagnostic %select index for tag kind for
703/// record diagnostic message.
704/// WARNING: Indexes apply to particular diagnostics only!
705///
706/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000707static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000708 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000709 case TTK_Struct: return 0;
710 case TTK_Interface: return 1;
711 case TTK_Class: return 2;
712 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000713 }
Joao Matos17d35c32012-08-31 22:18:20 +0000714}
715
716// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
717// the requirements of a constexpr function definition or a constexpr
718// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000719// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000720//
Richard Smith86c3ae42012-02-13 03:54:03 +0000721// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
722bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000723 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
724 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000725 // C++11 [dcl.constexpr]p4:
726 // The definition of a constexpr constructor shall satisfy the following
727 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000728 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000729 const CXXRecordDecl *RD = MD->getParent();
730 if (RD->getNumVBases()) {
731 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
732 << isa<CXXConstructorDecl>(NewFD)
733 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
734 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
735 E = RD->vbases_end(); I != E; ++I)
736 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000737 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000738 return false;
739 }
Richard Smith35340502012-01-13 04:54:00 +0000740 }
741
742 if (!isa<CXXConstructorDecl>(NewFD)) {
743 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000744 // The definition of a constexpr function shall satisfy the following
745 // constraints:
746 // - it shall not be virtual;
747 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
748 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000749 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000750
Richard Smith86c3ae42012-02-13 03:54:03 +0000751 // If it's not obvious why this function is virtual, find an overridden
752 // function which uses the 'virtual' keyword.
753 const CXXMethodDecl *WrittenVirtual = Method;
754 while (!WrittenVirtual->isVirtualAsWritten())
755 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
756 if (WrittenVirtual != Method)
757 Diag(WrittenVirtual->getLocation(),
758 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000759 return false;
760 }
761
762 // - its return type shall be a literal type;
763 QualType RT = NewFD->getResultType();
764 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000765 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000766 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000767 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000768 }
769
Richard Smith35340502012-01-13 04:54:00 +0000770 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000771 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000772 return false;
773
Richard Smith9f569cc2011-10-01 02:31:28 +0000774 return true;
775}
776
777/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000778/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000779///
Richard Smitha10b9782013-04-22 15:31:51 +0000780/// \return true if the body is OK (maybe only as an extension), false if we
781/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000782static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000783 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
784 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000785 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
786 // contain only
787 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
788 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
789 switch ((*DclIt)->getKind()) {
790 case Decl::StaticAssert:
791 case Decl::Using:
792 case Decl::UsingShadow:
793 case Decl::UsingDirective:
794 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000795 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000796 // - static_assert-declarations
797 // - using-declarations,
798 // - using-directives,
799 continue;
800
801 case Decl::Typedef:
802 case Decl::TypeAlias: {
803 // - typedef declarations and alias-declarations that do not define
804 // classes or enumerations,
805 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
806 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
807 // Don't allow variably-modified types in constexpr functions.
808 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
809 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
810 << TL.getSourceRange() << TL.getType()
811 << isa<CXXConstructorDecl>(Dcl);
812 return false;
813 }
814 continue;
815 }
816
817 case Decl::Enum:
818 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000819 // C++1y allows types to be defined, not just declared.
820 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
821 SemaRef.Diag(DS->getLocStart(),
822 SemaRef.getLangOpts().CPlusPlus1y
823 ? diag::warn_cxx11_compat_constexpr_type_definition
824 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000825 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000826 continue;
827
Richard Smitha10b9782013-04-22 15:31:51 +0000828 case Decl::EnumConstant:
829 case Decl::IndirectField:
830 case Decl::ParmVar:
831 // These can only appear with other declarations which are banned in
832 // C++11 and permitted in C++1y, so ignore them.
833 continue;
834
835 case Decl::Var: {
836 // C++1y [dcl.constexpr]p3 allows anything except:
837 // a definition of a variable of non-literal type or of static or
838 // thread storage duration or for which no initialization is performed.
839 VarDecl *VD = cast<VarDecl>(*DclIt);
840 if (VD->isThisDeclarationADefinition()) {
841 if (VD->isStaticLocal()) {
842 SemaRef.Diag(VD->getLocation(),
843 diag::err_constexpr_local_var_static)
844 << isa<CXXConstructorDecl>(Dcl)
845 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
846 return false;
847 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000848 if (!VD->getType()->isDependentType() &&
849 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000850 VD->getLocation(), VD->getType(),
851 diag::err_constexpr_local_var_non_literal_type,
852 isa<CXXConstructorDecl>(Dcl)))
853 return false;
854 if (!VD->hasInit()) {
855 SemaRef.Diag(VD->getLocation(),
856 diag::err_constexpr_local_var_no_init)
857 << isa<CXXConstructorDecl>(Dcl);
858 return false;
859 }
860 }
861 SemaRef.Diag(VD->getLocation(),
862 SemaRef.getLangOpts().CPlusPlus1y
863 ? diag::warn_cxx11_compat_constexpr_local_var
864 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000865 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000866 continue;
867 }
868
869 case Decl::NamespaceAlias:
870 case Decl::Function:
871 // These are disallowed in C++11 and permitted in C++1y. Allow them
872 // everywhere as an extension.
873 if (!Cxx1yLoc.isValid())
874 Cxx1yLoc = DS->getLocStart();
875 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000876
877 default:
878 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
879 << isa<CXXConstructorDecl>(Dcl);
880 return false;
881 }
882 }
883
884 return true;
885}
886
887/// Check that the given field is initialized within a constexpr constructor.
888///
889/// \param Dcl The constexpr constructor being checked.
890/// \param Field The field being checked. This may be a member of an anonymous
891/// struct or union nested within the class being checked.
892/// \param Inits All declarations, including anonymous struct/union members and
893/// indirect members, for which any initialization was provided.
894/// \param Diagnosed Set to true if an error is produced.
895static void CheckConstexprCtorInitializer(Sema &SemaRef,
896 const FunctionDecl *Dcl,
897 FieldDecl *Field,
898 llvm::SmallSet<Decl*, 16> &Inits,
899 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000900 if (Field->isUnnamedBitfield())
901 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000902
903 if (Field->isAnonymousStructOrUnion() &&
904 Field->getType()->getAsCXXRecordDecl()->isEmpty())
905 return;
906
Richard Smith9f569cc2011-10-01 02:31:28 +0000907 if (!Inits.count(Field)) {
908 if (!Diagnosed) {
909 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
910 Diagnosed = true;
911 }
912 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
913 } else if (Field->isAnonymousStructOrUnion()) {
914 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
915 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
916 I != E; ++I)
917 // If an anonymous union contains an anonymous struct of which any member
918 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000919 if (!RD->isUnion() || Inits.count(*I))
920 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000921 }
922}
923
Richard Smitha10b9782013-04-22 15:31:51 +0000924/// Check the provided statement is allowed in a constexpr function
925/// definition.
926static bool
927CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
928 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
929 SourceLocation &Cxx1yLoc) {
930 // - its function-body shall be [...] a compound-statement that contains only
931 switch (S->getStmtClass()) {
932 case Stmt::NullStmtClass:
933 // - null statements,
934 return true;
935
936 case Stmt::DeclStmtClass:
937 // - static_assert-declarations
938 // - using-declarations,
939 // - using-directives,
940 // - typedef declarations and alias-declarations that do not define
941 // classes or enumerations,
942 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
943 return false;
944 return true;
945
946 case Stmt::ReturnStmtClass:
947 // - and exactly one return statement;
948 if (isa<CXXConstructorDecl>(Dcl)) {
949 // C++1y allows return statements in constexpr constructors.
950 if (!Cxx1yLoc.isValid())
951 Cxx1yLoc = S->getLocStart();
952 return true;
953 }
954
955 ReturnStmts.push_back(S->getLocStart());
956 return true;
957
958 case Stmt::CompoundStmtClass: {
959 // C++1y allows compound-statements.
960 if (!Cxx1yLoc.isValid())
961 Cxx1yLoc = S->getLocStart();
962
963 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
964 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
965 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
966 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
967 Cxx1yLoc))
968 return false;
969 }
970 return true;
971 }
972
973 case Stmt::AttributedStmtClass:
974 if (!Cxx1yLoc.isValid())
975 Cxx1yLoc = S->getLocStart();
976 return true;
977
978 case Stmt::IfStmtClass: {
979 // C++1y allows if-statements.
980 if (!Cxx1yLoc.isValid())
981 Cxx1yLoc = S->getLocStart();
982
983 IfStmt *If = cast<IfStmt>(S);
984 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
985 Cxx1yLoc))
986 return false;
987 if (If->getElse() &&
988 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
989 Cxx1yLoc))
990 return false;
991 return true;
992 }
993
994 case Stmt::WhileStmtClass:
995 case Stmt::DoStmtClass:
996 case Stmt::ForStmtClass:
997 case Stmt::CXXForRangeStmtClass:
998 case Stmt::ContinueStmtClass:
999 // C++1y allows all of these. We don't allow them as extensions in C++11,
1000 // because they don't make sense without variable mutation.
1001 if (!SemaRef.getLangOpts().CPlusPlus1y)
1002 break;
1003 if (!Cxx1yLoc.isValid())
1004 Cxx1yLoc = S->getLocStart();
1005 for (Stmt::child_range Children = S->children(); Children; ++Children)
1006 if (*Children &&
1007 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1008 Cxx1yLoc))
1009 return false;
1010 return true;
1011
1012 case Stmt::SwitchStmtClass:
1013 case Stmt::CaseStmtClass:
1014 case Stmt::DefaultStmtClass:
1015 case Stmt::BreakStmtClass:
1016 // C++1y allows switch-statements, and since they don't need variable
1017 // mutation, we can reasonably allow them in C++11 as an extension.
1018 if (!Cxx1yLoc.isValid())
1019 Cxx1yLoc = S->getLocStart();
1020 for (Stmt::child_range Children = S->children(); Children; ++Children)
1021 if (*Children &&
1022 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1023 Cxx1yLoc))
1024 return false;
1025 return true;
1026
1027 default:
1028 if (!isa<Expr>(S))
1029 break;
1030
1031 // C++1y allows expression-statements.
1032 if (!Cxx1yLoc.isValid())
1033 Cxx1yLoc = S->getLocStart();
1034 return true;
1035 }
1036
1037 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1038 << isa<CXXConstructorDecl>(Dcl);
1039 return false;
1040}
1041
Richard Smith9f569cc2011-10-01 02:31:28 +00001042/// Check the body for the given constexpr function declaration only contains
1043/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1044///
1045/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001046bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001047 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001048 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001049 // The definition of a constexpr function shall satisfy the following
1050 // constraints: [...]
1051 // - its function-body shall be = delete, = default, or a
1052 // compound-statement
1053 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001054 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001055 // In the definition of a constexpr constructor, [...]
1056 // - its function-body shall not be a function-try-block;
1057 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1058 << isa<CXXConstructorDecl>(Dcl);
1059 return false;
1060 }
1061
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001062 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001063
1064 // - its function-body shall be [...] a compound-statement that contains only
1065 // [... list of cases ...]
1066 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1067 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001068 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1069 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001070 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1071 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001072 }
1073
Richard Smitha10b9782013-04-22 15:31:51 +00001074 if (Cxx1yLoc.isValid())
1075 Diag(Cxx1yLoc,
1076 getLangOpts().CPlusPlus1y
1077 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1078 : diag::ext_constexpr_body_invalid_stmt)
1079 << isa<CXXConstructorDecl>(Dcl);
1080
Richard Smith9f569cc2011-10-01 02:31:28 +00001081 if (const CXXConstructorDecl *Constructor
1082 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1083 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001084 // DR1359:
1085 // - every non-variant non-static data member and base class sub-object
1086 // shall be initialized;
1087 // - if the class is a non-empty union, or for each non-empty anonymous
1088 // union member of a non-union class, exactly one non-static data member
1089 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001090 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001091 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001092 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1093 return false;
1094 }
Richard Smith6e433752011-10-10 16:38:04 +00001095 } else if (!Constructor->isDependentContext() &&
1096 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001097 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1098
1099 // Skip detailed checking if we have enough initializers, and we would
1100 // allow at most one initializer per member.
1101 bool AnyAnonStructUnionMembers = false;
1102 unsigned Fields = 0;
1103 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1104 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001105 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001106 AnyAnonStructUnionMembers = true;
1107 break;
1108 }
1109 }
1110 if (AnyAnonStructUnionMembers ||
1111 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1112 // Check initialization of non-static data members. Base classes are
1113 // always initialized so do not need to be checked. Dependent bases
1114 // might not have initializers in the member initializer list.
1115 llvm::SmallSet<Decl*, 16> Inits;
1116 for (CXXConstructorDecl::init_const_iterator
1117 I = Constructor->init_begin(), E = Constructor->init_end();
1118 I != E; ++I) {
1119 if (FieldDecl *FD = (*I)->getMember())
1120 Inits.insert(FD);
1121 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1122 Inits.insert(ID->chain_begin(), ID->chain_end());
1123 }
1124
1125 bool Diagnosed = false;
1126 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1127 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001128 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001129 if (Diagnosed)
1130 return false;
1131 }
1132 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001133 } else {
1134 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001135 // C++1y doesn't require constexpr functions to contain a 'return'
1136 // statement. We still do, unless the return type is void, because
1137 // otherwise if there's no return statement, the function cannot
1138 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001139 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001140 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001141 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1142 : diag::err_constexpr_body_no_return);
1143 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001144 }
1145 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001146 Diag(ReturnStmts.back(),
1147 getLangOpts().CPlusPlus1y
1148 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1149 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001150 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1151 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001152 }
1153 }
1154
Richard Smith5ba73e12012-02-04 00:33:54 +00001155 // C++11 [dcl.constexpr]p5:
1156 // if no function argument values exist such that the function invocation
1157 // substitution would produce a constant expression, the program is
1158 // ill-formed; no diagnostic required.
1159 // C++11 [dcl.constexpr]p3:
1160 // - every constructor call and implicit conversion used in initializing the
1161 // return value shall be one of those allowed in a constant expression.
1162 // C++11 [dcl.constexpr]p4:
1163 // - every constructor involved in initializing non-static data members and
1164 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001165 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001166 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001167 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001168 << isa<CXXConstructorDecl>(Dcl);
1169 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1170 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001171 // Don't return false here: we allow this for compatibility in
1172 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001173 }
1174
Richard Smith9f569cc2011-10-01 02:31:28 +00001175 return true;
1176}
1177
Douglas Gregorb48fe382008-10-31 09:07:45 +00001178/// isCurrentClassName - Determine whether the identifier II is the
1179/// name of the class type currently being defined. In the case of
1180/// nested classes, this will only return true if II is the name of
1181/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001182bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1183 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001184 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001185
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001186 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001187 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001188 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001189 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1190 } else
1191 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1192
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001193 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001194 return &II == CurDecl->getIdentifier();
1195 else
1196 return false;
1197}
1198
Douglas Gregor229d47a2012-11-10 07:24:09 +00001199/// \brief Determine whether the given class is a base class of the given
1200/// class, including looking at dependent bases.
1201static bool findCircularInheritance(const CXXRecordDecl *Class,
1202 const CXXRecordDecl *Current) {
1203 SmallVector<const CXXRecordDecl*, 8> Queue;
1204
1205 Class = Class->getCanonicalDecl();
1206 while (true) {
1207 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1208 E = Current->bases_end();
1209 I != E; ++I) {
1210 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1211 if (!Base)
1212 continue;
1213
1214 Base = Base->getDefinition();
1215 if (!Base)
1216 continue;
1217
1218 if (Base->getCanonicalDecl() == Class)
1219 return true;
1220
1221 Queue.push_back(Base);
1222 }
1223
1224 if (Queue.empty())
1225 return false;
1226
1227 Current = Queue.back();
1228 Queue.pop_back();
1229 }
1230
1231 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001232}
1233
Mike Stump1eb44332009-09-09 15:08:12 +00001234/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001235///
1236/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1237/// and returns NULL otherwise.
1238CXXBaseSpecifier *
1239Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1240 SourceRange SpecifierRange,
1241 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001242 TypeSourceInfo *TInfo,
1243 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001244 QualType BaseType = TInfo->getType();
1245
Douglas Gregor2943aed2009-03-03 04:44:36 +00001246 // C++ [class.union]p1:
1247 // A union shall not have base classes.
1248 if (Class->isUnion()) {
1249 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1250 << SpecifierRange;
1251 return 0;
1252 }
1253
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001254 if (EllipsisLoc.isValid() &&
1255 !TInfo->getType()->containsUnexpandedParameterPack()) {
1256 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1257 << TInfo->getTypeLoc().getSourceRange();
1258 EllipsisLoc = SourceLocation();
1259 }
Douglas Gregord777e282012-11-10 01:18:17 +00001260
1261 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1262
1263 if (BaseType->isDependentType()) {
1264 // Make sure that we don't have circular inheritance among our dependent
1265 // bases. For non-dependent bases, the check for completeness below handles
1266 // this.
1267 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1268 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1269 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001270 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001271 Diag(BaseLoc, diag::err_circular_inheritance)
1272 << BaseType << Context.getTypeDeclType(Class);
1273
1274 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1275 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1276 << BaseType;
1277
1278 return 0;
1279 }
1280 }
1281
Mike Stump1eb44332009-09-09 15:08:12 +00001282 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001283 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001284 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001285 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001286
1287 // Base specifiers must be record types.
1288 if (!BaseType->isRecordType()) {
1289 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1290 return 0;
1291 }
1292
1293 // C++ [class.union]p1:
1294 // A union shall not be used as a base class.
1295 if (BaseType->isUnionType()) {
1296 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1297 return 0;
1298 }
1299
1300 // C++ [class.derived]p2:
1301 // The class-name in a base-specifier shall not be an incompletely
1302 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001303 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001304 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001305 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001306 return 0;
John McCall572fc622010-08-17 07:23:57 +00001307 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001308
Eli Friedman1d954f62009-08-15 21:55:26 +00001309 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001310 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001311 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001312 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001313 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer585bee42013-06-06 23:43:20 +00001314 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001315 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001316
Anders Carlsson1d209272011-03-25 14:55:14 +00001317 // C++ [class]p3:
1318 // If a class is marked final and it appears as a base-type-specifier in
1319 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001320 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001321 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1322 << CXXBaseDecl->getDeclName();
1323 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1324 << CXXBaseDecl->getDeclName();
1325 return 0;
1326 }
1327
John McCall572fc622010-08-17 07:23:57 +00001328 if (BaseDecl->isInvalidDecl())
1329 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001330
1331 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001332 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001333 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001334 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001335}
1336
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001337/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1338/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001339/// example:
1340/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001341/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001342BaseResult
John McCalld226f652010-08-21 09:40:31 +00001343Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001344 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001345 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001346 ParsedType basetype, SourceLocation BaseLoc,
1347 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001348 if (!classdecl)
1349 return true;
1350
Douglas Gregor40808ce2009-03-09 23:48:35 +00001351 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001352 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001353 if (!Class)
1354 return true;
1355
Richard Smith05321402013-02-19 23:47:15 +00001356 // We do not support any C++11 attributes on base-specifiers yet.
1357 // Diagnose any attributes we see.
1358 if (!Attributes.empty()) {
1359 for (AttributeList *Attr = Attributes.getList(); Attr;
1360 Attr = Attr->getNext()) {
1361 if (Attr->isInvalid() ||
1362 Attr->getKind() == AttributeList::IgnoredAttribute)
1363 continue;
1364 Diag(Attr->getLoc(),
1365 Attr->getKind() == AttributeList::UnknownAttribute
1366 ? diag::warn_unknown_attribute_ignored
1367 : diag::err_base_specifier_attribute)
1368 << Attr->getName();
1369 }
1370 }
1371
Nick Lewycky56062202010-07-26 16:56:01 +00001372 TypeSourceInfo *TInfo = 0;
1373 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001374
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001375 if (EllipsisLoc.isInvalid() &&
1376 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001377 UPPC_BaseType))
1378 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001379
Douglas Gregor2943aed2009-03-03 04:44:36 +00001380 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001381 Virtual, Access, TInfo,
1382 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001383 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001384 else
1385 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Douglas Gregor2943aed2009-03-03 04:44:36 +00001387 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001388}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001389
Douglas Gregor2943aed2009-03-03 04:44:36 +00001390/// \brief Performs the actual work of attaching the given base class
1391/// specifiers to a C++ class.
1392bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1393 unsigned NumBases) {
1394 if (NumBases == 0)
1395 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001396
1397 // Used to keep track of which base types we have already seen, so
1398 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001399 // that the key is always the unqualified canonical type of the base
1400 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001401 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1402
1403 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001404 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001405 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001406 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001407 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001408 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001409 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001410
1411 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1412 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001413 // C++ [class.mi]p3:
1414 // A class shall not be specified as a direct base class of a
1415 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001416 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001417 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001418 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001419 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001420
1421 // Delete the duplicate base class specifier; we're going to
1422 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001423 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001424
1425 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001426 } else {
1427 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001428 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001429 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001430 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1431 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1432 if (Class->isInterface() &&
1433 (!RD->isInterface() ||
1434 KnownBase->getAccessSpecifier() != AS_public)) {
1435 // The Microsoft extension __interface does not permit bases that
1436 // are not themselves public interfaces.
1437 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1438 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1439 << RD->getSourceRange();
1440 Invalid = true;
1441 }
1442 if (RD->hasAttr<WeakAttr>())
1443 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1444 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001445 }
1446 }
1447
1448 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001449 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001450
1451 // Delete the remaining (good) base class specifiers, since their
1452 // data has been copied into the CXXRecordDecl.
1453 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001454 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001455
1456 return Invalid;
1457}
1458
1459/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1460/// class, after checking whether there are any duplicate base
1461/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001462void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001463 unsigned NumBases) {
1464 if (!ClassDecl || !Bases || !NumBases)
1465 return;
1466
1467 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001468 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001469 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001470}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001471
Douglas Gregora8f32e02009-10-06 17:59:45 +00001472/// \brief Determine whether the type \p Derived is a C++ class that is
1473/// derived from the type \p Base.
1474bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001475 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001476 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001477
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001478 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001479 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001480 return false;
1481
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001482 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001483 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001484 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001485
1486 // If either the base or the derived type is invalid, don't try to
1487 // check whether one is derived from the other.
1488 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1489 return false;
1490
John McCall86ff3082010-02-04 22:26:26 +00001491 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1492 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001493}
1494
1495/// \brief Determine whether the type \p Derived is a C++ class that is
1496/// derived from the type \p Base.
1497bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001498 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001499 return false;
1500
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001501 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001502 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001503 return false;
1504
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001505 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001506 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001507 return false;
1508
Douglas Gregora8f32e02009-10-06 17:59:45 +00001509 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1510}
1511
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001512void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001513 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001514 assert(BasePathArray.empty() && "Base path array must be empty!");
1515 assert(Paths.isRecordingPaths() && "Must record paths!");
1516
1517 const CXXBasePath &Path = Paths.front();
1518
1519 // We first go backward and check if we have a virtual base.
1520 // FIXME: It would be better if CXXBasePath had the base specifier for
1521 // the nearest virtual base.
1522 unsigned Start = 0;
1523 for (unsigned I = Path.size(); I != 0; --I) {
1524 if (Path[I - 1].Base->isVirtual()) {
1525 Start = I - 1;
1526 break;
1527 }
1528 }
1529
1530 // Now add all bases.
1531 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001532 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001533}
1534
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001535/// \brief Determine whether the given base path includes a virtual
1536/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001537bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1538 for (CXXCastPath::const_iterator B = BasePath.begin(),
1539 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001540 B != BEnd; ++B)
1541 if ((*B)->isVirtual())
1542 return true;
1543
1544 return false;
1545}
1546
Douglas Gregora8f32e02009-10-06 17:59:45 +00001547/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1548/// conversion (where Derived and Base are class types) is
1549/// well-formed, meaning that the conversion is unambiguous (and
1550/// that all of the base classes are accessible). Returns true
1551/// and emits a diagnostic if the code is ill-formed, returns false
1552/// otherwise. Loc is the location where this routine should point to
1553/// if there is an error, and Range is the source range to highlight
1554/// if there is an error.
1555bool
1556Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001557 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001558 unsigned AmbigiousBaseConvID,
1559 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001560 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001561 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001562 // First, determine whether the path from Derived to Base is
1563 // ambiguous. This is slightly more expensive than checking whether
1564 // the Derived to Base conversion exists, because here we need to
1565 // explore multiple paths to determine if there is an ambiguity.
1566 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1567 /*DetectVirtual=*/false);
1568 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1569 assert(DerivationOkay &&
1570 "Can only be used with a derived-to-base conversion");
1571 (void)DerivationOkay;
1572
1573 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001574 if (InaccessibleBaseID) {
1575 // Check that the base class can be accessed.
1576 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1577 InaccessibleBaseID)) {
1578 case AR_inaccessible:
1579 return true;
1580 case AR_accessible:
1581 case AR_dependent:
1582 case AR_delayed:
1583 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001584 }
John McCall6b2accb2010-02-10 09:31:12 +00001585 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001586
1587 // Build a base path if necessary.
1588 if (BasePath)
1589 BuildBasePathArray(Paths, *BasePath);
1590 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001591 }
1592
1593 // We know that the derived-to-base conversion is ambiguous, and
1594 // we're going to produce a diagnostic. Perform the derived-to-base
1595 // search just one more time to compute all of the possible paths so
1596 // that we can print them out. This is more expensive than any of
1597 // the previous derived-to-base checks we've done, but at this point
1598 // performance isn't as much of an issue.
1599 Paths.clear();
1600 Paths.setRecordingPaths(true);
1601 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1602 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1603 (void)StillOkay;
1604
1605 // Build up a textual representation of the ambiguous paths, e.g.,
1606 // D -> B -> A, that will be used to illustrate the ambiguous
1607 // conversions in the diagnostic. We only print one of the paths
1608 // to each base class subobject.
1609 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1610
1611 Diag(Loc, AmbigiousBaseConvID)
1612 << Derived << Base << PathDisplayStr << Range << Name;
1613 return true;
1614}
1615
1616bool
1617Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001618 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001619 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001620 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001621 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001622 IgnoreAccess ? 0
1623 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001624 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001625 Loc, Range, DeclarationName(),
1626 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001627}
1628
1629
1630/// @brief Builds a string representing ambiguous paths from a
1631/// specific derived class to different subobjects of the same base
1632/// class.
1633///
1634/// This function builds a string that can be used in error messages
1635/// to show the different paths that one can take through the
1636/// inheritance hierarchy to go from the derived class to different
1637/// subobjects of a base class. The result looks something like this:
1638/// @code
1639/// struct D -> struct B -> struct A
1640/// struct D -> struct C -> struct A
1641/// @endcode
1642std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1643 std::string PathDisplayStr;
1644 std::set<unsigned> DisplayedPaths;
1645 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1646 Path != Paths.end(); ++Path) {
1647 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1648 // We haven't displayed a path to this particular base
1649 // class subobject yet.
1650 PathDisplayStr += "\n ";
1651 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1652 for (CXXBasePath::const_iterator Element = Path->begin();
1653 Element != Path->end(); ++Element)
1654 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1655 }
1656 }
1657
1658 return PathDisplayStr;
1659}
1660
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001661//===----------------------------------------------------------------------===//
1662// C++ class member Handling
1663//===----------------------------------------------------------------------===//
1664
Abramo Bagnara6206d532010-06-05 05:09:32 +00001665/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001666bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1667 SourceLocation ASLoc,
1668 SourceLocation ColonLoc,
1669 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001670 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001671 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001672 ASLoc, ColonLoc);
1673 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001674 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001675}
1676
Richard Smitha4b39652012-08-06 03:25:17 +00001677/// CheckOverrideControl - Check C++11 override control semantics.
1678void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001679 if (D->isInvalidDecl())
1680 return;
1681
Chris Lattner5f9e2722011-07-23 10:55:15 +00001682 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001683
Richard Smitha4b39652012-08-06 03:25:17 +00001684 // Do we know which functions this declaration might be overriding?
1685 bool OverridesAreKnown = !MD ||
1686 (!MD->getParent()->hasAnyDependentBases() &&
1687 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001688
Richard Smitha4b39652012-08-06 03:25:17 +00001689 if (!MD || !MD->isVirtual()) {
1690 if (OverridesAreKnown) {
1691 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1692 Diag(OA->getLocation(),
1693 diag::override_keyword_only_allowed_on_virtual_member_functions)
1694 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1695 D->dropAttr<OverrideAttr>();
1696 }
1697 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1698 Diag(FA->getLocation(),
1699 diag::override_keyword_only_allowed_on_virtual_member_functions)
1700 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1701 D->dropAttr<FinalAttr>();
1702 }
1703 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001704 return;
1705 }
Richard Smitha4b39652012-08-06 03:25:17 +00001706
1707 if (!OverridesAreKnown)
1708 return;
1709
1710 // C++11 [class.virtual]p5:
1711 // If a virtual function is marked with the virt-specifier override and
1712 // does not override a member function of a base class, the program is
1713 // ill-formed.
1714 bool HasOverriddenMethods =
1715 MD->begin_overridden_methods() != MD->end_overridden_methods();
1716 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1717 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1718 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001719}
1720
Richard Smitha4b39652012-08-06 03:25:17 +00001721/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001722/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001723/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001724bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1725 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001726 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001727 return false;
1728
1729 Diag(New->getLocation(), diag::err_final_function_overridden)
1730 << New->getDeclName();
1731 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1732 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001733}
1734
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001735static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001736 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1737 // FIXME: Destruction of ObjC lifetime types has side-effects.
1738 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1739 return !RD->isCompleteDefinition() ||
1740 !RD->hasTrivialDefaultConstructor() ||
1741 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001742 return false;
1743}
1744
John McCall76da55d2013-04-16 07:28:30 +00001745static AttributeList *getMSPropertyAttr(AttributeList *list) {
1746 for (AttributeList* it = list; it != 0; it = it->getNext())
1747 if (it->isDeclspecPropertyAttribute())
1748 return it;
1749 return 0;
1750}
1751
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001752/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1753/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001754/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001755/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1756/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001757NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001758Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001759 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001760 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001761 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001762 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001763 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1764 DeclarationName Name = NameInfo.getName();
1765 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001766
1767 // For anonymous bitfields, the location should point to the type.
1768 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001769 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001770
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001771 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001772
John McCall4bde1e12010-06-04 08:34:12 +00001773 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001774 assert(!DS.isFriendSpecified());
1775
Richard Smith1ab0d902011-06-25 02:28:38 +00001776 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001777
John McCalle402e722012-09-25 07:32:39 +00001778 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1779 // The Microsoft extension __interface only permits public member functions
1780 // and prohibits constructors, destructors, operators, non-public member
1781 // functions, static methods and data members.
1782 unsigned InvalidDecl;
1783 bool ShowDeclName = true;
1784 if (!isFunc)
1785 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1786 else if (AS != AS_public)
1787 InvalidDecl = 2;
1788 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1789 InvalidDecl = 3;
1790 else switch (Name.getNameKind()) {
1791 case DeclarationName::CXXConstructorName:
1792 InvalidDecl = 4;
1793 ShowDeclName = false;
1794 break;
1795
1796 case DeclarationName::CXXDestructorName:
1797 InvalidDecl = 5;
1798 ShowDeclName = false;
1799 break;
1800
1801 case DeclarationName::CXXOperatorName:
1802 case DeclarationName::CXXConversionFunctionName:
1803 InvalidDecl = 6;
1804 break;
1805
1806 default:
1807 InvalidDecl = 0;
1808 break;
1809 }
1810
1811 if (InvalidDecl) {
1812 if (ShowDeclName)
1813 Diag(Loc, diag::err_invalid_member_in_interface)
1814 << (InvalidDecl-1) << Name;
1815 else
1816 Diag(Loc, diag::err_invalid_member_in_interface)
1817 << (InvalidDecl-1) << "";
1818 return 0;
1819 }
1820 }
1821
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001822 // C++ 9.2p6: A member shall not be declared to have automatic storage
1823 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001824 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1825 // data members and cannot be applied to names declared const or static,
1826 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001827 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001828 case DeclSpec::SCS_unspecified:
1829 case DeclSpec::SCS_typedef:
1830 case DeclSpec::SCS_static:
1831 break;
1832 case DeclSpec::SCS_mutable:
1833 if (isFunc) {
1834 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001835
Richard Smithec642442013-04-12 22:46:28 +00001836 // FIXME: It would be nicer if the keyword was ignored only for this
1837 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001838 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001839 }
1840 break;
1841 default:
1842 Diag(DS.getStorageClassSpecLoc(),
1843 diag::err_storageclass_invalid_for_member);
1844 D.getMutableDeclSpec().ClearStorageClassSpecs();
1845 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001846 }
1847
Sebastian Redl669d5d72008-11-14 23:42:31 +00001848 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1849 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001850 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001851
David Blaikie1d87fba2013-01-30 01:22:18 +00001852 if (DS.isConstexprSpecified() && isInstField) {
1853 SemaDiagnosticBuilder B =
1854 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1855 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1856 if (InitStyle == ICIS_NoInit) {
1857 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1858 D.getMutableDeclSpec().ClearConstexprSpec();
1859 const char *PrevSpec;
1860 unsigned DiagID;
1861 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1862 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001863 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001864 assert(!Failed && "Making a constexpr member const shouldn't fail");
1865 } else {
1866 B << 1;
1867 const char *PrevSpec;
1868 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001869 if (D.getMutableDeclSpec().SetStorageClassSpec(
1870 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001871 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001872 "This is the only DeclSpec that should fail to be applied");
1873 B << 1;
1874 } else {
1875 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1876 isInstField = false;
1877 }
1878 }
1879 }
1880
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001881 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001882 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001883 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001884
1885 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001886 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001887 Diag(Loc, diag::err_bad_variable_name)
1888 << Name;
1889 return 0;
1890 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001891
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001892 IdentifierInfo *II = Name.getAsIdentifierInfo();
1893
Douglas Gregorf2503652011-09-21 14:40:46 +00001894 // Member field could not be with "template" keyword.
1895 // So TemplateParameterLists should be empty in this case.
1896 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001897 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001898 if (TemplateParams->size()) {
1899 // There is no such thing as a member field template.
1900 Diag(D.getIdentifierLoc(), diag::err_template_member)
1901 << II
1902 << SourceRange(TemplateParams->getTemplateLoc(),
1903 TemplateParams->getRAngleLoc());
1904 } else {
1905 // There is an extraneous 'template<>' for this member.
1906 Diag(TemplateParams->getTemplateLoc(),
1907 diag::err_template_member_noparams)
1908 << II
1909 << SourceRange(TemplateParams->getTemplateLoc(),
1910 TemplateParams->getRAngleLoc());
1911 }
1912 return 0;
1913 }
1914
Douglas Gregor922fff22010-10-13 22:19:53 +00001915 if (SS.isSet() && !SS.isInvalid()) {
1916 // The user provided a superfluous scope specifier inside a class
1917 // definition:
1918 //
1919 // class X {
1920 // int X::member;
1921 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001922 if (DeclContext *DC = computeDeclContext(SS, false))
1923 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001924 else
1925 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1926 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001927
Douglas Gregor922fff22010-10-13 22:19:53 +00001928 SS.clear();
1929 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001930
John McCall76da55d2013-04-16 07:28:30 +00001931 AttributeList *MSPropertyAttr =
1932 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1933 if (MSPropertyAttr) {
1934 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1935 BitWidth, InitStyle, AS, MSPropertyAttr);
1936 isInstField = false;
1937 } else {
1938 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1939 BitWidth, InitStyle, AS);
1940 }
Chris Lattner6f8ce142009-03-05 23:03:49 +00001941 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001942 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001943 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001944
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001945 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001946 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001947 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001948 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001949
1950 // Non-instance-fields can't have a bitfield.
1951 if (BitWidth) {
1952 if (Member->isInvalidDecl()) {
1953 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001954 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001955 // C++ 9.6p3: A bit-field shall not be a static member.
1956 // "static member 'A' cannot be a bit-field"
1957 Diag(Loc, diag::err_static_not_bitfield)
1958 << Name << BitWidth->getSourceRange();
1959 } else if (isa<TypedefDecl>(Member)) {
1960 // "typedef member 'x' cannot be a bit-field"
1961 Diag(Loc, diag::err_typedef_not_bitfield)
1962 << Name << BitWidth->getSourceRange();
1963 } else {
1964 // A function typedef ("typedef int f(); f a;").
1965 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1966 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001967 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001968 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001969 }
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Chris Lattner8b963ef2009-03-05 23:01:03 +00001971 BitWidth = 0;
1972 Member->setInvalidDecl();
1973 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001974
1975 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Douglas Gregor37b372b2009-08-20 22:52:58 +00001977 // If we have declared a member function template, set the access of the
1978 // templated declaration as well.
1979 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1980 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001981 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001982
Richard Smitha4b39652012-08-06 03:25:17 +00001983 if (VS.isOverrideSpecified())
1984 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1985 if (VS.isFinalSpecified())
1986 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001987
Douglas Gregorf5251602011-03-08 17:10:18 +00001988 if (VS.getLastLocation().isValid()) {
1989 // Update the end location of a method that has a virt-specifiers.
1990 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1991 MD->setRangeEnd(VS.getLastLocation());
1992 }
Richard Smitha4b39652012-08-06 03:25:17 +00001993
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001994 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001995
Douglas Gregor10bd3682008-11-17 22:58:34 +00001996 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001997
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001998 if (isInstField) {
1999 FieldDecl *FD = cast<FieldDecl>(Member);
2000 FieldCollector->Add(FD);
2001
2002 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2003 FD->getLocation())
2004 != DiagnosticsEngine::Ignored) {
2005 // Remember all explicit private FieldDecls that have a name, no side
2006 // effects and are not part of a dependent type declaration.
2007 if (!FD->isImplicit() && FD->getDeclName() &&
2008 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002009 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002010 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002011 !InitializationHasSideEffects(*FD))
2012 UnusedPrivateFields.insert(FD);
2013 }
2014 }
2015
John McCalld226f652010-08-21 09:40:31 +00002016 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002017}
2018
Hans Wennborg471f9852012-09-18 15:58:06 +00002019namespace {
2020 class UninitializedFieldVisitor
2021 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2022 Sema &S;
2023 ValueDecl *VD;
2024 public:
2025 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2026 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002027 S(S) {
2028 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2029 this->VD = IFD->getAnonField();
2030 else
2031 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002032 }
2033
2034 void HandleExpr(Expr *E) {
2035 if (!E) return;
2036
2037 // Expressions like x(x) sometimes lack the surrounding expressions
2038 // but need to be checked anyways.
2039 HandleValue(E);
2040 Visit(E);
2041 }
2042
2043 void HandleValue(Expr *E) {
2044 E = E->IgnoreParens();
2045
2046 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2047 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002048 return;
2049
2050 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2051 // or union.
2052 MemberExpr *FieldME = ME;
2053
Hans Wennborg471f9852012-09-18 15:58:06 +00002054 Expr *Base = E;
2055 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002056 ME = cast<MemberExpr>(Base);
2057
2058 if (isa<VarDecl>(ME->getMemberDecl()))
2059 return;
2060
2061 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2062 if (!FD->isAnonymousStructOrUnion())
2063 FieldME = ME;
2064
Hans Wennborg471f9852012-09-18 15:58:06 +00002065 Base = ME->getBase();
2066 }
2067
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002068 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00002069 unsigned diag = VD->getType()->isReferenceType()
2070 ? diag::warn_reference_field_is_uninit
2071 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002072 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002073 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002074 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002075 }
2076
2077 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2078 HandleValue(CO->getTrueExpr());
2079 HandleValue(CO->getFalseExpr());
2080 return;
2081 }
2082
2083 if (BinaryConditionalOperator *BCO =
2084 dyn_cast<BinaryConditionalOperator>(E)) {
2085 HandleValue(BCO->getCommon());
2086 HandleValue(BCO->getFalseExpr());
2087 return;
2088 }
2089
2090 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2091 switch (BO->getOpcode()) {
2092 default:
2093 return;
2094 case(BO_PtrMemD):
2095 case(BO_PtrMemI):
2096 HandleValue(BO->getLHS());
2097 return;
2098 case(BO_Comma):
2099 HandleValue(BO->getRHS());
2100 return;
2101 }
2102 }
2103 }
2104
2105 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2106 if (E->getCastKind() == CK_LValueToRValue)
2107 HandleValue(E->getSubExpr());
2108
2109 Inherited::VisitImplicitCastExpr(E);
2110 }
2111
2112 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2113 Expr *Callee = E->getCallee();
2114 if (isa<MemberExpr>(Callee))
2115 HandleValue(Callee);
2116
2117 Inherited::VisitCXXMemberCallExpr(E);
2118 }
2119 };
2120 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2121 ValueDecl *VD) {
2122 UninitializedFieldVisitor(S, VD).HandleExpr(E);
2123 }
2124} // namespace
2125
Richard Smith7a614d82011-06-11 17:19:42 +00002126/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002127/// in-class initializer for a non-static C++ class member, and after
2128/// instantiating an in-class initializer in a class template. Such actions
2129/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002130void
Richard Smithca523302012-06-10 03:12:00 +00002131Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002132 Expr *InitExpr) {
2133 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002134 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2135 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002136
2137 if (!InitExpr) {
2138 FD->setInvalidDecl();
2139 FD->removeInClassInitializer();
2140 return;
2141 }
2142
Peter Collingbournefef21892011-10-23 18:59:44 +00002143 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2144 FD->setInvalidDecl();
2145 FD->removeInClassInitializer();
2146 return;
2147 }
2148
Hans Wennborg471f9852012-09-18 15:58:06 +00002149 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2150 != DiagnosticsEngine::Ignored) {
2151 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2152 }
2153
Richard Smith7a614d82011-06-11 17:19:42 +00002154 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002155 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00002156 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002157 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00002158 << /*at end of ctor*/1 << InitExpr->getSourceRange();
2159 }
Sebastian Redl33deb352012-02-22 10:50:08 +00002160 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002161 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002162 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002163 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002164 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2165 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002166 if (Init.isInvalid()) {
2167 FD->setInvalidDecl();
2168 return;
2169 }
Richard Smith7a614d82011-06-11 17:19:42 +00002170 }
2171
Richard Smith41956372013-01-14 22:39:08 +00002172 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002173 // The initialization of each base and member constitutes a
2174 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002175 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002176 if (Init.isInvalid()) {
2177 FD->setInvalidDecl();
2178 return;
2179 }
2180
2181 InitExpr = Init.release();
2182
2183 FD->setInClassInitializer(InitExpr);
2184}
2185
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002186/// \brief Find the direct and/or virtual base specifiers that
2187/// correspond to the given base type, for use in base initialization
2188/// within a constructor.
2189static bool FindBaseInitializer(Sema &SemaRef,
2190 CXXRecordDecl *ClassDecl,
2191 QualType BaseType,
2192 const CXXBaseSpecifier *&DirectBaseSpec,
2193 const CXXBaseSpecifier *&VirtualBaseSpec) {
2194 // First, check for a direct base class.
2195 DirectBaseSpec = 0;
2196 for (CXXRecordDecl::base_class_const_iterator Base
2197 = ClassDecl->bases_begin();
2198 Base != ClassDecl->bases_end(); ++Base) {
2199 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2200 // We found a direct base of this type. That's what we're
2201 // initializing.
2202 DirectBaseSpec = &*Base;
2203 break;
2204 }
2205 }
2206
2207 // Check for a virtual base class.
2208 // FIXME: We might be able to short-circuit this if we know in advance that
2209 // there are no virtual bases.
2210 VirtualBaseSpec = 0;
2211 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2212 // We haven't found a base yet; search the class hierarchy for a
2213 // virtual base class.
2214 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2215 /*DetectVirtual=*/false);
2216 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2217 BaseType, Paths)) {
2218 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2219 Path != Paths.end(); ++Path) {
2220 if (Path->back().Base->isVirtual()) {
2221 VirtualBaseSpec = Path->back().Base;
2222 break;
2223 }
2224 }
2225 }
2226 }
2227
2228 return DirectBaseSpec || VirtualBaseSpec;
2229}
2230
Sebastian Redl6df65482011-09-24 17:48:25 +00002231/// \brief Handle a C++ member initializer using braced-init-list syntax.
2232MemInitResult
2233Sema::ActOnMemInitializer(Decl *ConstructorD,
2234 Scope *S,
2235 CXXScopeSpec &SS,
2236 IdentifierInfo *MemberOrBase,
2237 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002238 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002239 SourceLocation IdLoc,
2240 Expr *InitList,
2241 SourceLocation EllipsisLoc) {
2242 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002243 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002244 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002245}
2246
2247/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002248MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002249Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002250 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002251 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002252 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002253 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002254 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002255 SourceLocation IdLoc,
2256 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002257 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002258 SourceLocation RParenLoc,
2259 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002260 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002261 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002262 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002263 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002264}
2265
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002266namespace {
2267
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002268// Callback to only accept typo corrections that can be a valid C++ member
2269// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002270class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2271 public:
2272 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2273 : ClassDecl(ClassDecl) {}
2274
2275 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2276 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2277 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2278 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2279 else
2280 return isa<TypeDecl>(ND);
2281 }
2282 return false;
2283 }
2284
2285 private:
2286 CXXRecordDecl *ClassDecl;
2287};
2288
2289}
2290
Sebastian Redl6df65482011-09-24 17:48:25 +00002291/// \brief Handle a C++ member initializer.
2292MemInitResult
2293Sema::BuildMemInitializer(Decl *ConstructorD,
2294 Scope *S,
2295 CXXScopeSpec &SS,
2296 IdentifierInfo *MemberOrBase,
2297 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002298 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002299 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002300 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002301 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002302 if (!ConstructorD)
2303 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002305 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002306
2307 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002308 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002309 if (!Constructor) {
2310 // The user wrote a constructor initializer on a function that is
2311 // not a C++ constructor. Ignore the error for now, because we may
2312 // have more member initializers coming; we'll diagnose it just
2313 // once in ActOnMemInitializers.
2314 return true;
2315 }
2316
2317 CXXRecordDecl *ClassDecl = Constructor->getParent();
2318
2319 // C++ [class.base.init]p2:
2320 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002321 // constructor's class and, if not found in that scope, are looked
2322 // up in the scope containing the constructor's definition.
2323 // [Note: if the constructor's class contains a member with the
2324 // same name as a direct or virtual base class of the class, a
2325 // mem-initializer-id naming the member or base class and composed
2326 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002327 // mem-initializer-id for the hidden base class may be specified
2328 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002329 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002330 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002331 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002332 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002333 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002334 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002335 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2336 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002337 if (EllipsisLoc.isValid())
2338 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002339 << MemberOrBase
2340 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002341
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002342 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002343 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002344 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002345 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002346 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002347 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002348 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002349
2350 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002351 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002352 } else if (DS.getTypeSpecType() == TST_decltype) {
2353 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002354 } else {
2355 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2356 LookupParsedName(R, S, &SS);
2357
2358 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2359 if (!TyD) {
2360 if (R.isAmbiguous()) return true;
2361
John McCallfd225442010-04-09 19:01:14 +00002362 // We don't want access-control diagnostics here.
2363 R.suppressDiagnostics();
2364
Douglas Gregor7a886e12010-01-19 06:46:48 +00002365 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2366 bool NotUnknownSpecialization = false;
2367 DeclContext *DC = computeDeclContext(SS, false);
2368 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2369 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2370
2371 if (!NotUnknownSpecialization) {
2372 // When the scope specifier can refer to a member of an unknown
2373 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002374 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2375 SS.getWithLocInContext(Context),
2376 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002377 if (BaseType.isNull())
2378 return true;
2379
Douglas Gregor7a886e12010-01-19 06:46:48 +00002380 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002381 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002382 }
2383 }
2384
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002385 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002386 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002387 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002388 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002389 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002390 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002391 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2392 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002393 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002394 // We have found a non-static data member with a similar
2395 // name to what was typed; complain and initialize that
2396 // member.
2397 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2398 << MemberOrBase << true << CorrectedQuotedStr
2399 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2400 Diag(Member->getLocation(), diag::note_previous_decl)
2401 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002402
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002403 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002404 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002405 const CXXBaseSpecifier *DirectBaseSpec;
2406 const CXXBaseSpecifier *VirtualBaseSpec;
2407 if (FindBaseInitializer(*this, ClassDecl,
2408 Context.getTypeDeclType(Type),
2409 DirectBaseSpec, VirtualBaseSpec)) {
2410 // We have found a direct or virtual base class with a
2411 // similar name to what was typed; complain and initialize
2412 // that base class.
2413 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002414 << MemberOrBase << false << CorrectedQuotedStr
2415 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002416
2417 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2418 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002419 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002420 diag::note_base_class_specified_here)
2421 << BaseSpec->getType()
2422 << BaseSpec->getSourceRange();
2423
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002424 TyD = Type;
2425 }
2426 }
2427 }
2428
Douglas Gregor7a886e12010-01-19 06:46:48 +00002429 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002430 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002431 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002432 return true;
2433 }
John McCall2b194412009-12-21 10:41:20 +00002434 }
2435
Douglas Gregor7a886e12010-01-19 06:46:48 +00002436 if (BaseType.isNull()) {
2437 BaseType = Context.getTypeDeclType(TyD);
2438 if (SS.isSet()) {
2439 NestedNameSpecifier *Qualifier =
2440 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002441
Douglas Gregor7a886e12010-01-19 06:46:48 +00002442 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002443 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002444 }
John McCall2b194412009-12-21 10:41:20 +00002445 }
2446 }
Mike Stump1eb44332009-09-09 15:08:12 +00002447
John McCalla93c9342009-12-07 02:54:59 +00002448 if (!TInfo)
2449 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002450
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002451 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002452}
2453
Chandler Carruth81c64772011-09-03 01:14:15 +00002454/// Checks a member initializer expression for cases where reference (or
2455/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002456static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2457 Expr *Init,
2458 SourceLocation IdLoc) {
2459 QualType MemberTy = Member->getType();
2460
2461 // We only handle pointers and references currently.
2462 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2463 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2464 return;
2465
2466 const bool IsPointer = MemberTy->isPointerType();
2467 if (IsPointer) {
2468 if (const UnaryOperator *Op
2469 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2470 // The only case we're worried about with pointers requires taking the
2471 // address.
2472 if (Op->getOpcode() != UO_AddrOf)
2473 return;
2474
2475 Init = Op->getSubExpr();
2476 } else {
2477 // We only handle address-of expression initializers for pointers.
2478 return;
2479 }
2480 }
2481
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002482 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2483 // Taking the address of a temporary will be diagnosed as a hard error.
2484 if (IsPointer)
2485 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002486
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002487 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2488 << Member << Init->getSourceRange();
2489 } else if (const DeclRefExpr *DRE
2490 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2491 // We only warn when referring to a non-reference parameter declaration.
2492 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2493 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002494 return;
2495
2496 S.Diag(Init->getExprLoc(),
2497 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2498 : diag::warn_bind_ref_member_to_parameter)
2499 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002500 } else {
2501 // Other initializers are fine.
2502 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002503 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002504
2505 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2506 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002507}
2508
John McCallf312b1e2010-08-26 23:41:50 +00002509MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002510Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002511 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002512 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2513 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2514 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002515 "Member must be a FieldDecl or IndirectFieldDecl");
2516
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002517 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002518 return true;
2519
Douglas Gregor464b2f02010-11-05 22:21:31 +00002520 if (Member->isInvalidDecl())
2521 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002522
John McCallb4190042009-11-04 23:02:40 +00002523 // Diagnose value-uses of fields to initialize themselves, e.g.
2524 // foo(foo)
2525 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002526 // TODO: implement -Wuninitialized and fold this into that framework.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002527 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002528 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002529 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002530 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002531 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002532 } else {
2533 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002534 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002535 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002536
Richard Trieude5e75c2012-06-14 23:11:34 +00002537 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2538 != DiagnosticsEngine::Ignored)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002539 for (unsigned i = 0, e = Args.size(); i != e; ++i)
Richard Trieude5e75c2012-06-14 23:11:34 +00002540 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002541 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002542 // initializing the i'th field, throw a warning if any of the >= i'th
2543 // fields are used, as they are not yet initialized.
2544 // Right now we are only handling the case where the i'th field uses
2545 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002546 // Also need to take into account that some fields may be initialized by
2547 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002548 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002549
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002550 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002551
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002552 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002553 // Can't check initialization for a member of dependent type or when
2554 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002555 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002556 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002557 bool InitList = false;
2558 if (isa<InitListExpr>(Init)) {
2559 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002560 Args = Init;
Sebastian Redl772291a2012-02-19 16:31:05 +00002561
2562 if (isStdInitializerList(Member->getType(), 0)) {
2563 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2564 << /*at end of ctor*/1 << InitRange;
2565 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002566 }
2567
Chandler Carruth894aed92010-12-06 09:23:57 +00002568 // Initialize the member.
2569 InitializedEntity MemberEntity =
2570 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2571 : InitializedEntity::InitializeMember(IndirectMember, 0);
2572 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002573 InitList ? InitializationKind::CreateDirectList(IdLoc)
2574 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2575 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002576
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002577 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2578 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002579 if (MemberInit.isInvalid())
2580 return true;
2581
Richard Smith41956372013-01-14 22:39:08 +00002582 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002583 // The initialization of each base and member constitutes a
2584 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002585 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002586 if (MemberInit.isInvalid())
2587 return true;
2588
Richard Smithc83c2302012-12-19 01:39:02 +00002589 Init = MemberInit.get();
2590 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002591 }
2592
Chandler Carruth894aed92010-12-06 09:23:57 +00002593 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002594 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2595 InitRange.getBegin(), Init,
2596 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002597 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002598 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2599 InitRange.getBegin(), Init,
2600 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002601 }
Eli Friedman59c04372009-07-29 19:44:27 +00002602}
2603
John McCallf312b1e2010-08-26 23:41:50 +00002604MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002605Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002606 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002607 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002608 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002609 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002610 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002611 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002612
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002613 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002614 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002615 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2616 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002617 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002618 }
2619
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002620 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002621 // Initialize the object.
2622 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2623 QualType(ClassDecl->getTypeForDecl(), 0));
2624 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002625 InitList ? InitializationKind::CreateDirectList(NameLoc)
2626 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2627 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002628 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002629 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002630 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002631 if (DelegationInit.isInvalid())
2632 return true;
2633
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002634 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2635 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002636
Richard Smith41956372013-01-14 22:39:08 +00002637 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002638 // The initialization of each base and member constitutes a
2639 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002640 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2641 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002642 if (DelegationInit.isInvalid())
2643 return true;
2644
Eli Friedmand21016f2012-05-19 23:35:23 +00002645 // If we are in a dependent context, template instantiation will
2646 // perform this type-checking again. Just save the arguments that we
2647 // received in a ParenListExpr.
2648 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2649 // of the information that we have about the base
2650 // initializer. However, deconstructing the ASTs is a dicey process,
2651 // and this approach is far more likely to get the corner cases right.
2652 if (CurContext->isDependentContext())
2653 DelegationInit = Owned(Init);
2654
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002655 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002656 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002657 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002658}
2659
2660MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002661Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002662 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002663 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002664 SourceLocation BaseLoc
2665 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002666
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002667 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2668 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2669 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2670
2671 // C++ [class.base.init]p2:
2672 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002673 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002674 // of that class, the mem-initializer is ill-formed. A
2675 // mem-initializer-list can initialize a base class using any
2676 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002677 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002678
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002679 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002680 if (EllipsisLoc.isValid()) {
2681 // This is a pack expansion.
2682 if (!BaseType->containsUnexpandedParameterPack()) {
2683 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002684 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002685
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002686 EllipsisLoc = SourceLocation();
2687 }
2688 } else {
2689 // Check for any unexpanded parameter packs.
2690 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2691 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002692
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002693 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002694 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002695 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002696
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002697 // Check for direct and virtual base classes.
2698 const CXXBaseSpecifier *DirectBaseSpec = 0;
2699 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2700 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002701 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2702 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002703 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002704
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002705 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2706 VirtualBaseSpec);
2707
2708 // C++ [base.class.init]p2:
2709 // Unless the mem-initializer-id names a nonstatic data member of the
2710 // constructor's class or a direct or virtual base of that class, the
2711 // mem-initializer is ill-formed.
2712 if (!DirectBaseSpec && !VirtualBaseSpec) {
2713 // If the class has any dependent bases, then it's possible that
2714 // one of those types will resolve to the same type as
2715 // BaseType. Therefore, just treat this as a dependent base
2716 // class initialization. FIXME: Should we try to check the
2717 // initialization anyway? It seems odd.
2718 if (ClassDecl->hasAnyDependentBases())
2719 Dependent = true;
2720 else
2721 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2722 << BaseType << Context.getTypeDeclType(ClassDecl)
2723 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2724 }
2725 }
2726
2727 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002728 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002729
Sebastian Redl6df65482011-09-24 17:48:25 +00002730 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2731 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002732 InitRange.getBegin(), Init,
2733 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002734 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002735
2736 // C++ [base.class.init]p2:
2737 // If a mem-initializer-id is ambiguous because it designates both
2738 // a direct non-virtual base class and an inherited virtual base
2739 // class, the mem-initializer is ill-formed.
2740 if (DirectBaseSpec && VirtualBaseSpec)
2741 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002742 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002743
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002744 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002745 if (!BaseSpec)
2746 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2747
2748 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002749 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002750 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002751 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002752 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002753 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002754 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002755
2756 InitializedEntity BaseEntity =
2757 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2758 InitializationKind Kind =
2759 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2760 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2761 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002762 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2763 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002764 if (BaseInit.isInvalid())
2765 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002766
Richard Smith41956372013-01-14 22:39:08 +00002767 // C++11 [class.base.init]p7:
2768 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002769 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002770 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002771 if (BaseInit.isInvalid())
2772 return true;
2773
2774 // If we are in a dependent context, template instantiation will
2775 // perform this type-checking again. Just save the arguments that we
2776 // received in a ParenListExpr.
2777 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2778 // of the information that we have about the base
2779 // initializer. However, deconstructing the ASTs is a dicey process,
2780 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002781 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002782 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002783
Sean Huntcbb67482011-01-08 20:30:50 +00002784 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002785 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002786 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002787 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002788 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002789}
2790
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002791// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002792static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2793 if (T.isNull()) T = E->getType();
2794 QualType TargetType = SemaRef.BuildReferenceType(
2795 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002796 SourceLocation ExprLoc = E->getLocStart();
2797 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2798 TargetType, ExprLoc);
2799
2800 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2801 SourceRange(ExprLoc, ExprLoc),
2802 E->getSourceRange()).take();
2803}
2804
Anders Carlssone5ef7402010-04-23 03:10:23 +00002805/// ImplicitInitializerKind - How an implicit base or member initializer should
2806/// initialize its base or member.
2807enum ImplicitInitializerKind {
2808 IIK_Default,
2809 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002810 IIK_Move,
2811 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002812};
2813
Anders Carlssondefefd22010-04-23 02:00:02 +00002814static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002815BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002816 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002817 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002818 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002819 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002820 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002821 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2822 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002823
John McCall60d7b3a2010-08-24 06:29:42 +00002824 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002825
2826 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002827 case IIK_Inherit: {
2828 const CXXRecordDecl *Inherited =
2829 Constructor->getInheritedConstructor()->getParent();
2830 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2831 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2832 // C++11 [class.inhctor]p8:
2833 // Each expression in the expression-list is of the form
2834 // static_cast<T&&>(p), where p is the name of the corresponding
2835 // constructor parameter and T is the declared type of p.
2836 SmallVector<Expr*, 16> Args;
2837 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2838 ParmVarDecl *PD = Constructor->getParamDecl(I);
2839 ExprResult ArgExpr =
2840 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2841 VK_LValue, SourceLocation());
2842 if (ArgExpr.isInvalid())
2843 return true;
2844 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2845 }
2846
2847 InitializationKind InitKind = InitializationKind::CreateDirect(
2848 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002849 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002850 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2851 break;
2852 }
2853 }
2854 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002855 case IIK_Default: {
2856 InitializationKind InitKind
2857 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002858 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2859 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002860 break;
2861 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002862
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002863 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002864 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002865 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002866 ParmVarDecl *Param = Constructor->getParamDecl(0);
2867 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002868
Anders Carlssone5ef7402010-04-23 03:10:23 +00002869 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002870 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002871 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002872 Constructor->getLocation(), ParamType,
2873 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002874
Eli Friedman5f2987c2012-02-02 03:46:19 +00002875 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2876
Anders Carlssonc7957502010-04-24 22:02:54 +00002877 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002878 QualType ArgTy =
2879 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2880 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002881
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002882 if (Moving) {
2883 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2884 }
2885
John McCallf871d0c2010-08-07 06:22:56 +00002886 CXXCastPath BasePath;
2887 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002888 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2889 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002890 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002891 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002892
Anders Carlssone5ef7402010-04-23 03:10:23 +00002893 InitializationKind InitKind
2894 = InitializationKind::CreateDirect(Constructor->getLocation(),
2895 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002896 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2897 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002898 break;
2899 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002900 }
John McCall9ae2f072010-08-23 23:25:46 +00002901
Douglas Gregor53c374f2010-12-07 00:41:46 +00002902 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002903 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002904 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002905
Anders Carlssondefefd22010-04-23 02:00:02 +00002906 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002907 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002908 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2909 SourceLocation()),
2910 BaseSpec->isVirtual(),
2911 SourceLocation(),
2912 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002913 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002914 SourceLocation());
2915
Anders Carlssondefefd22010-04-23 02:00:02 +00002916 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002917}
2918
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002919static bool RefersToRValueRef(Expr *MemRef) {
2920 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2921 return Referenced->getType()->isRValueReferenceType();
2922}
2923
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002924static bool
2925BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002926 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002927 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002928 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002929 if (Field->isInvalidDecl())
2930 return true;
2931
Chandler Carruthf186b542010-06-29 23:50:44 +00002932 SourceLocation Loc = Constructor->getLocation();
2933
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002934 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2935 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002936 ParmVarDecl *Param = Constructor->getParamDecl(0);
2937 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002938
2939 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002940 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2941 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002942
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002943 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002944 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002945 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002946 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002947
Eli Friedman5f2987c2012-02-02 03:46:19 +00002948 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2949
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002950 if (Moving) {
2951 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2952 }
2953
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002954 // Build a reference to this field within the parameter.
2955 CXXScopeSpec SS;
2956 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2957 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002958 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2959 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002960 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002961 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002962 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002963 ParamType, Loc,
2964 /*IsArrow=*/false,
2965 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002966 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002967 /*FirstQualifierInScope=*/0,
2968 MemberLookup,
2969 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002970 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002971 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002972
2973 // C++11 [class.copy]p15:
2974 // - if a member m has rvalue reference type T&&, it is direct-initialized
2975 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002976 if (RefersToRValueRef(CtorArg.get())) {
2977 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002978 }
2979
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002980 // When the field we are copying is an array, create index variables for
2981 // each dimension of the array. We use these index variables to subscript
2982 // the source array, and other clients (e.g., CodeGen) will perform the
2983 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002984 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002985 QualType BaseType = Field->getType();
2986 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002987 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002988 while (const ConstantArrayType *Array
2989 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002990 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002991 // Create the iteration variable for this array index.
2992 IdentifierInfo *IterationVarName = 0;
2993 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002994 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002995 llvm::raw_svector_ostream OS(Str);
2996 OS << "__i" << IndexVariables.size();
2997 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2998 }
2999 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003000 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003001 IterationVarName, SizeType,
3002 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003003 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003004 IndexVariables.push_back(IterationVar);
3005
3006 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003007 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003008 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003009 assert(!IterationVarRef.isInvalid() &&
3010 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003011 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3012 assert(!IterationVarRef.isInvalid() &&
3013 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003014
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003015 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003016 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003017 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003018 Loc);
3019 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003020 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003021
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003022 BaseType = Array->getElementType();
3023 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003024
3025 // The array subscript expression is an lvalue, which is wrong for moving.
3026 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003027 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003028
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003029 // Construct the entity that we will be initializing. For an array, this
3030 // will be first element in the array, which may require several levels
3031 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003032 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003033 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003034 if (Indirect)
3035 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3036 else
3037 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003038 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3039 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3040 0,
3041 Entities.back()));
3042
3043 // Direct-initialize to use the copy constructor.
3044 InitializationKind InitKind =
3045 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3046
Sebastian Redl74e611a2011-09-04 18:14:28 +00003047 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003048 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003049
John McCall60d7b3a2010-08-24 06:29:42 +00003050 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003051 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003052 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003053 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003054 if (MemberInit.isInvalid())
3055 return true;
3056
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003057 if (Indirect) {
3058 assert(IndexVariables.size() == 0 &&
3059 "Indirect field improperly initialized");
3060 CXXMemberInit
3061 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3062 Loc, Loc,
3063 MemberInit.takeAs<Expr>(),
3064 Loc);
3065 } else
3066 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3067 Loc, MemberInit.takeAs<Expr>(),
3068 Loc,
3069 IndexVariables.data(),
3070 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003071 return false;
3072 }
3073
Richard Smith07b0fdc2013-03-18 21:12:30 +00003074 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3075 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003076
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003077 QualType FieldBaseElementType =
3078 SemaRef.Context.getBaseElementType(Field->getType());
3079
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003080 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003081 InitializedEntity InitEntity
3082 = Indirect? InitializedEntity::InitializeMember(Indirect)
3083 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003084 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003085 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003086
3087 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3088 ExprResult MemberInit =
3089 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003090
Douglas Gregor53c374f2010-12-07 00:41:46 +00003091 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003092 if (MemberInit.isInvalid())
3093 return true;
3094
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003095 if (Indirect)
3096 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3097 Indirect, Loc,
3098 Loc,
3099 MemberInit.get(),
3100 Loc);
3101 else
3102 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3103 Field, Loc, Loc,
3104 MemberInit.get(),
3105 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003106 return false;
3107 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003108
Sean Hunt1f2f3842011-05-17 00:19:05 +00003109 if (!Field->getParent()->isUnion()) {
3110 if (FieldBaseElementType->isReferenceType()) {
3111 SemaRef.Diag(Constructor->getLocation(),
3112 diag::err_uninitialized_member_in_ctor)
3113 << (int)Constructor->isImplicit()
3114 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3115 << 0 << Field->getDeclName();
3116 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3117 return true;
3118 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003119
Sean Hunt1f2f3842011-05-17 00:19:05 +00003120 if (FieldBaseElementType.isConstQualified()) {
3121 SemaRef.Diag(Constructor->getLocation(),
3122 diag::err_uninitialized_member_in_ctor)
3123 << (int)Constructor->isImplicit()
3124 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3125 << 1 << Field->getDeclName();
3126 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3127 return true;
3128 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003129 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003130
David Blaikie4e4d0842012-03-11 07:00:24 +00003131 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003132 FieldBaseElementType->isObjCRetainableType() &&
3133 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3134 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003135 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003136 // Default-initialize Objective-C pointers to NULL.
3137 CXXMemberInit
3138 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3139 Loc, Loc,
3140 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3141 Loc);
3142 return false;
3143 }
3144
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003145 // Nothing to initialize.
3146 CXXMemberInit = 0;
3147 return false;
3148}
John McCallf1860e52010-05-20 23:23:51 +00003149
3150namespace {
3151struct BaseAndFieldInfo {
3152 Sema &S;
3153 CXXConstructorDecl *Ctor;
3154 bool AnyErrorsInInits;
3155 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003156 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003157 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003158
3159 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3160 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003161 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3162 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003163 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003164 else if (Generated && Ctor->isMoveConstructor())
3165 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003166 else if (Ctor->getInheritedConstructor())
3167 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003168 else
3169 IIK = IIK_Default;
3170 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003171
3172 bool isImplicitCopyOrMove() const {
3173 switch (IIK) {
3174 case IIK_Copy:
3175 case IIK_Move:
3176 return true;
3177
3178 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003179 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003180 return false;
3181 }
David Blaikie30263482012-01-20 21:50:17 +00003182
3183 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003184 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003185
3186 bool addFieldInitializer(CXXCtorInitializer *Init) {
3187 AllToInit.push_back(Init);
3188
3189 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003190 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003191 S.UnusedPrivateFields.remove(Init->getAnyMember());
3192
3193 return false;
3194 }
John McCallf1860e52010-05-20 23:23:51 +00003195};
3196}
3197
Richard Smitha4950662011-09-19 13:34:43 +00003198/// \brief Determine whether the given indirect field declaration is somewhere
3199/// within an anonymous union.
3200static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3201 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3202 CEnd = F->chain_end();
3203 C != CEnd; ++C)
3204 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3205 if (Record->isUnion())
3206 return true;
3207
3208 return false;
3209}
3210
Douglas Gregorddb21472011-11-02 23:04:16 +00003211/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3212/// array type.
3213static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3214 if (T->isIncompleteArrayType())
3215 return true;
3216
3217 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3218 if (!ArrayT->getSize())
3219 return true;
3220
3221 T = ArrayT->getElementType();
3222 }
3223
3224 return false;
3225}
3226
Richard Smith7a614d82011-06-11 17:19:42 +00003227static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003228 FieldDecl *Field,
3229 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003230
Chandler Carruthe861c602010-06-30 02:59:29 +00003231 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003232 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3233 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003234
Richard Smith0b8220a2012-08-07 21:30:42 +00003235 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003236 // has a brace-or-equal-initializer, the entity is initialized as specified
3237 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003238 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003239 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3240 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003241 CXXCtorInitializer *Init;
3242 if (Indirect)
3243 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3244 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003245 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003246 SourceLocation());
3247 else
3248 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3249 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003250 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003251 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003252 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003253 }
3254
Richard Smithc115f632011-09-18 11:14:50 +00003255 // Don't build an implicit initializer for union members if none was
3256 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003257 if (Field->getParent()->isUnion() ||
3258 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003259 return false;
3260
Douglas Gregorddb21472011-11-02 23:04:16 +00003261 // Don't initialize incomplete or zero-length arrays.
3262 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3263 return false;
3264
John McCallf1860e52010-05-20 23:23:51 +00003265 // Don't try to build an implicit initializer if there were semantic
3266 // errors in any of the initializers (and therefore we might be
3267 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003268 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003269 return false;
3270
Sean Huntcbb67482011-01-08 20:30:50 +00003271 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003272 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3273 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003274 return true;
John McCallf1860e52010-05-20 23:23:51 +00003275
Richard Smith0b8220a2012-08-07 21:30:42 +00003276 if (!Init)
3277 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003278
Richard Smith0b8220a2012-08-07 21:30:42 +00003279 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003280}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003281
3282bool
3283Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3284 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003285 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003286 Constructor->setNumCtorInitializers(1);
3287 CXXCtorInitializer **initializer =
3288 new (Context) CXXCtorInitializer*[1];
3289 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3290 Constructor->setCtorInitializers(initializer);
3291
Sean Huntb76af9c2011-05-03 23:05:34 +00003292 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003293 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003294 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3295 }
3296
Sean Huntc1598702011-05-05 00:05:47 +00003297 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003298
Sean Hunt059ce0d2011-05-01 07:04:31 +00003299 return false;
3300}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003301
David Blaikie93c86172013-01-17 05:26:25 +00003302bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3303 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003304 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003305 // Just store the initializers as written, they will be checked during
3306 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003307 if (!Initializers.empty()) {
3308 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003309 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003310 new (Context) CXXCtorInitializer*[Initializers.size()];
3311 memcpy(baseOrMemberInitializers, Initializers.data(),
3312 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003313 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003314 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003315
3316 // Let template instantiation know whether we had errors.
3317 if (AnyErrors)
3318 Constructor->setInvalidDecl();
3319
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003320 return false;
3321 }
3322
John McCallf1860e52010-05-20 23:23:51 +00003323 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003324
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003325 // We need to build the initializer AST according to order of construction
3326 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003327 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003328 if (!ClassDecl)
3329 return true;
3330
Eli Friedman80c30da2009-11-09 19:20:36 +00003331 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003332
David Blaikie93c86172013-01-17 05:26:25 +00003333 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003334 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003335
3336 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003337 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003338 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003339 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003340 }
3341
Anders Carlsson711f34a2010-04-21 19:52:01 +00003342 // Keep track of the direct virtual bases.
3343 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3344 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3345 E = ClassDecl->bases_end(); I != E; ++I) {
3346 if (I->isVirtual())
3347 DirectVBases.insert(I);
3348 }
3349
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003350 // Push virtual bases before others.
3351 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3352 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3353
Sean Huntcbb67482011-01-08 20:30:50 +00003354 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003355 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3356 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003357 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003358 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003359 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003360 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003361 VBase, IsInheritedVirtualBase,
3362 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003363 HadError = true;
3364 continue;
3365 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003366
John McCallf1860e52010-05-20 23:23:51 +00003367 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003368 }
3369 }
Mike Stump1eb44332009-09-09 15:08:12 +00003370
John McCallf1860e52010-05-20 23:23:51 +00003371 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003372 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3373 E = ClassDecl->bases_end(); Base != E; ++Base) {
3374 // Virtuals are in the virtual base list and already constructed.
3375 if (Base->isVirtual())
3376 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003377
Sean Huntcbb67482011-01-08 20:30:50 +00003378 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003379 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3380 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003381 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003382 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003383 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003384 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003385 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003386 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003387 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003388 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003389
John McCallf1860e52010-05-20 23:23:51 +00003390 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003391 }
3392 }
Mike Stump1eb44332009-09-09 15:08:12 +00003393
John McCallf1860e52010-05-20 23:23:51 +00003394 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003395 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3396 MemEnd = ClassDecl->decls_end();
3397 Mem != MemEnd; ++Mem) {
3398 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003399 // C++ [class.bit]p2:
3400 // A declaration for a bit-field that omits the identifier declares an
3401 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3402 // initialized.
3403 if (F->isUnnamedBitfield())
3404 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003405
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003406 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003407 // handle anonymous struct/union fields based on their individual
3408 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003409 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003410 continue;
3411
3412 if (CollectFieldInitializer(*this, Info, F))
3413 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003414 continue;
3415 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003416
3417 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003418 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003419 continue;
3420
3421 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3422 if (F->getType()->isIncompleteArrayType()) {
3423 assert(ClassDecl->hasFlexibleArrayMember() &&
3424 "Incomplete array type is not valid");
3425 continue;
3426 }
3427
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003428 // Initialize each field of an anonymous struct individually.
3429 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3430 HadError = true;
3431
3432 continue;
3433 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003434 }
Mike Stump1eb44332009-09-09 15:08:12 +00003435
David Blaikie93c86172013-01-17 05:26:25 +00003436 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003437 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003438 Constructor->setNumCtorInitializers(NumInitializers);
3439 CXXCtorInitializer **baseOrMemberInitializers =
3440 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003441 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003442 NumInitializers * sizeof(CXXCtorInitializer*));
3443 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003444
John McCallef027fe2010-03-16 21:39:52 +00003445 // Constructors implicitly reference the base and member
3446 // destructors.
3447 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3448 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003449 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003450
3451 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003452}
3453
David Blaikieee000bb2013-01-17 08:49:22 +00003454static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003455 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003456 const RecordDecl *RD = RT->getDecl();
3457 if (RD->isAnonymousStructOrUnion()) {
3458 for (RecordDecl::field_iterator Field = RD->field_begin(),
3459 E = RD->field_end(); Field != E; ++Field)
3460 PopulateKeysForFields(*Field, IdealInits);
3461 return;
3462 }
Eli Friedman6347f422009-07-21 19:28:10 +00003463 }
David Blaikieee000bb2013-01-17 08:49:22 +00003464 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003465}
3466
Anders Carlssonea356fb2010-04-02 05:42:15 +00003467static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003468 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003469}
3470
Anders Carlssonea356fb2010-04-02 05:42:15 +00003471static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003472 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003473 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003474 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003475
David Blaikieee000bb2013-01-17 08:49:22 +00003476 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003477}
3478
David Blaikie93c86172013-01-17 05:26:25 +00003479static void DiagnoseBaseOrMemInitializerOrder(
3480 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3481 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003482 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003483 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003484
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003485 // Don't check initializers order unless the warning is enabled at the
3486 // location of at least one initializer.
3487 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003488 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003489 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003490 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3491 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003492 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003493 ShouldCheckOrder = true;
3494 break;
3495 }
3496 }
3497 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003498 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003499
John McCalld6ca8da2010-04-10 07:37:23 +00003500 // Build the list of bases and members in the order that they'll
3501 // actually be initialized. The explicit initializers should be in
3502 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003503 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003504
Anders Carlsson071d6102010-04-02 03:38:04 +00003505 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3506
John McCalld6ca8da2010-04-10 07:37:23 +00003507 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003508 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003509 ClassDecl->vbases_begin(),
3510 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003511 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003512
John McCalld6ca8da2010-04-10 07:37:23 +00003513 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003514 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003515 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003516 if (Base->isVirtual())
3517 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003518 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003519 }
Mike Stump1eb44332009-09-09 15:08:12 +00003520
John McCalld6ca8da2010-04-10 07:37:23 +00003521 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003522 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003523 E = ClassDecl->field_end(); Field != E; ++Field) {
3524 if (Field->isUnnamedBitfield())
3525 continue;
3526
David Blaikieee000bb2013-01-17 08:49:22 +00003527 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003528 }
3529
John McCalld6ca8da2010-04-10 07:37:23 +00003530 unsigned NumIdealInits = IdealInitKeys.size();
3531 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003532
Sean Huntcbb67482011-01-08 20:30:50 +00003533 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003534 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003535 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003536 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003537
3538 // Scan forward to try to find this initializer in the idealized
3539 // initializers list.
3540 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3541 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003542 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003543
3544 // If we didn't find this initializer, it must be because we
3545 // scanned past it on a previous iteration. That can only
3546 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003547 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003548 Sema::SemaDiagnosticBuilder D =
3549 SemaRef.Diag(PrevInit->getSourceLocation(),
3550 diag::warn_initializer_out_of_order);
3551
Francois Pichet00eb3f92010-12-04 09:14:42 +00003552 if (PrevInit->isAnyMemberInitializer())
3553 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003554 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003555 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003556
Francois Pichet00eb3f92010-12-04 09:14:42 +00003557 if (Init->isAnyMemberInitializer())
3558 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003559 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003560 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003561
3562 // Move back to the initializer's location in the ideal list.
3563 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3564 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003565 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003566
3567 assert(IdealIndex != NumIdealInits &&
3568 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003569 }
John McCalld6ca8da2010-04-10 07:37:23 +00003570
3571 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003572 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003573}
3574
John McCall3c3ccdb2010-04-10 09:28:51 +00003575namespace {
3576bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003577 CXXCtorInitializer *Init,
3578 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003579 if (!PrevInit) {
3580 PrevInit = Init;
3581 return false;
3582 }
3583
Douglas Gregordc392c12013-03-25 23:28:23 +00003584 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003585 S.Diag(Init->getSourceLocation(),
3586 diag::err_multiple_mem_initialization)
3587 << Field->getDeclName()
3588 << Init->getSourceRange();
3589 else {
John McCallf4c73712011-01-19 06:33:43 +00003590 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003591 assert(BaseClass && "neither field nor base");
3592 S.Diag(Init->getSourceLocation(),
3593 diag::err_multiple_base_initialization)
3594 << QualType(BaseClass, 0)
3595 << Init->getSourceRange();
3596 }
3597 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3598 << 0 << PrevInit->getSourceRange();
3599
3600 return true;
3601}
3602
Sean Huntcbb67482011-01-08 20:30:50 +00003603typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003604typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3605
3606bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003607 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003608 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003609 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003610 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003611 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003612
3613 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003614 if (Parent->isUnion()) {
3615 UnionEntry &En = Unions[Parent];
3616 if (En.first && En.first != Child) {
3617 S.Diag(Init->getSourceLocation(),
3618 diag::err_multiple_mem_union_initialization)
3619 << Field->getDeclName()
3620 << Init->getSourceRange();
3621 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3622 << 0 << En.second->getSourceRange();
3623 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003624 }
3625 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003626 En.first = Child;
3627 En.second = Init;
3628 }
David Blaikie6fe29652011-11-17 06:01:57 +00003629 if (!Parent->isAnonymousStructOrUnion())
3630 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003631 }
3632
3633 Child = Parent;
3634 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003635 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003636
3637 return false;
3638}
3639}
3640
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003641/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003642void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003643 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003644 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003645 bool AnyErrors) {
3646 if (!ConstructorDecl)
3647 return;
3648
3649 AdjustDeclIfTemplate(ConstructorDecl);
3650
3651 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003652 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003653
3654 if (!Constructor) {
3655 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3656 return;
3657 }
3658
John McCall3c3ccdb2010-04-10 09:28:51 +00003659 // Mapping for the duplicate initializers check.
3660 // For member initializers, this is keyed with a FieldDecl*.
3661 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003662 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003663
3664 // Mapping for the inconsistent anonymous-union initializers check.
3665 RedundantUnionMap MemberUnions;
3666
Anders Carlssonea356fb2010-04-02 05:42:15 +00003667 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003668 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003669 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003670
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003671 // Set the source order index.
3672 Init->setSourceOrder(i);
3673
Francois Pichet00eb3f92010-12-04 09:14:42 +00003674 if (Init->isAnyMemberInitializer()) {
3675 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003676 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3677 CheckRedundantUnionInit(*this, Init, MemberUnions))
3678 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003679 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003680 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3681 if (CheckRedundantInit(*this, Init, Members[Key]))
3682 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003683 } else {
3684 assert(Init->isDelegatingInitializer());
3685 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003686 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003687 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003688 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003689 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003690 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003691 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003692 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003693 // Return immediately as the initializer is set.
3694 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003695 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003696 }
3697
Anders Carlssonea356fb2010-04-02 05:42:15 +00003698 if (HadError)
3699 return;
3700
David Blaikie93c86172013-01-17 05:26:25 +00003701 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003702
David Blaikie93c86172013-01-17 05:26:25 +00003703 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003704}
3705
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003706void
John McCallef027fe2010-03-16 21:39:52 +00003707Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3708 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003709 // Ignore dependent contexts. Also ignore unions, since their members never
3710 // have destructors implicitly called.
3711 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003712 return;
John McCall58e6f342010-03-16 05:22:47 +00003713
3714 // FIXME: all the access-control diagnostics are positioned on the
3715 // field/base declaration. That's probably good; that said, the
3716 // user might reasonably want to know why the destructor is being
3717 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003718
Anders Carlsson9f853df2009-11-17 04:44:12 +00003719 // Non-static data members.
3720 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3721 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003722 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003723 if (Field->isInvalidDecl())
3724 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003725
3726 // Don't destroy incomplete or zero-length arrays.
3727 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3728 continue;
3729
Anders Carlsson9f853df2009-11-17 04:44:12 +00003730 QualType FieldType = Context.getBaseElementType(Field->getType());
3731
3732 const RecordType* RT = FieldType->getAs<RecordType>();
3733 if (!RT)
3734 continue;
3735
3736 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003737 if (FieldClassDecl->isInvalidDecl())
3738 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003739 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003740 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003741 // The destructor for an implicit anonymous union member is never invoked.
3742 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3743 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003744
Douglas Gregordb89f282010-07-01 22:47:18 +00003745 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003746 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003747 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003748 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003749 << Field->getDeclName()
3750 << FieldType);
3751
Eli Friedman5f2987c2012-02-02 03:46:19 +00003752 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003753 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003754 }
3755
John McCall58e6f342010-03-16 05:22:47 +00003756 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3757
Anders Carlsson9f853df2009-11-17 04:44:12 +00003758 // Bases.
3759 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3760 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003761 // Bases are always records in a well-formed non-dependent class.
3762 const RecordType *RT = Base->getType()->getAs<RecordType>();
3763
3764 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003765 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003766 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003767
John McCall58e6f342010-03-16 05:22:47 +00003768 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003769 // If our base class is invalid, we probably can't get its dtor anyway.
3770 if (BaseClassDecl->isInvalidDecl())
3771 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003772 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003773 continue;
John McCall58e6f342010-03-16 05:22:47 +00003774
Douglas Gregordb89f282010-07-01 22:47:18 +00003775 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003776 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003777
3778 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003779 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003780 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003781 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003782 << Base->getSourceRange(),
3783 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003784
Eli Friedman5f2987c2012-02-02 03:46:19 +00003785 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003786 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003787 }
3788
3789 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003790 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3791 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003792
3793 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003794 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003795
3796 // Ignore direct virtual bases.
3797 if (DirectVirtualBases.count(RT))
3798 continue;
3799
John McCall58e6f342010-03-16 05:22:47 +00003800 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003801 // If our base class is invalid, we probably can't get its dtor anyway.
3802 if (BaseClassDecl->isInvalidDecl())
3803 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003804 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003805 continue;
John McCall58e6f342010-03-16 05:22:47 +00003806
Douglas Gregordb89f282010-07-01 22:47:18 +00003807 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003808 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer585bee42013-06-06 23:43:20 +00003809 if (CheckDestructorAccess(
3810 ClassDecl->getLocation(), Dtor,
3811 PDiag(diag::err_access_dtor_vbase)
3812 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3813 Context.getTypeDeclType(ClassDecl)) ==
3814 AR_accessible) {
3815 CheckDerivedToBaseConversion(
3816 Context.getTypeDeclType(ClassDecl), VBase->getType(),
3817 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3818 SourceRange(), DeclarationName(), 0);
3819 }
John McCall58e6f342010-03-16 05:22:47 +00003820
Eli Friedman5f2987c2012-02-02 03:46:19 +00003821 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003822 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003823 }
3824}
3825
John McCalld226f652010-08-21 09:40:31 +00003826void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003827 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003828 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003829
Mike Stump1eb44332009-09-09 15:08:12 +00003830 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003831 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003832 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003833}
3834
Mike Stump1eb44332009-09-09 15:08:12 +00003835bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003836 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003837 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3838 unsigned DiagID;
3839 AbstractDiagSelID SelID;
3840
3841 public:
3842 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3843 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3844
3845 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003846 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003847 if (SelID == -1)
3848 S.Diag(Loc, DiagID) << T;
3849 else
3850 S.Diag(Loc, DiagID) << SelID << T;
3851 }
3852 } Diagnoser(DiagID, SelID);
3853
3854 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003855}
3856
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003857bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003858 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003859 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003860 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003861
Anders Carlsson11f21a02009-03-23 19:10:31 +00003862 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003863 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003864
Ted Kremenek6217b802009-07-29 21:53:49 +00003865 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003866 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003867 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003868 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003869
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003870 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003871 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003872 }
Mike Stump1eb44332009-09-09 15:08:12 +00003873
Ted Kremenek6217b802009-07-29 21:53:49 +00003874 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003875 if (!RT)
3876 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003877
John McCall86ff3082010-02-04 22:26:26 +00003878 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003879
John McCall94c3b562010-08-18 09:41:07 +00003880 // We can't answer whether something is abstract until it has a
3881 // definition. If it's currently being defined, we'll walk back
3882 // over all the declarations when we have a full definition.
3883 const CXXRecordDecl *Def = RD->getDefinition();
3884 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003885 return false;
3886
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003887 if (!RD->isAbstract())
3888 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003889
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003890 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003891 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003892
John McCall94c3b562010-08-18 09:41:07 +00003893 return true;
3894}
3895
3896void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3897 // Check if we've already emitted the list of pure virtual functions
3898 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003899 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003900 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003901
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003902 CXXFinalOverriderMap FinalOverriders;
3903 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003904
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003905 // Keep a set of seen pure methods so we won't diagnose the same method
3906 // more than once.
3907 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3908
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003909 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3910 MEnd = FinalOverriders.end();
3911 M != MEnd;
3912 ++M) {
3913 for (OverridingMethods::iterator SO = M->second.begin(),
3914 SOEnd = M->second.end();
3915 SO != SOEnd; ++SO) {
3916 // C++ [class.abstract]p4:
3917 // A class is abstract if it contains or inherits at least one
3918 // pure virtual function for which the final overrider is pure
3919 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003920
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003921 //
3922 if (SO->second.size() != 1)
3923 continue;
3924
3925 if (!SO->second.front().Method->isPure())
3926 continue;
3927
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003928 if (!SeenPureMethods.insert(SO->second.front().Method))
3929 continue;
3930
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003931 Diag(SO->second.front().Method->getLocation(),
3932 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003933 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003934 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003935 }
3936
3937 if (!PureVirtualClassDiagSet)
3938 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3939 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003940}
3941
Anders Carlsson8211eff2009-03-24 01:19:16 +00003942namespace {
John McCall94c3b562010-08-18 09:41:07 +00003943struct AbstractUsageInfo {
3944 Sema &S;
3945 CXXRecordDecl *Record;
3946 CanQualType AbstractType;
3947 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003948
John McCall94c3b562010-08-18 09:41:07 +00003949 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3950 : S(S), Record(Record),
3951 AbstractType(S.Context.getCanonicalType(
3952 S.Context.getTypeDeclType(Record))),
3953 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003954
John McCall94c3b562010-08-18 09:41:07 +00003955 void DiagnoseAbstractType() {
3956 if (Invalid) return;
3957 S.DiagnoseAbstractType(Record);
3958 Invalid = true;
3959 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003960
John McCall94c3b562010-08-18 09:41:07 +00003961 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3962};
3963
3964struct CheckAbstractUsage {
3965 AbstractUsageInfo &Info;
3966 const NamedDecl *Ctx;
3967
3968 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3969 : Info(Info), Ctx(Ctx) {}
3970
3971 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3972 switch (TL.getTypeLocClass()) {
3973#define ABSTRACT_TYPELOC(CLASS, PARENT)
3974#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003975 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003976#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003977 }
John McCall94c3b562010-08-18 09:41:07 +00003978 }
Mike Stump1eb44332009-09-09 15:08:12 +00003979
John McCall94c3b562010-08-18 09:41:07 +00003980 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3981 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3982 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003983 if (!TL.getArg(I))
3984 continue;
3985
John McCall94c3b562010-08-18 09:41:07 +00003986 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3987 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003988 }
John McCall94c3b562010-08-18 09:41:07 +00003989 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003990
John McCall94c3b562010-08-18 09:41:07 +00003991 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3992 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3993 }
Mike Stump1eb44332009-09-09 15:08:12 +00003994
John McCall94c3b562010-08-18 09:41:07 +00003995 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3996 // Visit the type parameters from a permissive context.
3997 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3998 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3999 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4000 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4001 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4002 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004003 }
John McCall94c3b562010-08-18 09:41:07 +00004004 }
Mike Stump1eb44332009-09-09 15:08:12 +00004005
John McCall94c3b562010-08-18 09:41:07 +00004006 // Visit pointee types from a permissive context.
4007#define CheckPolymorphic(Type) \
4008 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4009 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4010 }
4011 CheckPolymorphic(PointerTypeLoc)
4012 CheckPolymorphic(ReferenceTypeLoc)
4013 CheckPolymorphic(MemberPointerTypeLoc)
4014 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004015 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004016
John McCall94c3b562010-08-18 09:41:07 +00004017 /// Handle all the types we haven't given a more specific
4018 /// implementation for above.
4019 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4020 // Every other kind of type that we haven't called out already
4021 // that has an inner type is either (1) sugar or (2) contains that
4022 // inner type in some way as a subobject.
4023 if (TypeLoc Next = TL.getNextTypeLoc())
4024 return Visit(Next, Sel);
4025
4026 // If there's no inner type and we're in a permissive context,
4027 // don't diagnose.
4028 if (Sel == Sema::AbstractNone) return;
4029
4030 // Check whether the type matches the abstract type.
4031 QualType T = TL.getType();
4032 if (T->isArrayType()) {
4033 Sel = Sema::AbstractArrayType;
4034 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004035 }
John McCall94c3b562010-08-18 09:41:07 +00004036 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4037 if (CT != Info.AbstractType) return;
4038
4039 // It matched; do some magic.
4040 if (Sel == Sema::AbstractArrayType) {
4041 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4042 << T << TL.getSourceRange();
4043 } else {
4044 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4045 << Sel << T << TL.getSourceRange();
4046 }
4047 Info.DiagnoseAbstractType();
4048 }
4049};
4050
4051void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4052 Sema::AbstractDiagSelID Sel) {
4053 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4054}
4055
4056}
4057
4058/// Check for invalid uses of an abstract type in a method declaration.
4059static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4060 CXXMethodDecl *MD) {
4061 // No need to do the check on definitions, which require that
4062 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004063 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004064 return;
4065
4066 // For safety's sake, just ignore it if we don't have type source
4067 // information. This should never happen for non-implicit methods,
4068 // but...
4069 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4070 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4071}
4072
4073/// Check for invalid uses of an abstract type within a class definition.
4074static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4075 CXXRecordDecl *RD) {
4076 for (CXXRecordDecl::decl_iterator
4077 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4078 Decl *D = *I;
4079 if (D->isImplicit()) continue;
4080
4081 // Methods and method templates.
4082 if (isa<CXXMethodDecl>(D)) {
4083 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4084 } else if (isa<FunctionTemplateDecl>(D)) {
4085 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4086 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4087
4088 // Fields and static variables.
4089 } else if (isa<FieldDecl>(D)) {
4090 FieldDecl *FD = cast<FieldDecl>(D);
4091 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4092 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4093 } else if (isa<VarDecl>(D)) {
4094 VarDecl *VD = cast<VarDecl>(D);
4095 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4096 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4097
4098 // Nested classes and class templates.
4099 } else if (isa<CXXRecordDecl>(D)) {
4100 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4101 } else if (isa<ClassTemplateDecl>(D)) {
4102 CheckAbstractClassUsage(Info,
4103 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4104 }
4105 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004106}
4107
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004108/// \brief Perform semantic checks on a class definition that has been
4109/// completing, introducing implicitly-declared members, checking for
4110/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004111void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004112 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004113 return;
4114
John McCall94c3b562010-08-18 09:41:07 +00004115 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4116 AbstractUsageInfo Info(*this, Record);
4117 CheckAbstractClassUsage(Info, Record);
4118 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004119
4120 // If this is not an aggregate type and has no user-declared constructor,
4121 // complain about any non-static data members of reference or const scalar
4122 // type, since they will never get initializers.
4123 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004124 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4125 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004126 bool Complained = false;
4127 for (RecordDecl::field_iterator F = Record->field_begin(),
4128 FEnd = Record->field_end();
4129 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004130 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004131 continue;
4132
Douglas Gregor325e5932010-04-15 00:00:53 +00004133 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004134 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004135 if (!Complained) {
4136 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4137 << Record->getTagKind() << Record;
4138 Complained = true;
4139 }
4140
4141 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4142 << F->getType()->isReferenceType()
4143 << F->getDeclName();
4144 }
4145 }
4146 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004147
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004148 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004149 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004150
4151 if (Record->getIdentifier()) {
4152 // C++ [class.mem]p13:
4153 // If T is the name of a class, then each of the following shall have a
4154 // name different from T:
4155 // - every member of every anonymous union that is a member of class T.
4156 //
4157 // C++ [class.mem]p14:
4158 // In addition, if class T has a user-declared constructor (12.1), every
4159 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004160 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4161 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4162 ++I) {
4163 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004164 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4165 isa<IndirectFieldDecl>(D)) {
4166 Diag(D->getLocation(), diag::err_member_name_of_class)
4167 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004168 break;
4169 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004170 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004171 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004172
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004173 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004174 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004175 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004176 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004177 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4178 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4179 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004180
David Blaikieb6b5b972012-09-21 03:21:07 +00004181 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4182 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4183 DiagnoseAbstractType(Record);
4184 }
4185
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004186 if (!Record->isDependentType()) {
4187 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4188 MEnd = Record->method_end();
4189 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004190 // See if a method overloads virtual methods in a base
4191 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004192 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004193 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004194
4195 // Check whether the explicitly-defaulted special members are valid.
4196 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4197 CheckExplicitlyDefaultedSpecialMember(*M);
4198
4199 // For an explicitly defaulted or deleted special member, we defer
4200 // determining triviality until the class is complete. That time is now!
4201 if (!M->isImplicit() && !M->isUserProvided()) {
4202 CXXSpecialMember CSM = getSpecialMember(*M);
4203 if (CSM != CXXInvalid) {
4204 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4205
4206 // Inform the class that we've finished declaring this member.
4207 Record->finishedDefaultedOrDeletedMember(*M);
4208 }
4209 }
4210 }
4211 }
4212
4213 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4214 // function that is not a constructor declares that member function to be
4215 // const. [...] The class of which that function is a member shall be
4216 // a literal type.
4217 //
4218 // If the class has virtual bases, any constexpr members will already have
4219 // been diagnosed by the checks performed on the member declaration, so
4220 // suppress this (less useful) diagnostic.
4221 //
4222 // We delay this until we know whether an explicitly-defaulted (or deleted)
4223 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004224 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004225 !Record->isLiteral() && !Record->getNumVBases()) {
4226 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4227 MEnd = Record->method_end();
4228 M != MEnd; ++M) {
4229 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4230 switch (Record->getTemplateSpecializationKind()) {
4231 case TSK_ImplicitInstantiation:
4232 case TSK_ExplicitInstantiationDeclaration:
4233 case TSK_ExplicitInstantiationDefinition:
4234 // If a template instantiates to a non-literal type, but its members
4235 // instantiate to constexpr functions, the template is technically
4236 // ill-formed, but we allow it for sanity.
4237 continue;
4238
4239 case TSK_Undeclared:
4240 case TSK_ExplicitSpecialization:
4241 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4242 diag::err_constexpr_method_non_literal);
4243 break;
4244 }
4245
4246 // Only produce one error per class.
4247 break;
4248 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004249 }
4250 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004251
Richard Smith07b0fdc2013-03-18 21:12:30 +00004252 // Declare inheriting constructors. We do this eagerly here because:
4253 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004254 // constructors from different classes.
4255 // - The lazy declaration of the other implicit constructors is so as to not
4256 // waste space and performance on classes that are not meant to be
4257 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004258 // have inheriting constructors.
4259 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004260}
4261
Richard Smith7756afa2012-06-10 05:43:50 +00004262/// Is the special member function which would be selected to perform the
4263/// specified operation on the specified class type a constexpr constructor?
4264static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4265 Sema::CXXSpecialMember CSM,
4266 bool ConstArg) {
4267 Sema::SpecialMemberOverloadResult *SMOR =
4268 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4269 false, false, false, false);
4270 if (!SMOR || !SMOR->getMethod())
4271 // A constructor we wouldn't select can't be "involved in initializing"
4272 // anything.
4273 return true;
4274 return SMOR->getMethod()->isConstexpr();
4275}
4276
4277/// Determine whether the specified special member function would be constexpr
4278/// if it were implicitly defined.
4279static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4280 Sema::CXXSpecialMember CSM,
4281 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004282 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004283 return false;
4284
4285 // C++11 [dcl.constexpr]p4:
4286 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004287 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004288 switch (CSM) {
4289 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004290 // Since default constructor lookup is essentially trivial (and cannot
4291 // involve, for instance, template instantiation), we compute whether a
4292 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4293 //
4294 // This is important for performance; we need to know whether the default
4295 // constructor is constexpr to determine whether the type is a literal type.
4296 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4297
Richard Smith7756afa2012-06-10 05:43:50 +00004298 case Sema::CXXCopyConstructor:
4299 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004300 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004301 break;
4302
4303 case Sema::CXXCopyAssignment:
4304 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004305 if (!S.getLangOpts().CPlusPlus1y)
4306 return false;
4307 // In C++1y, we need to perform overload resolution.
4308 Ctor = false;
4309 break;
4310
Richard Smith7756afa2012-06-10 05:43:50 +00004311 case Sema::CXXDestructor:
4312 case Sema::CXXInvalid:
4313 return false;
4314 }
4315
4316 // -- if the class is a non-empty union, or for each non-empty anonymous
4317 // union member of a non-union class, exactly one non-static data member
4318 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004319 //
4320 // If we squint, this is guaranteed, since exactly one non-static data member
4321 // will be initialized (if the constructor isn't deleted), we just don't know
4322 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004323 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004324 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004325
4326 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004327 if (Ctor && ClassDecl->getNumVBases())
4328 return false;
4329
4330 // C++1y [class.copy]p26:
4331 // -- [the class] is a literal type, and
4332 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004333 return false;
4334
4335 // -- every constructor involved in initializing [...] base class
4336 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004337 // -- the assignment operator selected to copy/move each direct base
4338 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004339 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4340 BEnd = ClassDecl->bases_end();
4341 B != BEnd; ++B) {
4342 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4343 if (!BaseType) continue;
4344
4345 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4346 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4347 return false;
4348 }
4349
4350 // -- every constructor involved in initializing non-static data members
4351 // [...] shall be a constexpr constructor;
4352 // -- every non-static data member and base class sub-object shall be
4353 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004354 // -- for each non-stastic data member of X that is of class type (or array
4355 // thereof), the assignment operator selected to copy/move that member is
4356 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004357 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4358 FEnd = ClassDecl->field_end();
4359 F != FEnd; ++F) {
4360 if (F->isInvalidDecl())
4361 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004362 if (const RecordType *RecordTy =
4363 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004364 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4365 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4366 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004367 }
4368 }
4369
4370 // All OK, it's constexpr!
4371 return true;
4372}
4373
Richard Smithb9d0b762012-07-27 04:22:15 +00004374static Sema::ImplicitExceptionSpecification
4375computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4376 switch (S.getSpecialMember(MD)) {
4377 case Sema::CXXDefaultConstructor:
4378 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4379 case Sema::CXXCopyConstructor:
4380 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4381 case Sema::CXXCopyAssignment:
4382 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4383 case Sema::CXXMoveConstructor:
4384 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4385 case Sema::CXXMoveAssignment:
4386 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4387 case Sema::CXXDestructor:
4388 return S.ComputeDefaultedDtorExceptionSpec(MD);
4389 case Sema::CXXInvalid:
4390 break;
4391 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004392 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4393 "only special members have implicit exception specs");
4394 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004395}
4396
Richard Smithdd25e802012-07-30 23:48:14 +00004397static void
4398updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4399 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4400 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4401 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004402 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4403 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004404}
4405
Richard Smithb9d0b762012-07-27 04:22:15 +00004406void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4407 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4408 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4409 return;
4410
Richard Smithdd25e802012-07-30 23:48:14 +00004411 // Evaluate the exception specification.
4412 ImplicitExceptionSpecification ExceptSpec =
4413 computeImplicitExceptionSpec(*this, Loc, MD);
4414
4415 // Update the type of the special member to use it.
4416 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4417
4418 // A user-provided destructor can be defined outside the class. When that
4419 // happens, be sure to update the exception specification on both
4420 // declarations.
4421 const FunctionProtoType *CanonicalFPT =
4422 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4423 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4424 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4425 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004426}
4427
Richard Smith3003e1d2012-05-15 04:39:51 +00004428void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4429 CXXRecordDecl *RD = MD->getParent();
4430 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004431
Richard Smith3003e1d2012-05-15 04:39:51 +00004432 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4433 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004434
4435 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004436 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004437 bool First = MD == MD->getCanonicalDecl();
4438
4439 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004440
4441 // C++11 [dcl.fct.def.default]p1:
4442 // A function that is explicitly defaulted shall
4443 // -- be a special member function (checked elsewhere),
4444 // -- have the same type (except for ref-qualifiers, and except that a
4445 // copy operation can take a non-const reference) as an implicit
4446 // declaration, and
4447 // -- not have default arguments.
4448 unsigned ExpectedParams = 1;
4449 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4450 ExpectedParams = 0;
4451 if (MD->getNumParams() != ExpectedParams) {
4452 // This also checks for default arguments: a copy or move constructor with a
4453 // default argument is classified as a default constructor, and assignment
4454 // operations and destructors can't have default arguments.
4455 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4456 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004457 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004458 } else if (MD->isVariadic()) {
4459 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4460 << CSM << MD->getSourceRange();
4461 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004462 }
4463
Richard Smith3003e1d2012-05-15 04:39:51 +00004464 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004465
Richard Smith7756afa2012-06-10 05:43:50 +00004466 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004467 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004468 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004469 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004470 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004471
Richard Smith3003e1d2012-05-15 04:39:51 +00004472 QualType ReturnType = Context.VoidTy;
4473 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4474 // Check for return type matching.
4475 ReturnType = Type->getResultType();
4476 QualType ExpectedReturnType =
4477 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4478 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4479 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4480 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4481 HadError = true;
4482 }
4483
4484 // A defaulted special member cannot have cv-qualifiers.
4485 if (Type->getTypeQuals()) {
4486 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004487 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004488 HadError = true;
4489 }
4490 }
4491
4492 // Check for parameter type matching.
4493 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004494 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004495 if (ExpectedParams && ArgType->isReferenceType()) {
4496 // Argument must be reference to possibly-const T.
4497 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004498 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004499
4500 if (ReferentType.isVolatileQualified()) {
4501 Diag(MD->getLocation(),
4502 diag::err_defaulted_special_member_volatile_param) << CSM;
4503 HadError = true;
4504 }
4505
Richard Smith7756afa2012-06-10 05:43:50 +00004506 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004507 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4508 Diag(MD->getLocation(),
4509 diag::err_defaulted_special_member_copy_const_param)
4510 << (CSM == CXXCopyAssignment);
4511 // FIXME: Explain why this special member can't be const.
4512 } else {
4513 Diag(MD->getLocation(),
4514 diag::err_defaulted_special_member_move_const_param)
4515 << (CSM == CXXMoveAssignment);
4516 }
4517 HadError = true;
4518 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004519 } else if (ExpectedParams) {
4520 // A copy assignment operator can take its argument by value, but a
4521 // defaulted one cannot.
4522 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004523 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004524 HadError = true;
4525 }
Sean Huntbe631222011-05-17 20:44:43 +00004526
Richard Smith61802452011-12-22 02:22:31 +00004527 // C++11 [dcl.fct.def.default]p2:
4528 // An explicitly-defaulted function may be declared constexpr only if it
4529 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004530 // Do not apply this rule to members of class templates, since core issue 1358
4531 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004532 // functions which cannot be constexpr (for non-constructors in C++11 and for
4533 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004534 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4535 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004536 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4537 : isa<CXXConstructorDecl>(MD)) &&
4538 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004539 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4540 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004541 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004542 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004543 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004544
Richard Smith61802452011-12-22 02:22:31 +00004545 // and may have an explicit exception-specification only if it is compatible
4546 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004547 if (Type->hasExceptionSpec()) {
4548 // Delay the check if this is the first declaration of the special member,
4549 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004550 if (First) {
4551 // If the exception specification needs to be instantiated, do so now,
4552 // before we clobber it with an EST_Unevaluated specification below.
4553 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4554 InstantiateExceptionSpec(MD->getLocStart(), MD);
4555 Type = MD->getType()->getAs<FunctionProtoType>();
4556 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004557 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004558 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004559 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4560 }
Richard Smith61802452011-12-22 02:22:31 +00004561
4562 // If a function is explicitly defaulted on its first declaration,
4563 if (First) {
4564 // -- it is implicitly considered to be constexpr if the implicit
4565 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004566 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004567
Richard Smith3003e1d2012-05-15 04:39:51 +00004568 // -- it is implicitly considered to have the same exception-specification
4569 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004570 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4571 EPI.ExceptionSpecType = EST_Unevaluated;
4572 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004573 MD->setType(Context.getFunctionType(ReturnType,
4574 ArrayRef<QualType>(&ArgType,
4575 ExpectedParams),
4576 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004577 }
4578
Richard Smith3003e1d2012-05-15 04:39:51 +00004579 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004580 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004581 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004582 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004583 // C++11 [dcl.fct.def.default]p4:
4584 // [For a] user-provided explicitly-defaulted function [...] if such a
4585 // function is implicitly defined as deleted, the program is ill-formed.
4586 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4587 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004588 }
4589 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004590
Richard Smith3003e1d2012-05-15 04:39:51 +00004591 if (HadError)
4592 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004593}
4594
Richard Smith1d28caf2012-12-11 01:14:52 +00004595/// Check whether the exception specification provided for an
4596/// explicitly-defaulted special member matches the exception specification
4597/// that would have been generated for an implicit special member, per
4598/// C++11 [dcl.fct.def.default]p2.
4599void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4600 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4601 // Compute the implicit exception specification.
4602 FunctionProtoType::ExtProtoInfo EPI;
4603 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4604 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004605 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004606
4607 // Ensure that it matches.
4608 CheckEquivalentExceptionSpec(
4609 PDiag(diag::err_incorrect_defaulted_exception_spec)
4610 << getSpecialMember(MD), PDiag(),
4611 ImplicitType, SourceLocation(),
4612 SpecifiedType, MD->getLocation());
4613}
4614
4615void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4616 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4617 I != N; ++I)
4618 CheckExplicitlyDefaultedMemberExceptionSpec(
4619 DelayedDefaultedMemberExceptionSpecs[I].first,
4620 DelayedDefaultedMemberExceptionSpecs[I].second);
4621
4622 DelayedDefaultedMemberExceptionSpecs.clear();
4623}
4624
Richard Smith7d5088a2012-02-18 02:02:13 +00004625namespace {
4626struct SpecialMemberDeletionInfo {
4627 Sema &S;
4628 CXXMethodDecl *MD;
4629 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004630 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004631
4632 // Properties of the special member, computed for convenience.
4633 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4634 SourceLocation Loc;
4635
4636 bool AllFieldsAreConst;
4637
4638 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004639 Sema::CXXSpecialMember CSM, bool Diagnose)
4640 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004641 IsConstructor(false), IsAssignment(false), IsMove(false),
4642 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4643 AllFieldsAreConst(true) {
4644 switch (CSM) {
4645 case Sema::CXXDefaultConstructor:
4646 case Sema::CXXCopyConstructor:
4647 IsConstructor = true;
4648 break;
4649 case Sema::CXXMoveConstructor:
4650 IsConstructor = true;
4651 IsMove = true;
4652 break;
4653 case Sema::CXXCopyAssignment:
4654 IsAssignment = true;
4655 break;
4656 case Sema::CXXMoveAssignment:
4657 IsAssignment = true;
4658 IsMove = true;
4659 break;
4660 case Sema::CXXDestructor:
4661 break;
4662 case Sema::CXXInvalid:
4663 llvm_unreachable("invalid special member kind");
4664 }
4665
4666 if (MD->getNumParams()) {
4667 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4668 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4669 }
4670 }
4671
4672 bool inUnion() const { return MD->getParent()->isUnion(); }
4673
4674 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004675 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4676 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004677 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004678 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4679 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4680 Quals = 0;
4681 return S.LookupSpecialMember(Class, CSM,
4682 ConstArg || (Quals & Qualifiers::Const),
4683 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004684 MD->getRefQualifier() == RQ_RValue,
4685 TQ & Qualifiers::Const,
4686 TQ & Qualifiers::Volatile);
4687 }
4688
Richard Smith6c4c36c2012-03-30 20:53:28 +00004689 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004690
Richard Smith6c4c36c2012-03-30 20:53:28 +00004691 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004692 bool shouldDeleteForField(FieldDecl *FD);
4693 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004694
Richard Smith517bb842012-07-18 03:51:16 +00004695 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4696 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004697 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4698 Sema::SpecialMemberOverloadResult *SMOR,
4699 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004700
4701 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004702};
4703}
4704
John McCall12d8d802012-04-09 20:53:23 +00004705/// Is the given special member inaccessible when used on the given
4706/// sub-object.
4707bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4708 CXXMethodDecl *target) {
4709 /// If we're operating on a base class, the object type is the
4710 /// type of this special member.
4711 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004712 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004713 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4714 objectTy = S.Context.getTypeDeclType(MD->getParent());
4715 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4716
4717 // If we're operating on a field, the object type is the type of the field.
4718 } else {
4719 objectTy = S.Context.getTypeDeclType(target->getParent());
4720 }
4721
4722 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4723}
4724
Richard Smith6c4c36c2012-03-30 20:53:28 +00004725/// Check whether we should delete a special member due to the implicit
4726/// definition containing a call to a special member of a subobject.
4727bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4728 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4729 bool IsDtorCallInCtor) {
4730 CXXMethodDecl *Decl = SMOR->getMethod();
4731 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4732
4733 int DiagKind = -1;
4734
4735 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4736 DiagKind = !Decl ? 0 : 1;
4737 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4738 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004739 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004740 DiagKind = 3;
4741 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4742 !Decl->isTrivial()) {
4743 // A member of a union must have a trivial corresponding special member.
4744 // As a weird special case, a destructor call from a union's constructor
4745 // must be accessible and non-deleted, but need not be trivial. Such a
4746 // destructor is never actually called, but is semantically checked as
4747 // if it were.
4748 DiagKind = 4;
4749 }
4750
4751 if (DiagKind == -1)
4752 return false;
4753
4754 if (Diagnose) {
4755 if (Field) {
4756 S.Diag(Field->getLocation(),
4757 diag::note_deleted_special_member_class_subobject)
4758 << CSM << MD->getParent() << /*IsField*/true
4759 << Field << DiagKind << IsDtorCallInCtor;
4760 } else {
4761 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4762 S.Diag(Base->getLocStart(),
4763 diag::note_deleted_special_member_class_subobject)
4764 << CSM << MD->getParent() << /*IsField*/false
4765 << Base->getType() << DiagKind << IsDtorCallInCtor;
4766 }
4767
4768 if (DiagKind == 1)
4769 S.NoteDeletedFunction(Decl);
4770 // FIXME: Explain inaccessibility if DiagKind == 3.
4771 }
4772
4773 return true;
4774}
4775
Richard Smith9a561d52012-02-26 09:11:52 +00004776/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004777/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004778bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004779 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004780 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004781
4782 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004783 // -- any direct or virtual base class, or non-static data member with no
4784 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004785 // either M has no default constructor or overload resolution as applied
4786 // to M's default constructor results in an ambiguity or in a function
4787 // that is deleted or inaccessible
4788 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4789 // -- a direct or virtual base class B that cannot be copied/moved because
4790 // overload resolution, as applied to B's corresponding special member,
4791 // results in an ambiguity or a function that is deleted or inaccessible
4792 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004793 // C++11 [class.dtor]p5:
4794 // -- any direct or virtual base class [...] has a type with a destructor
4795 // that is deleted or inaccessible
4796 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004797 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004798 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004799 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004800
Richard Smith6c4c36c2012-03-30 20:53:28 +00004801 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4802 // -- any direct or virtual base class or non-static data member has a
4803 // type with a destructor that is deleted or inaccessible
4804 if (IsConstructor) {
4805 Sema::SpecialMemberOverloadResult *SMOR =
4806 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4807 false, false, false, false, false);
4808 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4809 return true;
4810 }
4811
Richard Smith9a561d52012-02-26 09:11:52 +00004812 return false;
4813}
4814
4815/// Check whether we should delete a special member function due to the class
4816/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004817bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004818 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004819 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004820}
4821
4822/// Check whether we should delete a special member function due to the class
4823/// having a particular non-static data member.
4824bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4825 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4826 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4827
4828 if (CSM == Sema::CXXDefaultConstructor) {
4829 // For a default constructor, all references must be initialized in-class
4830 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004831 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4832 if (Diagnose)
4833 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4834 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004835 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004836 }
Richard Smith79363f52012-02-27 06:07:25 +00004837 // C++11 [class.ctor]p5: any non-variant non-static data member of
4838 // const-qualified type (or array thereof) with no
4839 // brace-or-equal-initializer does not have a user-provided default
4840 // constructor.
4841 if (!inUnion() && FieldType.isConstQualified() &&
4842 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004843 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4844 if (Diagnose)
4845 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004846 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004847 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004848 }
4849
4850 if (inUnion() && !FieldType.isConstQualified())
4851 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004852 } else if (CSM == Sema::CXXCopyConstructor) {
4853 // For a copy constructor, data members must not be of rvalue reference
4854 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004855 if (FieldType->isRValueReferenceType()) {
4856 if (Diagnose)
4857 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4858 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004859 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004860 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004861 } else if (IsAssignment) {
4862 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004863 if (FieldType->isReferenceType()) {
4864 if (Diagnose)
4865 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4866 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004867 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004868 }
4869 if (!FieldRecord && FieldType.isConstQualified()) {
4870 // C++11 [class.copy]p23:
4871 // -- a non-static data member of const non-class type (or array thereof)
4872 if (Diagnose)
4873 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004874 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004875 return true;
4876 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004877 }
4878
4879 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004880 // Some additional restrictions exist on the variant members.
4881 if (!inUnion() && FieldRecord->isUnion() &&
4882 FieldRecord->isAnonymousStructOrUnion()) {
4883 bool AllVariantFieldsAreConst = true;
4884
Richard Smithdf8dc862012-03-29 19:00:10 +00004885 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004886 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4887 UE = FieldRecord->field_end();
4888 UI != UE; ++UI) {
4889 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004890
4891 if (!UnionFieldType.isConstQualified())
4892 AllVariantFieldsAreConst = false;
4893
Richard Smith9a561d52012-02-26 09:11:52 +00004894 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4895 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004896 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4897 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004898 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004899 }
4900
4901 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004902 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004903 FieldRecord->field_begin() != FieldRecord->field_end()) {
4904 if (Diagnose)
4905 S.Diag(FieldRecord->getLocation(),
4906 diag::note_deleted_default_ctor_all_const)
4907 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004908 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004909 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004910
Richard Smithdf8dc862012-03-29 19:00:10 +00004911 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004912 // This is technically non-conformant, but sanity demands it.
4913 return false;
4914 }
4915
Richard Smith517bb842012-07-18 03:51:16 +00004916 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4917 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004918 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004919 }
4920
4921 return false;
4922}
4923
4924/// C++11 [class.ctor] p5:
4925/// A defaulted default constructor for a class X is defined as deleted if
4926/// X is a union and all of its variant members are of const-qualified type.
4927bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004928 // This is a silly definition, because it gives an empty union a deleted
4929 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004930 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4931 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4932 if (Diagnose)
4933 S.Diag(MD->getParent()->getLocation(),
4934 diag::note_deleted_default_ctor_all_const)
4935 << MD->getParent() << /*not anonymous union*/0;
4936 return true;
4937 }
4938 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004939}
4940
4941/// Determine whether a defaulted special member function should be defined as
4942/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4943/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004944bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4945 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004946 if (MD->isInvalidDecl())
4947 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004948 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004949 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004950 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004951 return false;
4952
Richard Smith7d5088a2012-02-18 02:02:13 +00004953 // C++11 [expr.lambda.prim]p19:
4954 // The closure type associated with a lambda-expression has a
4955 // deleted (8.4.3) default constructor and a deleted copy
4956 // assignment operator.
4957 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004958 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4959 if (Diagnose)
4960 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004961 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004962 }
4963
Richard Smith5bdaac52012-04-02 20:59:25 +00004964 // For an anonymous struct or union, the copy and assignment special members
4965 // will never be used, so skip the check. For an anonymous union declared at
4966 // namespace scope, the constructor and destructor are used.
4967 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4968 RD->isAnonymousStructOrUnion())
4969 return false;
4970
Richard Smith6c4c36c2012-03-30 20:53:28 +00004971 // C++11 [class.copy]p7, p18:
4972 // If the class definition declares a move constructor or move assignment
4973 // operator, an implicitly declared copy constructor or copy assignment
4974 // operator is defined as deleted.
4975 if (MD->isImplicit() &&
4976 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4977 CXXMethodDecl *UserDeclaredMove = 0;
4978
4979 // In Microsoft mode, a user-declared move only causes the deletion of the
4980 // corresponding copy operation, not both copy operations.
4981 if (RD->hasUserDeclaredMoveConstructor() &&
4982 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4983 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004984
4985 // Find any user-declared move constructor.
4986 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4987 E = RD->ctor_end(); I != E; ++I) {
4988 if (I->isMoveConstructor()) {
4989 UserDeclaredMove = *I;
4990 break;
4991 }
4992 }
Richard Smith1c931be2012-04-02 18:40:40 +00004993 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004994 } else if (RD->hasUserDeclaredMoveAssignment() &&
4995 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4996 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004997
4998 // Find any user-declared move assignment operator.
4999 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5000 E = RD->method_end(); I != E; ++I) {
5001 if (I->isMoveAssignmentOperator()) {
5002 UserDeclaredMove = *I;
5003 break;
5004 }
5005 }
Richard Smith1c931be2012-04-02 18:40:40 +00005006 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005007 }
5008
5009 if (UserDeclaredMove) {
5010 Diag(UserDeclaredMove->getLocation(),
5011 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005012 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005013 << UserDeclaredMove->isMoveAssignmentOperator();
5014 return true;
5015 }
5016 }
Sean Hunte16da072011-10-10 06:18:57 +00005017
Richard Smith5bdaac52012-04-02 20:59:25 +00005018 // Do access control from the special member function
5019 ContextRAII MethodContext(*this, MD);
5020
Richard Smith9a561d52012-02-26 09:11:52 +00005021 // C++11 [class.dtor]p5:
5022 // -- for a virtual destructor, lookup of the non-array deallocation function
5023 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005024 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005025 FunctionDecl *OperatorDelete = 0;
5026 DeclarationName Name =
5027 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5028 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005029 OperatorDelete, false)) {
5030 if (Diagnose)
5031 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005032 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005033 }
Richard Smith9a561d52012-02-26 09:11:52 +00005034 }
5035
Richard Smith6c4c36c2012-03-30 20:53:28 +00005036 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005037
Sean Huntcdee3fe2011-05-11 22:34:38 +00005038 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005039 BE = RD->bases_end(); BI != BE; ++BI)
5040 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005041 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005042 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005043
5044 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005045 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00005046 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005047 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005048
5049 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005050 FE = RD->field_end(); FI != FE; ++FI)
5051 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005052 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005053 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005054
Richard Smith7d5088a2012-02-18 02:02:13 +00005055 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005056 return true;
5057
5058 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005059}
5060
Richard Smithac713512012-12-08 02:53:02 +00005061/// Perform lookup for a special member of the specified kind, and determine
5062/// whether it is trivial. If the triviality can be determined without the
5063/// lookup, skip it. This is intended for use when determining whether a
5064/// special member of a containing object is trivial, and thus does not ever
5065/// perform overload resolution for default constructors.
5066///
5067/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5068/// member that was most likely to be intended to be trivial, if any.
5069static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5070 Sema::CXXSpecialMember CSM, unsigned Quals,
5071 CXXMethodDecl **Selected) {
5072 if (Selected)
5073 *Selected = 0;
5074
5075 switch (CSM) {
5076 case Sema::CXXInvalid:
5077 llvm_unreachable("not a special member");
5078
5079 case Sema::CXXDefaultConstructor:
5080 // C++11 [class.ctor]p5:
5081 // A default constructor is trivial if:
5082 // - all the [direct subobjects] have trivial default constructors
5083 //
5084 // Note, no overload resolution is performed in this case.
5085 if (RD->hasTrivialDefaultConstructor())
5086 return true;
5087
5088 if (Selected) {
5089 // If there's a default constructor which could have been trivial, dig it
5090 // out. Otherwise, if there's any user-provided default constructor, point
5091 // to that as an example of why there's not a trivial one.
5092 CXXConstructorDecl *DefCtor = 0;
5093 if (RD->needsImplicitDefaultConstructor())
5094 S.DeclareImplicitDefaultConstructor(RD);
5095 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5096 CE = RD->ctor_end(); CI != CE; ++CI) {
5097 if (!CI->isDefaultConstructor())
5098 continue;
5099 DefCtor = *CI;
5100 if (!DefCtor->isUserProvided())
5101 break;
5102 }
5103
5104 *Selected = DefCtor;
5105 }
5106
5107 return false;
5108
5109 case Sema::CXXDestructor:
5110 // C++11 [class.dtor]p5:
5111 // A destructor is trivial if:
5112 // - all the direct [subobjects] have trivial destructors
5113 if (RD->hasTrivialDestructor())
5114 return true;
5115
5116 if (Selected) {
5117 if (RD->needsImplicitDestructor())
5118 S.DeclareImplicitDestructor(RD);
5119 *Selected = RD->getDestructor();
5120 }
5121
5122 return false;
5123
5124 case Sema::CXXCopyConstructor:
5125 // C++11 [class.copy]p12:
5126 // A copy constructor is trivial if:
5127 // - the constructor selected to copy each direct [subobject] is trivial
5128 if (RD->hasTrivialCopyConstructor()) {
5129 if (Quals == Qualifiers::Const)
5130 // We must either select the trivial copy constructor or reach an
5131 // ambiguity; no need to actually perform overload resolution.
5132 return true;
5133 } else if (!Selected) {
5134 return false;
5135 }
5136 // In C++98, we are not supposed to perform overload resolution here, but we
5137 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5138 // cases like B as having a non-trivial copy constructor:
5139 // struct A { template<typename T> A(T&); };
5140 // struct B { mutable A a; };
5141 goto NeedOverloadResolution;
5142
5143 case Sema::CXXCopyAssignment:
5144 // C++11 [class.copy]p25:
5145 // A copy assignment operator is trivial if:
5146 // - the assignment operator selected to copy each direct [subobject] is
5147 // trivial
5148 if (RD->hasTrivialCopyAssignment()) {
5149 if (Quals == Qualifiers::Const)
5150 return true;
5151 } else if (!Selected) {
5152 return false;
5153 }
5154 // In C++98, we are not supposed to perform overload resolution here, but we
5155 // treat that as a language defect.
5156 goto NeedOverloadResolution;
5157
5158 case Sema::CXXMoveConstructor:
5159 case Sema::CXXMoveAssignment:
5160 NeedOverloadResolution:
5161 Sema::SpecialMemberOverloadResult *SMOR =
5162 S.LookupSpecialMember(RD, CSM,
5163 Quals & Qualifiers::Const,
5164 Quals & Qualifiers::Volatile,
5165 /*RValueThis*/false, /*ConstThis*/false,
5166 /*VolatileThis*/false);
5167
5168 // The standard doesn't describe how to behave if the lookup is ambiguous.
5169 // We treat it as not making the member non-trivial, just like the standard
5170 // mandates for the default constructor. This should rarely matter, because
5171 // the member will also be deleted.
5172 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5173 return true;
5174
5175 if (!SMOR->getMethod()) {
5176 assert(SMOR->getKind() ==
5177 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5178 return false;
5179 }
5180
5181 // We deliberately don't check if we found a deleted special member. We're
5182 // not supposed to!
5183 if (Selected)
5184 *Selected = SMOR->getMethod();
5185 return SMOR->getMethod()->isTrivial();
5186 }
5187
5188 llvm_unreachable("unknown special method kind");
5189}
5190
Benjamin Kramera574c892013-02-15 12:30:38 +00005191static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005192 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5193 CI != CE; ++CI)
5194 if (!CI->isImplicit())
5195 return *CI;
5196
5197 // Look for constructor templates.
5198 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5199 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5200 if (CXXConstructorDecl *CD =
5201 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5202 return CD;
5203 }
5204
5205 return 0;
5206}
5207
5208/// The kind of subobject we are checking for triviality. The values of this
5209/// enumeration are used in diagnostics.
5210enum TrivialSubobjectKind {
5211 /// The subobject is a base class.
5212 TSK_BaseClass,
5213 /// The subobject is a non-static data member.
5214 TSK_Field,
5215 /// The object is actually the complete object.
5216 TSK_CompleteObject
5217};
5218
5219/// Check whether the special member selected for a given type would be trivial.
5220static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5221 QualType SubType,
5222 Sema::CXXSpecialMember CSM,
5223 TrivialSubobjectKind Kind,
5224 bool Diagnose) {
5225 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5226 if (!SubRD)
5227 return true;
5228
5229 CXXMethodDecl *Selected;
5230 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5231 Diagnose ? &Selected : 0))
5232 return true;
5233
5234 if (Diagnose) {
5235 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5236 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5237 << Kind << SubType.getUnqualifiedType();
5238 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5239 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5240 } else if (!Selected)
5241 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5242 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5243 else if (Selected->isUserProvided()) {
5244 if (Kind == TSK_CompleteObject)
5245 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5246 << Kind << SubType.getUnqualifiedType() << CSM;
5247 else {
5248 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5249 << Kind << SubType.getUnqualifiedType() << CSM;
5250 S.Diag(Selected->getLocation(), diag::note_declared_at);
5251 }
5252 } else {
5253 if (Kind != TSK_CompleteObject)
5254 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5255 << Kind << SubType.getUnqualifiedType() << CSM;
5256
5257 // Explain why the defaulted or deleted special member isn't trivial.
5258 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5259 }
5260 }
5261
5262 return false;
5263}
5264
5265/// Check whether the members of a class type allow a special member to be
5266/// trivial.
5267static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5268 Sema::CXXSpecialMember CSM,
5269 bool ConstArg, bool Diagnose) {
5270 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5271 FE = RD->field_end(); FI != FE; ++FI) {
5272 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5273 continue;
5274
5275 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5276
5277 // Pretend anonymous struct or union members are members of this class.
5278 if (FI->isAnonymousStructOrUnion()) {
5279 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5280 CSM, ConstArg, Diagnose))
5281 return false;
5282 continue;
5283 }
5284
5285 // C++11 [class.ctor]p5:
5286 // A default constructor is trivial if [...]
5287 // -- no non-static data member of its class has a
5288 // brace-or-equal-initializer
5289 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5290 if (Diagnose)
5291 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5292 return false;
5293 }
5294
5295 // Objective C ARC 4.3.5:
5296 // [...] nontrivally ownership-qualified types are [...] not trivially
5297 // default constructible, copy constructible, move constructible, copy
5298 // assignable, move assignable, or destructible [...]
5299 if (S.getLangOpts().ObjCAutoRefCount &&
5300 FieldType.hasNonTrivialObjCLifetime()) {
5301 if (Diagnose)
5302 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5303 << RD << FieldType.getObjCLifetime();
5304 return false;
5305 }
5306
5307 if (ConstArg && !FI->isMutable())
5308 FieldType.addConst();
5309 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5310 TSK_Field, Diagnose))
5311 return false;
5312 }
5313
5314 return true;
5315}
5316
5317/// Diagnose why the specified class does not have a trivial special member of
5318/// the given kind.
5319void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5320 QualType Ty = Context.getRecordType(RD);
5321 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5322 Ty.addConst();
5323
5324 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5325 TSK_CompleteObject, /*Diagnose*/true);
5326}
5327
5328/// Determine whether a defaulted or deleted special member function is trivial,
5329/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5330/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5331bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5332 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005333 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5334
5335 CXXRecordDecl *RD = MD->getParent();
5336
5337 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005338
5339 // C++11 [class.copy]p12, p25:
5340 // A [special member] is trivial if its declared parameter type is the same
5341 // as if it had been implicitly declared [...]
5342 switch (CSM) {
5343 case CXXDefaultConstructor:
5344 case CXXDestructor:
5345 // Trivial default constructors and destructors cannot have parameters.
5346 break;
5347
5348 case CXXCopyConstructor:
5349 case CXXCopyAssignment: {
5350 // Trivial copy operations always have const, non-volatile parameter types.
5351 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005352 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005353 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5354 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5355 if (Diagnose)
5356 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5357 << Param0->getSourceRange() << Param0->getType()
5358 << Context.getLValueReferenceType(
5359 Context.getRecordType(RD).withConst());
5360 return false;
5361 }
5362 break;
5363 }
5364
5365 case CXXMoveConstructor:
5366 case CXXMoveAssignment: {
5367 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005368 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005369 const RValueReferenceType *RT =
5370 Param0->getType()->getAs<RValueReferenceType>();
5371 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5372 if (Diagnose)
5373 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5374 << Param0->getSourceRange() << Param0->getType()
5375 << Context.getRValueReferenceType(Context.getRecordType(RD));
5376 return false;
5377 }
5378 break;
5379 }
5380
5381 case CXXInvalid:
5382 llvm_unreachable("not a special member");
5383 }
5384
5385 // FIXME: We require that the parameter-declaration-clause is equivalent to
5386 // that of an implicit declaration, not just that the declared parameter type
5387 // matches, in order to prevent absuridities like a function simultaneously
5388 // being a trivial copy constructor and a non-trivial default constructor.
5389 // This issue has not yet been assigned a core issue number.
5390 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5391 if (Diagnose)
5392 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5393 diag::note_nontrivial_default_arg)
5394 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5395 return false;
5396 }
5397 if (MD->isVariadic()) {
5398 if (Diagnose)
5399 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5400 return false;
5401 }
5402
5403 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5404 // A copy/move [constructor or assignment operator] is trivial if
5405 // -- the [member] selected to copy/move each direct base class subobject
5406 // is trivial
5407 //
5408 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5409 // A [default constructor or destructor] is trivial if
5410 // -- all the direct base classes have trivial [default constructors or
5411 // destructors]
5412 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5413 BE = RD->bases_end(); BI != BE; ++BI)
5414 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5415 ConstArg ? BI->getType().withConst()
5416 : BI->getType(),
5417 CSM, TSK_BaseClass, Diagnose))
5418 return false;
5419
5420 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5421 // A copy/move [constructor or assignment operator] for a class X is
5422 // trivial if
5423 // -- for each non-static data member of X that is of class type (or array
5424 // thereof), the constructor selected to copy/move that member is
5425 // trivial
5426 //
5427 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5428 // A [default constructor or destructor] is trivial if
5429 // -- for all of the non-static data members of its class that are of class
5430 // type (or array thereof), each such class has a trivial [default
5431 // constructor or destructor]
5432 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5433 return false;
5434
5435 // C++11 [class.dtor]p5:
5436 // A destructor is trivial if [...]
5437 // -- the destructor is not virtual
5438 if (CSM == CXXDestructor && MD->isVirtual()) {
5439 if (Diagnose)
5440 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5441 return false;
5442 }
5443
5444 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5445 // A [special member] for class X is trivial if [...]
5446 // -- class X has no virtual functions and no virtual base classes
5447 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5448 if (!Diagnose)
5449 return false;
5450
5451 if (RD->getNumVBases()) {
5452 // Check for virtual bases. We already know that the corresponding
5453 // member in all bases is trivial, so vbases must all be direct.
5454 CXXBaseSpecifier &BS = *RD->vbases_begin();
5455 assert(BS.isVirtual());
5456 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5457 return false;
5458 }
5459
5460 // Must have a virtual method.
5461 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5462 ME = RD->method_end(); MI != ME; ++MI) {
5463 if (MI->isVirtual()) {
5464 SourceLocation MLoc = MI->getLocStart();
5465 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5466 return false;
5467 }
5468 }
5469
5470 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5471 }
5472
5473 // Looks like it's trivial!
5474 return true;
5475}
5476
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005477/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005478namespace {
5479 struct FindHiddenVirtualMethodData {
5480 Sema *S;
5481 CXXMethodDecl *Method;
5482 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005483 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005484 };
5485}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005486
David Blaikie5f750682012-10-19 00:53:08 +00005487/// \brief Check whether any most overriden method from MD in Methods
5488static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5489 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5490 if (MD->size_overridden_methods() == 0)
5491 return Methods.count(MD->getCanonicalDecl());
5492 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5493 E = MD->end_overridden_methods();
5494 I != E; ++I)
5495 if (CheckMostOverridenMethods(*I, Methods))
5496 return true;
5497 return false;
5498}
5499
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005500/// \brief Member lookup function that determines whether a given C++
5501/// method overloads virtual methods in a base class without overriding any,
5502/// to be used with CXXRecordDecl::lookupInBases().
5503static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5504 CXXBasePath &Path,
5505 void *UserData) {
5506 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5507
5508 FindHiddenVirtualMethodData &Data
5509 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5510
5511 DeclarationName Name = Data.Method->getDeclName();
5512 assert(Name.getNameKind() == DeclarationName::Identifier);
5513
5514 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005515 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005516 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005517 !Path.Decls.empty();
5518 Path.Decls = Path.Decls.slice(1)) {
5519 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005520 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005521 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005522 foundSameNameMethod = true;
5523 // Interested only in hidden virtual methods.
5524 if (!MD->isVirtual())
5525 continue;
5526 // If the method we are checking overrides a method from its base
5527 // don't warn about the other overloaded methods.
5528 if (!Data.S->IsOverload(Data.Method, MD, false))
5529 return true;
5530 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005531 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005532 overloadedMethods.push_back(MD);
5533 }
5534 }
5535
5536 if (foundSameNameMethod)
5537 Data.OverloadedMethods.append(overloadedMethods.begin(),
5538 overloadedMethods.end());
5539 return foundSameNameMethod;
5540}
5541
David Blaikie5f750682012-10-19 00:53:08 +00005542/// \brief Add the most overriden methods from MD to Methods
5543static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5544 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5545 if (MD->size_overridden_methods() == 0)
5546 Methods.insert(MD->getCanonicalDecl());
5547 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5548 E = MD->end_overridden_methods();
5549 I != E; ++I)
5550 AddMostOverridenMethods(*I, Methods);
5551}
5552
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005553/// \brief See if a method overloads virtual methods in a base class without
5554/// overriding any.
5555void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5556 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005557 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005558 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005559 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005560 return;
5561
5562 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5563 /*bool RecordPaths=*/false,
5564 /*bool DetectVirtual=*/false);
5565 FindHiddenVirtualMethodData Data;
5566 Data.Method = MD;
5567 Data.S = this;
5568
5569 // Keep the base methods that were overriden or introduced in the subclass
5570 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005571 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5572 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5573 NamedDecl *ND = *I;
5574 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005575 ND = shad->getTargetDecl();
5576 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5577 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005578 }
5579
5580 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5581 !Data.OverloadedMethods.empty()) {
5582 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5583 << MD << (Data.OverloadedMethods.size() > 1);
5584
5585 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5586 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005587 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005588 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005589 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5590 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005591 }
5592 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005593}
5594
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005595void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005596 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005597 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005598 SourceLocation RBrac,
5599 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005600 if (!TagDecl)
5601 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005602
Douglas Gregor42af25f2009-05-11 19:58:34 +00005603 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005604
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005605 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5606 if (l->getKind() != AttributeList::AT_Visibility)
5607 continue;
5608 l->setInvalid();
5609 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5610 l->getName();
5611 }
5612
David Blaikie77b6de02011-09-22 02:58:26 +00005613 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005614 // strict aliasing violation!
5615 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005616 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005617
Douglas Gregor23c94db2010-07-02 17:43:08 +00005618 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005619 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005620}
5621
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005622/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5623/// special functions, such as the default constructor, copy
5624/// constructor, or destructor, to the given C++ class (C++
5625/// [special]p1). This routine can only be executed just before the
5626/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005627void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005628 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005629 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005630
Richard Smithbc2a35d2012-12-08 08:32:28 +00005631 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005632 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005633
Richard Smithbc2a35d2012-12-08 08:32:28 +00005634 // If the properties or semantics of the copy constructor couldn't be
5635 // determined while the class was being declared, force a declaration
5636 // of it now.
5637 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5638 DeclareImplicitCopyConstructor(ClassDecl);
5639 }
5640
Richard Smith80ad52f2013-01-02 11:42:31 +00005641 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005642 ++ASTContext::NumImplicitMoveConstructors;
5643
Richard Smithbc2a35d2012-12-08 08:32:28 +00005644 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5645 DeclareImplicitMoveConstructor(ClassDecl);
5646 }
5647
Douglas Gregora376d102010-07-02 21:50:04 +00005648 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5649 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005650
5651 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005652 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005653 // it shows up in the right place in the vtable and that we diagnose
5654 // problems with the implicit exception specification.
5655 if (ClassDecl->isDynamicClass() ||
5656 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005657 DeclareImplicitCopyAssignment(ClassDecl);
5658 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005659
Richard Smith80ad52f2013-01-02 11:42:31 +00005660 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005661 ++ASTContext::NumImplicitMoveAssignmentOperators;
5662
5663 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005664 if (ClassDecl->isDynamicClass() ||
5665 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005666 DeclareImplicitMoveAssignment(ClassDecl);
5667 }
5668
Douglas Gregor4923aa22010-07-02 20:37:36 +00005669 if (!ClassDecl->hasUserDeclaredDestructor()) {
5670 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005671
5672 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005673 // have to declare the destructor immediately. This ensures that, e.g., it
5674 // shows up in the right place in the vtable and that we diagnose problems
5675 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005676 if (ClassDecl->isDynamicClass() ||
5677 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005678 DeclareImplicitDestructor(ClassDecl);
5679 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005680}
5681
Francois Pichet8387e2a2011-04-22 22:18:13 +00005682void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5683 if (!D)
5684 return;
5685
5686 int NumParamList = D->getNumTemplateParameterLists();
5687 for (int i = 0; i < NumParamList; i++) {
5688 TemplateParameterList* Params = D->getTemplateParameterList(i);
5689 for (TemplateParameterList::iterator Param = Params->begin(),
5690 ParamEnd = Params->end();
5691 Param != ParamEnd; ++Param) {
5692 NamedDecl *Named = cast<NamedDecl>(*Param);
5693 if (Named->getDeclName()) {
5694 S->AddDecl(Named);
5695 IdResolver.AddDecl(Named);
5696 }
5697 }
5698 }
5699}
5700
John McCalld226f652010-08-21 09:40:31 +00005701void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005702 if (!D)
5703 return;
5704
5705 TemplateParameterList *Params = 0;
5706 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5707 Params = Template->getTemplateParameters();
5708 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5709 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5710 Params = PartialSpec->getTemplateParameters();
5711 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005712 return;
5713
Douglas Gregor6569d682009-05-27 23:11:45 +00005714 for (TemplateParameterList::iterator Param = Params->begin(),
5715 ParamEnd = Params->end();
5716 Param != ParamEnd; ++Param) {
5717 NamedDecl *Named = cast<NamedDecl>(*Param);
5718 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005719 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005720 IdResolver.AddDecl(Named);
5721 }
5722 }
5723}
5724
John McCalld226f652010-08-21 09:40:31 +00005725void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005726 if (!RecordD) return;
5727 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005728 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005729 PushDeclContext(S, Record);
5730}
5731
John McCalld226f652010-08-21 09:40:31 +00005732void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005733 if (!RecordD) return;
5734 PopDeclContext();
5735}
5736
Douglas Gregor72b505b2008-12-16 21:30:33 +00005737/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5738/// parsing a top-level (non-nested) C++ class, and we are now
5739/// parsing those parts of the given Method declaration that could
5740/// not be parsed earlier (C++ [class.mem]p2), such as default
5741/// arguments. This action should enter the scope of the given
5742/// Method declaration as if we had just parsed the qualified method
5743/// name. However, it should not bring the parameters into scope;
5744/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005745void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005746}
5747
5748/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5749/// C++ method declaration. We're (re-)introducing the given
5750/// function parameter into scope for use in parsing later parts of
5751/// the method declaration. For example, we could see an
5752/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005753void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005754 if (!ParamD)
5755 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005756
John McCalld226f652010-08-21 09:40:31 +00005757 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005758
5759 // If this parameter has an unparsed default argument, clear it out
5760 // to make way for the parsed default argument.
5761 if (Param->hasUnparsedDefaultArg())
5762 Param->setDefaultArg(0);
5763
John McCalld226f652010-08-21 09:40:31 +00005764 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005765 if (Param->getDeclName())
5766 IdResolver.AddDecl(Param);
5767}
5768
5769/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5770/// processing the delayed method declaration for Method. The method
5771/// declaration is now considered finished. There may be a separate
5772/// ActOnStartOfFunctionDef action later (not necessarily
5773/// immediately!) for this method, if it was also defined inside the
5774/// class body.
John McCalld226f652010-08-21 09:40:31 +00005775void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005776 if (!MethodD)
5777 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005778
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005779 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005780
John McCalld226f652010-08-21 09:40:31 +00005781 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005782
5783 // Now that we have our default arguments, check the constructor
5784 // again. It could produce additional diagnostics or affect whether
5785 // the class has implicitly-declared destructors, among other
5786 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005787 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5788 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005789
5790 // Check the default arguments, which we may have added.
5791 if (!Method->isInvalidDecl())
5792 CheckCXXDefaultArguments(Method);
5793}
5794
Douglas Gregor42a552f2008-11-05 20:51:48 +00005795/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005796/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005797/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005798/// emit diagnostics and set the invalid bit to true. In any case, the type
5799/// will be updated to reflect a well-formed type for the constructor and
5800/// returned.
5801QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005802 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005803 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005804
5805 // C++ [class.ctor]p3:
5806 // A constructor shall not be virtual (10.3) or static (9.4). A
5807 // constructor can be invoked for a const, volatile or const
5808 // volatile object. A constructor shall not be declared const,
5809 // volatile, or const volatile (9.3.2).
5810 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005811 if (!D.isInvalidType())
5812 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5813 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5814 << SourceRange(D.getIdentifierLoc());
5815 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005816 }
John McCalld931b082010-08-26 03:08:43 +00005817 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005818 if (!D.isInvalidType())
5819 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5820 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5821 << SourceRange(D.getIdentifierLoc());
5822 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005823 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005824 }
Mike Stump1eb44332009-09-09 15:08:12 +00005825
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005826 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005827 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005828 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005829 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5830 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005831 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005832 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5833 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005834 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005835 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5836 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005837 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005838 }
Mike Stump1eb44332009-09-09 15:08:12 +00005839
Douglas Gregorc938c162011-01-26 05:01:58 +00005840 // C++0x [class.ctor]p4:
5841 // A constructor shall not be declared with a ref-qualifier.
5842 if (FTI.hasRefQualifier()) {
5843 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5844 << FTI.RefQualifierIsLValueRef
5845 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5846 D.setInvalidType();
5847 }
5848
Douglas Gregor42a552f2008-11-05 20:51:48 +00005849 // Rebuild the function type "R" without any type qualifiers (in
5850 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005851 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005852 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005853 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5854 return R;
5855
5856 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5857 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005858 EPI.RefQualifier = RQ_None;
5859
Richard Smith07b0fdc2013-03-18 21:12:30 +00005860 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005861}
5862
Douglas Gregor72b505b2008-12-16 21:30:33 +00005863/// CheckConstructor - Checks a fully-formed constructor for
5864/// well-formedness, issuing any diagnostics required. Returns true if
5865/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005866void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005867 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005868 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5869 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005870 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005871
5872 // C++ [class.copy]p3:
5873 // A declaration of a constructor for a class X is ill-formed if
5874 // its first parameter is of type (optionally cv-qualified) X and
5875 // either there are no other parameters or else all other
5876 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005877 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005878 ((Constructor->getNumParams() == 1) ||
5879 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005880 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5881 Constructor->getTemplateSpecializationKind()
5882 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005883 QualType ParamType = Constructor->getParamDecl(0)->getType();
5884 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5885 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005886 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005887 const char *ConstRef
5888 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5889 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005890 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005891 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005892
5893 // FIXME: Rather that making the constructor invalid, we should endeavor
5894 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005895 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005896 }
5897 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005898}
5899
John McCall15442822010-08-04 01:04:25 +00005900/// CheckDestructor - Checks a fully-formed destructor definition for
5901/// well-formedness, issuing any diagnostics required. Returns true
5902/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005903bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005904 CXXRecordDecl *RD = Destructor->getParent();
5905
Peter Collingbournef51cfb82013-05-20 14:12:25 +00005906 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005907 SourceLocation Loc;
5908
5909 if (!Destructor->isImplicit())
5910 Loc = Destructor->getLocation();
5911 else
5912 Loc = RD->getLocation();
5913
5914 // If we have a virtual destructor, look up the deallocation function
5915 FunctionDecl *OperatorDelete = 0;
5916 DeclarationName Name =
5917 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005918 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005919 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005920
Eli Friedman5f2987c2012-02-02 03:46:19 +00005921 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005922
5923 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005924 }
Anders Carlsson37909802009-11-30 21:24:50 +00005925
5926 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005927}
5928
Mike Stump1eb44332009-09-09 15:08:12 +00005929static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005930FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5931 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5932 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005933 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005934}
5935
Douglas Gregor42a552f2008-11-05 20:51:48 +00005936/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5937/// the well-formednes of the destructor declarator @p D with type @p
5938/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005939/// emit diagnostics and set the declarator to invalid. Even if this happens,
5940/// will be updated to reflect a well-formed type for the destructor and
5941/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005942QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005943 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005944 // C++ [class.dtor]p1:
5945 // [...] A typedef-name that names a class is a class-name
5946 // (7.1.3); however, a typedef-name that names a class shall not
5947 // be used as the identifier in the declarator for a destructor
5948 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005949 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005950 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005951 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005952 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005953 else if (const TemplateSpecializationType *TST =
5954 DeclaratorType->getAs<TemplateSpecializationType>())
5955 if (TST->isTypeAlias())
5956 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5957 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005958
5959 // C++ [class.dtor]p2:
5960 // A destructor is used to destroy objects of its class type. A
5961 // destructor takes no parameters, and no return type can be
5962 // specified for it (not even void). The address of a destructor
5963 // shall not be taken. A destructor shall not be static. A
5964 // destructor can be invoked for a const, volatile or const
5965 // volatile object. A destructor shall not be declared const,
5966 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005967 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005968 if (!D.isInvalidType())
5969 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5970 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005971 << SourceRange(D.getIdentifierLoc())
5972 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5973
John McCalld931b082010-08-26 03:08:43 +00005974 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005975 }
Chris Lattner65401802009-04-25 08:28:21 +00005976 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005977 // Destructors don't have return types, but the parser will
5978 // happily parse something like:
5979 //
5980 // class X {
5981 // float ~X();
5982 // };
5983 //
5984 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005985 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5986 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5987 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005988 }
Mike Stump1eb44332009-09-09 15:08:12 +00005989
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005990 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005991 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005992 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005993 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5994 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005995 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005996 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5997 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005998 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005999 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6000 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006001 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006002 }
6003
Douglas Gregorc938c162011-01-26 05:01:58 +00006004 // C++0x [class.dtor]p2:
6005 // A destructor shall not be declared with a ref-qualifier.
6006 if (FTI.hasRefQualifier()) {
6007 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6008 << FTI.RefQualifierIsLValueRef
6009 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6010 D.setInvalidType();
6011 }
6012
Douglas Gregor42a552f2008-11-05 20:51:48 +00006013 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006014 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006015 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6016
6017 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006018 FTI.freeArgs();
6019 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006020 }
6021
Mike Stump1eb44332009-09-09 15:08:12 +00006022 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006023 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006024 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006025 D.setInvalidType();
6026 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006027
6028 // Rebuild the function type "R" without any type qualifiers or
6029 // parameters (in case any of the errors above fired) and with
6030 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006031 // types.
John McCalle23cf432010-12-14 08:05:40 +00006032 if (!D.isInvalidType())
6033 return R;
6034
Douglas Gregord92ec472010-07-01 05:10:53 +00006035 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006036 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6037 EPI.Variadic = false;
6038 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006039 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006040 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006041}
6042
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006043/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6044/// well-formednes of the conversion function declarator @p D with
6045/// type @p R. If there are any errors in the declarator, this routine
6046/// will emit diagnostics and return true. Otherwise, it will return
6047/// false. Either way, the type @p R will be updated to reflect a
6048/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006049void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006050 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006051 // C++ [class.conv.fct]p1:
6052 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006053 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006054 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006055 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006056 if (!D.isInvalidType())
6057 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6058 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6059 << SourceRange(D.getIdentifierLoc());
6060 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006061 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006062 }
John McCalla3f81372010-04-13 00:04:31 +00006063
6064 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6065
Chris Lattner6e475012009-04-25 08:35:12 +00006066 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006067 // Conversion functions don't have return types, but the parser will
6068 // happily parse something like:
6069 //
6070 // class X {
6071 // float operator bool();
6072 // };
6073 //
6074 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006075 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6076 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6077 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006078 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006079 }
6080
John McCalla3f81372010-04-13 00:04:31 +00006081 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6082
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006083 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006084 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006085 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6086
6087 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006088 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006089 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006090 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006091 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006092 D.setInvalidType();
6093 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006094
John McCalla3f81372010-04-13 00:04:31 +00006095 // Diagnose "&operator bool()" and other such nonsense. This
6096 // is actually a gcc extension which we don't support.
6097 if (Proto->getResultType() != ConvType) {
6098 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6099 << Proto->getResultType();
6100 D.setInvalidType();
6101 ConvType = Proto->getResultType();
6102 }
6103
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006104 // C++ [class.conv.fct]p4:
6105 // The conversion-type-id shall not represent a function type nor
6106 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006107 if (ConvType->isArrayType()) {
6108 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6109 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006110 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006111 } else if (ConvType->isFunctionType()) {
6112 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6113 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006114 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006115 }
6116
6117 // Rebuild the function type "R" without any parameters (in case any
6118 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006119 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006120 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006121 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006122
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006123 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006124 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006125 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006126 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006127 diag::warn_cxx98_compat_explicit_conversion_functions :
6128 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006129 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006130}
6131
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006132/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6133/// the declaration of the given C++ conversion function. This routine
6134/// is responsible for recording the conversion function in the C++
6135/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006136Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006137 assert(Conversion && "Expected to receive a conversion function declaration");
6138
Douglas Gregor9d350972008-12-12 08:25:50 +00006139 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006140
6141 // Make sure we aren't redeclaring the conversion function.
6142 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006143
6144 // C++ [class.conv.fct]p1:
6145 // [...] A conversion function is never used to convert a
6146 // (possibly cv-qualified) object to the (possibly cv-qualified)
6147 // same object type (or a reference to it), to a (possibly
6148 // cv-qualified) base class of that type (or a reference to it),
6149 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006150 // FIXME: Suppress this warning if the conversion function ends up being a
6151 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006152 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006153 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006154 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006155 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006156 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6157 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006158 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006159 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006160 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6161 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006162 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006163 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006164 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006165 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006166 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006167 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006168 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006169 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006170 }
6171
Douglas Gregore80622f2010-09-29 04:25:11 +00006172 if (FunctionTemplateDecl *ConversionTemplate
6173 = Conversion->getDescribedFunctionTemplate())
6174 return ConversionTemplate;
6175
John McCalld226f652010-08-21 09:40:31 +00006176 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006177}
6178
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006179//===----------------------------------------------------------------------===//
6180// Namespace Handling
6181//===----------------------------------------------------------------------===//
6182
Richard Smithd1a55a62012-10-04 22:13:39 +00006183/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6184/// reopened.
6185static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6186 SourceLocation Loc,
6187 IdentifierInfo *II, bool *IsInline,
6188 NamespaceDecl *PrevNS) {
6189 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006190
Richard Smithc969e6a2012-10-05 01:46:25 +00006191 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6192 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6193 // inline namespaces, with the intention of bringing names into namespace std.
6194 //
6195 // We support this just well enough to get that case working; this is not
6196 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006197 if (*IsInline && II && II->getName().startswith("__atomic") &&
6198 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006199 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006200 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6201 NS = NS->getPreviousDecl())
6202 NS->setInline(*IsInline);
6203 // Patch up the lookup table for the containing namespace. This isn't really
6204 // correct, but it's good enough for this particular case.
6205 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6206 E = PrevNS->decls_end(); I != E; ++I)
6207 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6208 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6209 return;
6210 }
6211
6212 if (PrevNS->isInline())
6213 // The user probably just forgot the 'inline', so suggest that it
6214 // be added back.
6215 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6216 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6217 else
6218 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6219 << IsInline;
6220
6221 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6222 *IsInline = PrevNS->isInline();
6223}
John McCallea318642010-08-26 09:15:37 +00006224
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006225/// ActOnStartNamespaceDef - This is called at the start of a namespace
6226/// definition.
John McCalld226f652010-08-21 09:40:31 +00006227Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006228 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006229 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006230 SourceLocation IdentLoc,
6231 IdentifierInfo *II,
6232 SourceLocation LBrace,
6233 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006234 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6235 // For anonymous namespace, take the location of the left brace.
6236 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006237 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006238 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006239 bool IsStd = false;
6240 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006241 Scope *DeclRegionScope = NamespcScope->getParent();
6242
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006243 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006244 if (II) {
6245 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006246 // The identifier in an original-namespace-definition shall not
6247 // have been previously defined in the declarative region in
6248 // which the original-namespace-definition appears. The
6249 // identifier in an original-namespace-definition is the name of
6250 // the namespace. Subsequently in that declarative region, it is
6251 // treated as an original-namespace-name.
6252 //
6253 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006254 // look through using directives, just look for any ordinary names.
6255
6256 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006257 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6258 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006259 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006260 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6261 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6262 ++I) {
6263 if ((*I)->getIdentifierNamespace() & IDNS) {
6264 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006265 break;
6266 }
6267 }
6268
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006269 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6270
6271 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006272 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006273 if (IsInline != PrevNS->isInline())
6274 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6275 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006276 } else if (PrevDecl) {
6277 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006278 Diag(Loc, diag::err_redefinition_different_kind)
6279 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006280 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006281 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006282 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006283 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006284 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006285 // This is the first "real" definition of the namespace "std", so update
6286 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006287 PrevNS = getStdNamespace();
6288 IsStd = true;
6289 AddToKnown = !IsInline;
6290 } else {
6291 // We've seen this namespace for the first time.
6292 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006293 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006294 } else {
John McCall9aeed322009-10-01 00:25:31 +00006295 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006296
6297 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006298 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006299 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006300 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006301 } else {
6302 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006303 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006304 }
6305
Richard Smithd1a55a62012-10-04 22:13:39 +00006306 if (PrevNS && IsInline != PrevNS->isInline())
6307 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6308 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006309 }
6310
6311 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6312 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006313 if (IsInvalid)
6314 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006315
6316 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006317
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006318 // FIXME: Should we be merging attributes?
6319 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006320 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006321
6322 if (IsStd)
6323 StdNamespace = Namespc;
6324 if (AddToKnown)
6325 KnownNamespaces[Namespc] = false;
6326
6327 if (II) {
6328 PushOnScopeChains(Namespc, DeclRegionScope);
6329 } else {
6330 // Link the anonymous namespace into its parent.
6331 DeclContext *Parent = CurContext->getRedeclContext();
6332 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6333 TU->setAnonymousNamespace(Namespc);
6334 } else {
6335 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006336 }
John McCall9aeed322009-10-01 00:25:31 +00006337
Douglas Gregora4181472010-03-24 00:46:35 +00006338 CurContext->addDecl(Namespc);
6339
John McCall9aeed322009-10-01 00:25:31 +00006340 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6341 // behaves as if it were replaced by
6342 // namespace unique { /* empty body */ }
6343 // using namespace unique;
6344 // namespace unique { namespace-body }
6345 // where all occurrences of 'unique' in a translation unit are
6346 // replaced by the same identifier and this identifier differs
6347 // from all other identifiers in the entire program.
6348
6349 // We just create the namespace with an empty name and then add an
6350 // implicit using declaration, just like the standard suggests.
6351 //
6352 // CodeGen enforces the "universally unique" aspect by giving all
6353 // declarations semantically contained within an anonymous
6354 // namespace internal linkage.
6355
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006356 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006357 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006358 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006359 /* 'using' */ LBrace,
6360 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006361 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006362 /* identifier */ SourceLocation(),
6363 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006364 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006365 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006366 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006367 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006368 }
6369
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006370 ActOnDocumentableDecl(Namespc);
6371
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006372 // Although we could have an invalid decl (i.e. the namespace name is a
6373 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006374 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6375 // for the namespace has the declarations that showed up in that particular
6376 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006377 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006378 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006379}
6380
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006381/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6382/// is a namespace alias, returns the namespace it points to.
6383static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6384 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6385 return AD->getNamespace();
6386 return dyn_cast_or_null<NamespaceDecl>(D);
6387}
6388
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006389/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6390/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006391void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006392 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6393 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006394 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006395 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006396 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006397 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006398}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006399
John McCall384aff82010-08-25 07:42:41 +00006400CXXRecordDecl *Sema::getStdBadAlloc() const {
6401 return cast_or_null<CXXRecordDecl>(
6402 StdBadAlloc.get(Context.getExternalSource()));
6403}
6404
6405NamespaceDecl *Sema::getStdNamespace() const {
6406 return cast_or_null<NamespaceDecl>(
6407 StdNamespace.get(Context.getExternalSource()));
6408}
6409
Douglas Gregor66992202010-06-29 17:53:46 +00006410/// \brief Retrieve the special "std" namespace, which may require us to
6411/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006412NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006413 if (!StdNamespace) {
6414 // The "std" namespace has not yet been defined, so build one implicitly.
6415 StdNamespace = NamespaceDecl::Create(Context,
6416 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006417 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006418 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006419 &PP.getIdentifierTable().get("std"),
6420 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006421 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006422 }
6423
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006424 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006425}
6426
Sebastian Redl395e04d2012-01-17 22:49:33 +00006427bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006428 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006429 "Looking for std::initializer_list outside of C++.");
6430
6431 // We're looking for implicit instantiations of
6432 // template <typename E> class std::initializer_list.
6433
6434 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6435 return false;
6436
Sebastian Redl84760e32012-01-17 22:49:58 +00006437 ClassTemplateDecl *Template = 0;
6438 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006439
Sebastian Redl84760e32012-01-17 22:49:58 +00006440 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006441
Sebastian Redl84760e32012-01-17 22:49:58 +00006442 ClassTemplateSpecializationDecl *Specialization =
6443 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6444 if (!Specialization)
6445 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006446
Sebastian Redl84760e32012-01-17 22:49:58 +00006447 Template = Specialization->getSpecializedTemplate();
6448 Arguments = Specialization->getTemplateArgs().data();
6449 } else if (const TemplateSpecializationType *TST =
6450 Ty->getAs<TemplateSpecializationType>()) {
6451 Template = dyn_cast_or_null<ClassTemplateDecl>(
6452 TST->getTemplateName().getAsTemplateDecl());
6453 Arguments = TST->getArgs();
6454 }
6455 if (!Template)
6456 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006457
6458 if (!StdInitializerList) {
6459 // Haven't recognized std::initializer_list yet, maybe this is it.
6460 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6461 if (TemplateClass->getIdentifier() !=
6462 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006463 !getStdNamespace()->InEnclosingNamespaceSetOf(
6464 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006465 return false;
6466 // This is a template called std::initializer_list, but is it the right
6467 // template?
6468 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006469 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006470 return false;
6471 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6472 return false;
6473
6474 // It's the right template.
6475 StdInitializerList = Template;
6476 }
6477
6478 if (Template != StdInitializerList)
6479 return false;
6480
6481 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006482 if (Element)
6483 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006484 return true;
6485}
6486
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006487static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6488 NamespaceDecl *Std = S.getStdNamespace();
6489 if (!Std) {
6490 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6491 return 0;
6492 }
6493
6494 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6495 Loc, Sema::LookupOrdinaryName);
6496 if (!S.LookupQualifiedName(Result, Std)) {
6497 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6498 return 0;
6499 }
6500 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6501 if (!Template) {
6502 Result.suppressDiagnostics();
6503 // We found something weird. Complain about the first thing we found.
6504 NamedDecl *Found = *Result.begin();
6505 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6506 return 0;
6507 }
6508
6509 // We found some template called std::initializer_list. Now verify that it's
6510 // correct.
6511 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006512 if (Params->getMinRequiredArguments() != 1 ||
6513 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006514 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6515 return 0;
6516 }
6517
6518 return Template;
6519}
6520
6521QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6522 if (!StdInitializerList) {
6523 StdInitializerList = LookupStdInitializerList(*this, Loc);
6524 if (!StdInitializerList)
6525 return QualType();
6526 }
6527
6528 TemplateArgumentListInfo Args(Loc, Loc);
6529 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6530 Context.getTrivialTypeSourceInfo(Element,
6531 Loc)));
6532 return Context.getCanonicalType(
6533 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6534}
6535
Sebastian Redl98d36062012-01-17 22:50:14 +00006536bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6537 // C++ [dcl.init.list]p2:
6538 // A constructor is an initializer-list constructor if its first parameter
6539 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6540 // std::initializer_list<E> for some type E, and either there are no other
6541 // parameters or else all other parameters have default arguments.
6542 if (Ctor->getNumParams() < 1 ||
6543 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6544 return false;
6545
6546 QualType ArgType = Ctor->getParamDecl(0)->getType();
6547 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6548 ArgType = RT->getPointeeType().getUnqualifiedType();
6549
6550 return isStdInitializerList(ArgType, 0);
6551}
6552
Douglas Gregor9172aa62011-03-26 22:25:30 +00006553/// \brief Determine whether a using statement is in a context where it will be
6554/// apply in all contexts.
6555static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6556 switch (CurContext->getDeclKind()) {
6557 case Decl::TranslationUnit:
6558 return true;
6559 case Decl::LinkageSpec:
6560 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6561 default:
6562 return false;
6563 }
6564}
6565
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006566namespace {
6567
6568// Callback to only accept typo corrections that are namespaces.
6569class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6570 public:
6571 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6572 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6573 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6574 }
6575 return false;
6576 }
6577};
6578
6579}
6580
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006581static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6582 CXXScopeSpec &SS,
6583 SourceLocation IdentLoc,
6584 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006585 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006586 R.clear();
6587 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006588 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006589 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006590 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6591 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006592 if (DeclContext *DC = S.computeDeclContext(SS, false))
6593 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6594 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006595 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6596 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006597 else
6598 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6599 << Ident << CorrectedQuotedStr
6600 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006601
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006602 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6603 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006604
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006605 R.addDecl(Corrected.getCorrectionDecl());
6606 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006607 }
6608 return false;
6609}
6610
John McCalld226f652010-08-21 09:40:31 +00006611Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006612 SourceLocation UsingLoc,
6613 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006614 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006615 SourceLocation IdentLoc,
6616 IdentifierInfo *NamespcName,
6617 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006618 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6619 assert(NamespcName && "Invalid NamespcName.");
6620 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006621
6622 // This can only happen along a recovery path.
6623 while (S->getFlags() & Scope::TemplateParamScope)
6624 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006625 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006626
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006627 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006628 NestedNameSpecifier *Qualifier = 0;
6629 if (SS.isSet())
6630 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6631
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006632 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006633 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6634 LookupParsedName(R, S, &SS);
6635 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006636 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006637
Douglas Gregor66992202010-06-29 17:53:46 +00006638 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006639 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006640 // Allow "using namespace std;" or "using namespace ::std;" even if
6641 // "std" hasn't been defined yet, for GCC compatibility.
6642 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6643 NamespcName->isStr("std")) {
6644 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006645 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006646 R.resolveKind();
6647 }
6648 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006649 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006650 }
6651
John McCallf36e02d2009-10-09 21:13:30 +00006652 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006653 NamedDecl *Named = R.getFoundDecl();
6654 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6655 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006656 // C++ [namespace.udir]p1:
6657 // A using-directive specifies that the names in the nominated
6658 // namespace can be used in the scope in which the
6659 // using-directive appears after the using-directive. During
6660 // unqualified name lookup (3.4.1), the names appear as if they
6661 // were declared in the nearest enclosing namespace which
6662 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006663 // namespace. [Note: in this context, "contains" means "contains
6664 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006665
6666 // Find enclosing context containing both using-directive and
6667 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006668 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006669 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6670 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6671 CommonAncestor = CommonAncestor->getParent();
6672
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006673 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006674 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006675 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006676
Douglas Gregor9172aa62011-03-26 22:25:30 +00006677 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006678 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006679 Diag(IdentLoc, diag::warn_using_directive_in_header);
6680 }
6681
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006682 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006683 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006684 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006685 }
6686
Richard Smith6b3d3e52013-02-20 19:22:51 +00006687 if (UDir)
6688 ProcessDeclAttributeList(S, UDir, AttrList);
6689
John McCalld226f652010-08-21 09:40:31 +00006690 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006691}
6692
6693void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006694 // If the scope has an associated entity and the using directive is at
6695 // namespace or translation unit scope, add the UsingDirectiveDecl into
6696 // its lookup structure so qualified name lookup can find it.
6697 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6698 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006699 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006700 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006701 // Otherwise, it is at block sope. The using-directives will affect lookup
6702 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006703 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006704}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006705
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006706
John McCalld226f652010-08-21 09:40:31 +00006707Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006708 AccessSpecifier AS,
6709 bool HasUsingKeyword,
6710 SourceLocation UsingLoc,
6711 CXXScopeSpec &SS,
6712 UnqualifiedId &Name,
6713 AttributeList *AttrList,
6714 bool IsTypeName,
6715 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006716 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006717
Douglas Gregor12c118a2009-11-04 16:30:06 +00006718 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006719 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006720 case UnqualifiedId::IK_Identifier:
6721 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006722 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006723 case UnqualifiedId::IK_ConversionFunctionId:
6724 break;
6725
6726 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006727 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006728 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006729 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006730 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006731 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006732 diag::err_using_decl_constructor)
6733 << SS.getRange();
6734
Richard Smith80ad52f2013-01-02 11:42:31 +00006735 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006736
John McCalld226f652010-08-21 09:40:31 +00006737 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006738
6739 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006740 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006741 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006742 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006743
6744 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006745 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006746 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006747 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006748 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006749
6750 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6751 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006752 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006753 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006754
Richard Smith07b0fdc2013-03-18 21:12:30 +00006755 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006756 // TODO: store that the declaration was written without 'using' and
6757 // talk about access decls instead of using decls in the
6758 // diagnostics.
6759 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006760 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006761
6762 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006763 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006764 }
6765
Douglas Gregor56c04582010-12-16 00:46:58 +00006766 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6767 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6768 return 0;
6769
John McCall9488ea12009-11-17 05:59:44 +00006770 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006771 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006772 /* IsInstantiation */ false,
6773 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006774 if (UD)
6775 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006776
John McCalld226f652010-08-21 09:40:31 +00006777 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006778}
6779
Douglas Gregor09acc982010-07-07 23:08:52 +00006780/// \brief Determine whether a using declaration considers the given
6781/// declarations as "equivalent", e.g., if they are redeclarations of
6782/// the same entity or are both typedefs of the same type.
6783static bool
6784IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6785 bool &SuppressRedeclaration) {
6786 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6787 SuppressRedeclaration = false;
6788 return true;
6789 }
6790
Richard Smith162e1c12011-04-15 14:24:37 +00006791 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6792 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006793 SuppressRedeclaration = true;
6794 return Context.hasSameType(TD1->getUnderlyingType(),
6795 TD2->getUnderlyingType());
6796 }
6797
6798 return false;
6799}
6800
6801
John McCall9f54ad42009-12-10 09:41:52 +00006802/// Determines whether to create a using shadow decl for a particular
6803/// decl, given the set of decls existing prior to this using lookup.
6804bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6805 const LookupResult &Previous) {
6806 // Diagnose finding a decl which is not from a base class of the
6807 // current class. We do this now because there are cases where this
6808 // function will silently decide not to build a shadow decl, which
6809 // will pre-empt further diagnostics.
6810 //
6811 // We don't need to do this in C++0x because we do the check once on
6812 // the qualifier.
6813 //
6814 // FIXME: diagnose the following if we care enough:
6815 // struct A { int foo; };
6816 // struct B : A { using A::foo; };
6817 // template <class T> struct C : A {};
6818 // template <class T> struct D : C<T> { using B::foo; } // <---
6819 // This is invalid (during instantiation) in C++03 because B::foo
6820 // resolves to the using decl in B, which is not a base class of D<T>.
6821 // We can't diagnose it immediately because C<T> is an unknown
6822 // specialization. The UsingShadowDecl in D<T> then points directly
6823 // to A::foo, which will look well-formed when we instantiate.
6824 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006825 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006826 DeclContext *OrigDC = Orig->getDeclContext();
6827
6828 // Handle enums and anonymous structs.
6829 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6830 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6831 while (OrigRec->isAnonymousStructOrUnion())
6832 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6833
6834 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6835 if (OrigDC == CurContext) {
6836 Diag(Using->getLocation(),
6837 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006838 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006839 Diag(Orig->getLocation(), diag::note_using_decl_target);
6840 return true;
6841 }
6842
Douglas Gregordc355712011-02-25 00:36:19 +00006843 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006844 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006845 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006846 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006847 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006848 Diag(Orig->getLocation(), diag::note_using_decl_target);
6849 return true;
6850 }
6851 }
6852
6853 if (Previous.empty()) return false;
6854
6855 NamedDecl *Target = Orig;
6856 if (isa<UsingShadowDecl>(Target))
6857 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6858
John McCalld7533ec2009-12-11 02:33:26 +00006859 // If the target happens to be one of the previous declarations, we
6860 // don't have a conflict.
6861 //
6862 // FIXME: but we might be increasing its access, in which case we
6863 // should redeclare it.
6864 NamedDecl *NonTag = 0, *Tag = 0;
6865 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6866 I != E; ++I) {
6867 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006868 bool Result;
6869 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6870 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006871
6872 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6873 }
6874
John McCall9f54ad42009-12-10 09:41:52 +00006875 if (Target->isFunctionOrFunctionTemplate()) {
6876 FunctionDecl *FD;
6877 if (isa<FunctionTemplateDecl>(Target))
6878 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6879 else
6880 FD = cast<FunctionDecl>(Target);
6881
6882 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006883 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006884 case Ovl_Overload:
6885 return false;
6886
6887 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006888 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006889 break;
6890
6891 // We found a decl with the exact signature.
6892 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006893 // If we're in a record, we want to hide the target, so we
6894 // return true (without a diagnostic) to tell the caller not to
6895 // build a shadow decl.
6896 if (CurContext->isRecord())
6897 return true;
6898
6899 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006900 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006901 break;
6902 }
6903
6904 Diag(Target->getLocation(), diag::note_using_decl_target);
6905 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6906 return true;
6907 }
6908
6909 // Target is not a function.
6910
John McCall9f54ad42009-12-10 09:41:52 +00006911 if (isa<TagDecl>(Target)) {
6912 // No conflict between a tag and a non-tag.
6913 if (!Tag) return false;
6914
John McCall41ce66f2009-12-10 19:51:03 +00006915 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006916 Diag(Target->getLocation(), diag::note_using_decl_target);
6917 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6918 return true;
6919 }
6920
6921 // No conflict between a tag and a non-tag.
6922 if (!NonTag) return false;
6923
John McCall41ce66f2009-12-10 19:51:03 +00006924 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006925 Diag(Target->getLocation(), diag::note_using_decl_target);
6926 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6927 return true;
6928}
6929
John McCall9488ea12009-11-17 05:59:44 +00006930/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006931UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006932 UsingDecl *UD,
6933 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006934
6935 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006936 NamedDecl *Target = Orig;
6937 if (isa<UsingShadowDecl>(Target)) {
6938 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6939 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006940 }
6941
6942 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006943 = UsingShadowDecl::Create(Context, CurContext,
6944 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006945 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006946
6947 Shadow->setAccess(UD->getAccess());
6948 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6949 Shadow->setInvalidDecl();
6950
John McCall9488ea12009-11-17 05:59:44 +00006951 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006952 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006953 else
John McCall604e7f12009-12-08 07:46:18 +00006954 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006955
John McCall604e7f12009-12-08 07:46:18 +00006956
John McCall9f54ad42009-12-10 09:41:52 +00006957 return Shadow;
6958}
John McCall604e7f12009-12-08 07:46:18 +00006959
John McCall9f54ad42009-12-10 09:41:52 +00006960/// Hides a using shadow declaration. This is required by the current
6961/// using-decl implementation when a resolvable using declaration in a
6962/// class is followed by a declaration which would hide or override
6963/// one or more of the using decl's targets; for example:
6964///
6965/// struct Base { void foo(int); };
6966/// struct Derived : Base {
6967/// using Base::foo;
6968/// void foo(int);
6969/// };
6970///
6971/// The governing language is C++03 [namespace.udecl]p12:
6972///
6973/// When a using-declaration brings names from a base class into a
6974/// derived class scope, member functions in the derived class
6975/// override and/or hide member functions with the same name and
6976/// parameter types in a base class (rather than conflicting).
6977///
6978/// There are two ways to implement this:
6979/// (1) optimistically create shadow decls when they're not hidden
6980/// by existing declarations, or
6981/// (2) don't create any shadow decls (or at least don't make them
6982/// visible) until we've fully parsed/instantiated the class.
6983/// The problem with (1) is that we might have to retroactively remove
6984/// a shadow decl, which requires several O(n) operations because the
6985/// decl structures are (very reasonably) not designed for removal.
6986/// (2) avoids this but is very fiddly and phase-dependent.
6987void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006988 if (Shadow->getDeclName().getNameKind() ==
6989 DeclarationName::CXXConversionFunctionName)
6990 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6991
John McCall9f54ad42009-12-10 09:41:52 +00006992 // Remove it from the DeclContext...
6993 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006994
John McCall9f54ad42009-12-10 09:41:52 +00006995 // ...and the scope, if applicable...
6996 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006997 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006998 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006999 }
7000
John McCall9f54ad42009-12-10 09:41:52 +00007001 // ...and the using decl.
7002 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7003
7004 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007005 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007006}
7007
John McCall7ba107a2009-11-18 02:36:19 +00007008/// Builds a using declaration.
7009///
7010/// \param IsInstantiation - Whether this call arises from an
7011/// instantiation of an unresolved using declaration. We treat
7012/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007013NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7014 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007015 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007016 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007017 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007018 bool IsInstantiation,
7019 bool IsTypeName,
7020 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007021 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007022 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007023 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007024
Anders Carlsson550b14b2009-08-28 05:49:21 +00007025 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007026
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007027 if (SS.isEmpty()) {
7028 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007029 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007030 }
Mike Stump1eb44332009-09-09 15:08:12 +00007031
John McCall9f54ad42009-12-10 09:41:52 +00007032 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007033 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007034 ForRedeclaration);
7035 Previous.setHideTags(false);
7036 if (S) {
7037 LookupName(Previous, S);
7038
7039 // It is really dumb that we have to do this.
7040 LookupResult::Filter F = Previous.makeFilter();
7041 while (F.hasNext()) {
7042 NamedDecl *D = F.next();
7043 if (!isDeclInScope(D, CurContext, S))
7044 F.erase();
7045 }
7046 F.done();
7047 } else {
7048 assert(IsInstantiation && "no scope in non-instantiation");
7049 assert(CurContext->isRecord() && "scope not record in instantiation");
7050 LookupQualifiedName(Previous, CurContext);
7051 }
7052
John McCall9f54ad42009-12-10 09:41:52 +00007053 // Check for invalid redeclarations.
7054 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7055 return 0;
7056
7057 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007058 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7059 return 0;
7060
John McCallaf8e6ed2009-11-12 03:15:40 +00007061 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007062 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007063 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007064 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00007065 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00007066 // FIXME: not all declaration name kinds are legal here
7067 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7068 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007069 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007070 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007071 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007072 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7073 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007074 }
John McCalled976492009-12-04 22:46:56 +00007075 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007076 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7077 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007078 }
John McCalled976492009-12-04 22:46:56 +00007079 D->setAccess(AS);
7080 CurContext->addDecl(D);
7081
7082 if (!LookupContext) return D;
7083 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007084
John McCall77bb1aa2010-05-01 00:40:08 +00007085 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007086 UD->setInvalidDecl();
7087 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007088 }
7089
Richard Smithc5a89a12012-04-02 01:30:27 +00007090 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007091 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007092 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007093 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007094 return UD;
7095 }
7096
7097 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007098
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007099 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007100
John McCall604e7f12009-12-08 07:46:18 +00007101 // Unlike most lookups, we don't always want to hide tag
7102 // declarations: tag names are visible through the using declaration
7103 // even if hidden by ordinary names, *except* in a dependent context
7104 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007105 if (!IsInstantiation)
7106 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007107
John McCallb9abd8722012-04-07 03:04:20 +00007108 // For the purposes of this lookup, we have a base object type
7109 // equal to that of the current context.
7110 if (CurContext->isRecord()) {
7111 R.setBaseObjectType(
7112 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7113 }
7114
John McCalla24dc2e2009-11-17 02:14:36 +00007115 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007116
John McCallf36e02d2009-10-09 21:13:30 +00007117 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00007118 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007119 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007120 UD->setInvalidDecl();
7121 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007122 }
7123
John McCalled976492009-12-04 22:46:56 +00007124 if (R.isAmbiguous()) {
7125 UD->setInvalidDecl();
7126 return UD;
7127 }
Mike Stump1eb44332009-09-09 15:08:12 +00007128
John McCall7ba107a2009-11-18 02:36:19 +00007129 if (IsTypeName) {
7130 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007131 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007132 Diag(IdentLoc, diag::err_using_typename_non_type);
7133 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7134 Diag((*I)->getUnderlyingDecl()->getLocation(),
7135 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007136 UD->setInvalidDecl();
7137 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007138 }
7139 } else {
7140 // If we asked for a non-typename and we got a type, error out,
7141 // but only if this is an instantiation of an unresolved using
7142 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007143 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007144 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7145 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007146 UD->setInvalidDecl();
7147 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007148 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007149 }
7150
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007151 // C++0x N2914 [namespace.udecl]p6:
7152 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007153 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007154 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7155 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007156 UD->setInvalidDecl();
7157 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007158 }
Mike Stump1eb44332009-09-09 15:08:12 +00007159
John McCall9f54ad42009-12-10 09:41:52 +00007160 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7161 if (!CheckUsingShadowDecl(UD, *I, Previous))
7162 BuildUsingShadowDecl(S, UD, *I);
7163 }
John McCall9488ea12009-11-17 05:59:44 +00007164
7165 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007166}
7167
Sebastian Redlf677ea32011-02-05 19:23:19 +00007168/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007169bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7170 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007171
Douglas Gregordc355712011-02-25 00:36:19 +00007172 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007173 assert(SourceType &&
7174 "Using decl naming constructor doesn't have type in scope spec.");
7175 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7176
7177 // Check whether the named type is a direct base class.
7178 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7179 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7180 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7181 BaseIt != BaseE; ++BaseIt) {
7182 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7183 if (CanonicalSourceType == BaseType)
7184 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007185 if (BaseIt->getType()->isDependentType())
7186 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007187 }
7188
7189 if (BaseIt == BaseE) {
7190 // Did not find SourceType in the bases.
7191 Diag(UD->getUsingLocation(),
7192 diag::err_using_decl_constructor_not_in_direct_base)
7193 << UD->getNameInfo().getSourceRange()
7194 << QualType(SourceType, 0) << TargetClass;
7195 return true;
7196 }
7197
Richard Smithc5a89a12012-04-02 01:30:27 +00007198 if (!CurContext->isDependentContext())
7199 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007200
7201 return false;
7202}
7203
John McCall9f54ad42009-12-10 09:41:52 +00007204/// Checks that the given using declaration is not an invalid
7205/// redeclaration. Note that this is checking only for the using decl
7206/// itself, not for any ill-formedness among the UsingShadowDecls.
7207bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7208 bool isTypeName,
7209 const CXXScopeSpec &SS,
7210 SourceLocation NameLoc,
7211 const LookupResult &Prev) {
7212 // C++03 [namespace.udecl]p8:
7213 // C++0x [namespace.udecl]p10:
7214 // A using-declaration is a declaration and can therefore be used
7215 // repeatedly where (and only where) multiple declarations are
7216 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007217 //
John McCall8a726212010-11-29 18:01:58 +00007218 // That's in non-member contexts.
7219 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007220 return false;
7221
7222 NestedNameSpecifier *Qual
7223 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7224
7225 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7226 NamedDecl *D = *I;
7227
7228 bool DTypename;
7229 NestedNameSpecifier *DQual;
7230 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7231 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007232 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007233 } else if (UnresolvedUsingValueDecl *UD
7234 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7235 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007236 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007237 } else if (UnresolvedUsingTypenameDecl *UD
7238 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7239 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007240 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007241 } else continue;
7242
7243 // using decls differ if one says 'typename' and the other doesn't.
7244 // FIXME: non-dependent using decls?
7245 if (isTypeName != DTypename) continue;
7246
7247 // using decls differ if they name different scopes (but note that
7248 // template instantiation can cause this check to trigger when it
7249 // didn't before instantiation).
7250 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7251 Context.getCanonicalNestedNameSpecifier(DQual))
7252 continue;
7253
7254 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007255 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007256 return true;
7257 }
7258
7259 return false;
7260}
7261
John McCall604e7f12009-12-08 07:46:18 +00007262
John McCalled976492009-12-04 22:46:56 +00007263/// Checks that the given nested-name qualifier used in a using decl
7264/// in the current context is appropriately related to the current
7265/// scope. If an error is found, diagnoses it and returns true.
7266bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7267 const CXXScopeSpec &SS,
7268 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007269 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007270
John McCall604e7f12009-12-08 07:46:18 +00007271 if (!CurContext->isRecord()) {
7272 // C++03 [namespace.udecl]p3:
7273 // C++0x [namespace.udecl]p8:
7274 // A using-declaration for a class member shall be a member-declaration.
7275
7276 // If we weren't able to compute a valid scope, it must be a
7277 // dependent class scope.
7278 if (!NamedContext || NamedContext->isRecord()) {
7279 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7280 << SS.getRange();
7281 return true;
7282 }
7283
7284 // Otherwise, everything is known to be fine.
7285 return false;
7286 }
7287
7288 // The current scope is a record.
7289
7290 // If the named context is dependent, we can't decide much.
7291 if (!NamedContext) {
7292 // FIXME: in C++0x, we can diagnose if we can prove that the
7293 // nested-name-specifier does not refer to a base class, which is
7294 // still possible in some cases.
7295
7296 // Otherwise we have to conservatively report that things might be
7297 // okay.
7298 return false;
7299 }
7300
7301 if (!NamedContext->isRecord()) {
7302 // Ideally this would point at the last name in the specifier,
7303 // but we don't have that level of source info.
7304 Diag(SS.getRange().getBegin(),
7305 diag::err_using_decl_nested_name_specifier_is_not_class)
7306 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7307 return true;
7308 }
7309
Douglas Gregor6fb07292010-12-21 07:41:49 +00007310 if (!NamedContext->isDependentContext() &&
7311 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7312 return true;
7313
Richard Smith80ad52f2013-01-02 11:42:31 +00007314 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007315 // C++0x [namespace.udecl]p3:
7316 // In a using-declaration used as a member-declaration, the
7317 // nested-name-specifier shall name a base class of the class
7318 // being defined.
7319
7320 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7321 cast<CXXRecordDecl>(NamedContext))) {
7322 if (CurContext == NamedContext) {
7323 Diag(NameLoc,
7324 diag::err_using_decl_nested_name_specifier_is_current_class)
7325 << SS.getRange();
7326 return true;
7327 }
7328
7329 Diag(SS.getRange().getBegin(),
7330 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7331 << (NestedNameSpecifier*) SS.getScopeRep()
7332 << cast<CXXRecordDecl>(CurContext)
7333 << SS.getRange();
7334 return true;
7335 }
7336
7337 return false;
7338 }
7339
7340 // C++03 [namespace.udecl]p4:
7341 // A using-declaration used as a member-declaration shall refer
7342 // to a member of a base class of the class being defined [etc.].
7343
7344 // Salient point: SS doesn't have to name a base class as long as
7345 // lookup only finds members from base classes. Therefore we can
7346 // diagnose here only if we can prove that that can't happen,
7347 // i.e. if the class hierarchies provably don't intersect.
7348
7349 // TODO: it would be nice if "definitely valid" results were cached
7350 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7351 // need to be repeated.
7352
7353 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007354 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007355
7356 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7357 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7358 Data->Bases.insert(Base);
7359 return true;
7360 }
7361
7362 bool hasDependentBases(const CXXRecordDecl *Class) {
7363 return !Class->forallBases(collect, this);
7364 }
7365
7366 /// Returns true if the base is dependent or is one of the
7367 /// accumulated base classes.
7368 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7369 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7370 return !Data->Bases.count(Base);
7371 }
7372
7373 bool mightShareBases(const CXXRecordDecl *Class) {
7374 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7375 }
7376 };
7377
7378 UserData Data;
7379
7380 // Returns false if we find a dependent base.
7381 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7382 return false;
7383
7384 // Returns false if the class has a dependent base or if it or one
7385 // of its bases is present in the base set of the current context.
7386 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7387 return false;
7388
7389 Diag(SS.getRange().getBegin(),
7390 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7391 << (NestedNameSpecifier*) SS.getScopeRep()
7392 << cast<CXXRecordDecl>(CurContext)
7393 << SS.getRange();
7394
7395 return true;
John McCalled976492009-12-04 22:46:56 +00007396}
7397
Richard Smith162e1c12011-04-15 14:24:37 +00007398Decl *Sema::ActOnAliasDeclaration(Scope *S,
7399 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007400 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007401 SourceLocation UsingLoc,
7402 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007403 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007404 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007405 // Skip up to the relevant declaration scope.
7406 while (S->getFlags() & Scope::TemplateParamScope)
7407 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007408 assert((S->getFlags() & Scope::DeclScope) &&
7409 "got alias-declaration outside of declaration scope");
7410
7411 if (Type.isInvalid())
7412 return 0;
7413
7414 bool Invalid = false;
7415 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7416 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007417 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007418
7419 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7420 return 0;
7421
7422 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007423 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007424 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007425 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7426 TInfo->getTypeLoc().getBeginLoc());
7427 }
Richard Smith162e1c12011-04-15 14:24:37 +00007428
7429 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7430 LookupName(Previous, S);
7431
7432 // Warn about shadowing the name of a template parameter.
7433 if (Previous.isSingleResult() &&
7434 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007435 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007436 Previous.clear();
7437 }
7438
7439 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7440 "name in alias declaration must be an identifier");
7441 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7442 Name.StartLocation,
7443 Name.Identifier, TInfo);
7444
7445 NewTD->setAccess(AS);
7446
7447 if (Invalid)
7448 NewTD->setInvalidDecl();
7449
Richard Smith6b3d3e52013-02-20 19:22:51 +00007450 ProcessDeclAttributeList(S, NewTD, AttrList);
7451
Richard Smith3e4c6c42011-05-05 21:57:07 +00007452 CheckTypedefForVariablyModifiedType(S, NewTD);
7453 Invalid |= NewTD->isInvalidDecl();
7454
Richard Smith162e1c12011-04-15 14:24:37 +00007455 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007456
7457 NamedDecl *NewND;
7458 if (TemplateParamLists.size()) {
7459 TypeAliasTemplateDecl *OldDecl = 0;
7460 TemplateParameterList *OldTemplateParams = 0;
7461
7462 if (TemplateParamLists.size() != 1) {
7463 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007464 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7465 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007466 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007467 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007468
7469 // Only consider previous declarations in the same scope.
7470 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7471 /*ExplicitInstantiationOrSpecialization*/false);
7472 if (!Previous.empty()) {
7473 Redeclaration = true;
7474
7475 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7476 if (!OldDecl && !Invalid) {
7477 Diag(UsingLoc, diag::err_redefinition_different_kind)
7478 << Name.Identifier;
7479
7480 NamedDecl *OldD = Previous.getRepresentativeDecl();
7481 if (OldD->getLocation().isValid())
7482 Diag(OldD->getLocation(), diag::note_previous_definition);
7483
7484 Invalid = true;
7485 }
7486
7487 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7488 if (TemplateParameterListsAreEqual(TemplateParams,
7489 OldDecl->getTemplateParameters(),
7490 /*Complain=*/true,
7491 TPL_TemplateMatch))
7492 OldTemplateParams = OldDecl->getTemplateParameters();
7493 else
7494 Invalid = true;
7495
7496 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7497 if (!Invalid &&
7498 !Context.hasSameType(OldTD->getUnderlyingType(),
7499 NewTD->getUnderlyingType())) {
7500 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7501 // but we can't reasonably accept it.
7502 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7503 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7504 if (OldTD->getLocation().isValid())
7505 Diag(OldTD->getLocation(), diag::note_previous_definition);
7506 Invalid = true;
7507 }
7508 }
7509 }
7510
7511 // Merge any previous default template arguments into our parameters,
7512 // and check the parameter list.
7513 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7514 TPC_TypeAliasTemplate))
7515 return 0;
7516
7517 TypeAliasTemplateDecl *NewDecl =
7518 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7519 Name.Identifier, TemplateParams,
7520 NewTD);
7521
7522 NewDecl->setAccess(AS);
7523
7524 if (Invalid)
7525 NewDecl->setInvalidDecl();
7526 else if (OldDecl)
7527 NewDecl->setPreviousDeclaration(OldDecl);
7528
7529 NewND = NewDecl;
7530 } else {
7531 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7532 NewND = NewTD;
7533 }
Richard Smith162e1c12011-04-15 14:24:37 +00007534
7535 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007536 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007537
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007538 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007539 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007540}
7541
John McCalld226f652010-08-21 09:40:31 +00007542Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007543 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007544 SourceLocation AliasLoc,
7545 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007546 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007547 SourceLocation IdentLoc,
7548 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007549
Anders Carlsson81c85c42009-03-28 23:53:49 +00007550 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007551 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7552 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007553
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007554 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007555 NamedDecl *PrevDecl
7556 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7557 ForRedeclaration);
7558 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7559 PrevDecl = 0;
7560
7561 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007562 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007563 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007564 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007565 // FIXME: At some point, we'll want to create the (redundant)
7566 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007567 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007568 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007569 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007570 }
Mike Stump1eb44332009-09-09 15:08:12 +00007571
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007572 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7573 diag::err_redefinition_different_kind;
7574 Diag(AliasLoc, DiagID) << Alias;
7575 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007576 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007577 }
7578
John McCalla24dc2e2009-11-17 02:14:36 +00007579 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007580 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007581
John McCallf36e02d2009-10-09 21:13:30 +00007582 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007583 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007584 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007585 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007586 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007587 }
Mike Stump1eb44332009-09-09 15:08:12 +00007588
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007589 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007590 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007591 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007592 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007593
John McCall3dbd3d52010-02-16 06:53:13 +00007594 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007595 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007596}
7597
Sean Hunt001cad92011-05-10 00:49:42 +00007598Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007599Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7600 CXXMethodDecl *MD) {
7601 CXXRecordDecl *ClassDecl = MD->getParent();
7602
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007603 // C++ [except.spec]p14:
7604 // An implicitly declared special member function (Clause 12) shall have an
7605 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007606 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007607 if (ClassDecl->isInvalidDecl())
7608 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007609
Sebastian Redl60618fa2011-03-12 11:50:43 +00007610 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007611 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7612 BEnd = ClassDecl->bases_end();
7613 B != BEnd; ++B) {
7614 if (B->isVirtual()) // Handled below.
7615 continue;
7616
Douglas Gregor18274032010-07-03 00:47:00 +00007617 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7618 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007619 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7620 // If this is a deleted function, add it anyway. This might be conformant
7621 // with the standard. This might not. I'm not sure. It might not matter.
7622 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007623 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007624 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007625 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007626
7627 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007628 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7629 BEnd = ClassDecl->vbases_end();
7630 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007631 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7632 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007633 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7634 // If this is a deleted function, add it anyway. This might be conformant
7635 // with the standard. This might not. I'm not sure. It might not matter.
7636 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007637 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007638 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007639 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007640
7641 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007642 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7643 FEnd = ClassDecl->field_end();
7644 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007645 if (F->hasInClassInitializer()) {
7646 if (Expr *E = F->getInClassInitializer())
7647 ExceptSpec.CalledExpr(E);
7648 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007649 // DR1351:
7650 // If the brace-or-equal-initializer of a non-static data member
7651 // invokes a defaulted default constructor of its class or of an
7652 // enclosing class in a potentially evaluated subexpression, the
7653 // program is ill-formed.
7654 //
7655 // This resolution is unworkable: the exception specification of the
7656 // default constructor can be needed in an unevaluated context, in
7657 // particular, in the operand of a noexcept-expression, and we can be
7658 // unable to compute an exception specification for an enclosed class.
7659 //
7660 // We do not allow an in-class initializer to require the evaluation
7661 // of the exception specification for any in-class initializer whose
7662 // definition is not lexically complete.
7663 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007664 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007665 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007666 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7667 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7668 // If this is a deleted function, add it anyway. This might be conformant
7669 // with the standard. This might not. I'm not sure. It might not matter.
7670 // In particular, the problem is that this function never gets called. It
7671 // might just be ill-formed because this function attempts to refer to
7672 // a deleted function here.
7673 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007674 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007675 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007676 }
John McCalle23cf432010-12-14 08:05:40 +00007677
Sean Hunt001cad92011-05-10 00:49:42 +00007678 return ExceptSpec;
7679}
7680
Richard Smith07b0fdc2013-03-18 21:12:30 +00007681Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007682Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7683 CXXRecordDecl *ClassDecl = CD->getParent();
7684
7685 // C++ [except.spec]p14:
7686 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007687 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007688 if (ClassDecl->isInvalidDecl())
7689 return ExceptSpec;
7690
7691 // Inherited constructor.
7692 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7693 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7694 // FIXME: Copying or moving the parameters could add extra exceptions to the
7695 // set, as could the default arguments for the inherited constructor. This
7696 // will be addressed when we implement the resolution of core issue 1351.
7697 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7698
7699 // Direct base-class constructors.
7700 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7701 BEnd = ClassDecl->bases_end();
7702 B != BEnd; ++B) {
7703 if (B->isVirtual()) // Handled below.
7704 continue;
7705
7706 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7707 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7708 if (BaseClassDecl == InheritedDecl)
7709 continue;
7710 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7711 if (Constructor)
7712 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7713 }
7714 }
7715
7716 // Virtual base-class constructors.
7717 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7718 BEnd = ClassDecl->vbases_end();
7719 B != BEnd; ++B) {
7720 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7721 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7722 if (BaseClassDecl == InheritedDecl)
7723 continue;
7724 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7725 if (Constructor)
7726 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7727 }
7728 }
7729
7730 // Field constructors.
7731 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7732 FEnd = ClassDecl->field_end();
7733 F != FEnd; ++F) {
7734 if (F->hasInClassInitializer()) {
7735 if (Expr *E = F->getInClassInitializer())
7736 ExceptSpec.CalledExpr(E);
7737 else if (!F->isInvalidDecl())
7738 Diag(CD->getLocation(),
7739 diag::err_in_class_initializer_references_def_ctor) << CD;
7740 } else if (const RecordType *RecordTy
7741 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7742 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7743 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7744 if (Constructor)
7745 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7746 }
7747 }
7748
Richard Smith07b0fdc2013-03-18 21:12:30 +00007749 return ExceptSpec;
7750}
7751
Richard Smithafb49182012-11-29 01:34:07 +00007752namespace {
7753/// RAII object to register a special member as being currently declared.
7754struct DeclaringSpecialMember {
7755 Sema &S;
7756 Sema::SpecialMemberDecl D;
7757 bool WasAlreadyBeingDeclared;
7758
7759 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7760 : S(S), D(RD, CSM) {
7761 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7762 if (WasAlreadyBeingDeclared)
7763 // This almost never happens, but if it does, ensure that our cache
7764 // doesn't contain a stale result.
7765 S.SpecialMemberCache.clear();
7766
7767 // FIXME: Register a note to be produced if we encounter an error while
7768 // declaring the special member.
7769 }
7770 ~DeclaringSpecialMember() {
7771 if (!WasAlreadyBeingDeclared)
7772 S.SpecialMembersBeingDeclared.erase(D);
7773 }
7774
7775 /// \brief Are we already trying to declare this special member?
7776 bool isAlreadyBeingDeclared() const {
7777 return WasAlreadyBeingDeclared;
7778 }
7779};
7780}
7781
Sean Hunt001cad92011-05-10 00:49:42 +00007782CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7783 CXXRecordDecl *ClassDecl) {
7784 // C++ [class.ctor]p5:
7785 // A default constructor for a class X is a constructor of class X
7786 // that can be called without an argument. If there is no
7787 // user-declared constructor for class X, a default constructor is
7788 // implicitly declared. An implicitly-declared default constructor
7789 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007790 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007791 "Should not build implicit default constructor!");
7792
Richard Smithafb49182012-11-29 01:34:07 +00007793 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7794 if (DSM.isAlreadyBeingDeclared())
7795 return 0;
7796
Richard Smith7756afa2012-06-10 05:43:50 +00007797 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7798 CXXDefaultConstructor,
7799 false);
7800
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007801 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007802 CanQualType ClassType
7803 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007804 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007805 DeclarationName Name
7806 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007807 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007808 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007809 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007810 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007811 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007812 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007813 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007814 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007815
7816 // Build an exception specification pointing back at this constructor.
7817 FunctionProtoType::ExtProtoInfo EPI;
7818 EPI.ExceptionSpecType = EST_Unevaluated;
7819 EPI.ExceptionSpecDecl = DefaultCon;
Dmitri Gribenko55431692013-05-05 00:41:58 +00007820 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007821
Richard Smithbc2a35d2012-12-08 08:32:28 +00007822 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7823 // constructors is easy to compute.
7824 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7825
7826 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007827 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007828
Douglas Gregor18274032010-07-03 00:47:00 +00007829 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007830 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007831
Douglas Gregor23c94db2010-07-02 17:43:08 +00007832 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007833 PushOnScopeChains(DefaultCon, S, false);
7834 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007835
Douglas Gregor32df23e2010-07-01 22:02:46 +00007836 return DefaultCon;
7837}
7838
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007839void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7840 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007841 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007842 !Constructor->doesThisDeclarationHaveABody() &&
7843 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007844 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007845
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007846 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007847 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007848
Eli Friedman9a14db32012-10-18 20:14:08 +00007849 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007850 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007851 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007852 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007853 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007854 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007855 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007856 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007857 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007858
7859 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007860 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007861
7862 Constructor->setUsed();
7863 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007864
7865 if (ASTMutationListener *L = getASTMutationListener()) {
7866 L->CompletedImplicitDefinition(Constructor);
7867 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007868}
7869
Richard Smith7a614d82011-06-11 17:19:42 +00007870void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007871 // Check that any explicitly-defaulted methods have exception specifications
7872 // compatible with their implicit exception specifications.
7873 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007874}
7875
Richard Smith4841ca52013-04-10 05:48:59 +00007876namespace {
7877/// Information on inheriting constructors to declare.
7878class InheritingConstructorInfo {
7879public:
7880 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7881 : SemaRef(SemaRef), Derived(Derived) {
7882 // Mark the constructors that we already have in the derived class.
7883 //
7884 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7885 // unless there is a user-declared constructor with the same signature in
7886 // the class where the using-declaration appears.
7887 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7888 }
7889
7890 void inheritAll(CXXRecordDecl *RD) {
7891 visitAll(RD, &InheritingConstructorInfo::inherit);
7892 }
7893
7894private:
7895 /// Information about an inheriting constructor.
7896 struct InheritingConstructor {
7897 InheritingConstructor()
7898 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7899
7900 /// If \c true, a constructor with this signature is already declared
7901 /// in the derived class.
7902 bool DeclaredInDerived;
7903
7904 /// The constructor which is inherited.
7905 const CXXConstructorDecl *BaseCtor;
7906
7907 /// The derived constructor we declared.
7908 CXXConstructorDecl *DerivedCtor;
7909 };
7910
7911 /// Inheriting constructors with a given canonical type. There can be at
7912 /// most one such non-template constructor, and any number of templated
7913 /// constructors.
7914 struct InheritingConstructorsForType {
7915 InheritingConstructor NonTemplate;
7916 llvm::SmallVector<
7917 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7918
7919 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7920 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7921 TemplateParameterList *ParamList = FTD->getTemplateParameters();
7922 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7923 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7924 false, S.TPL_TemplateMatch))
7925 return Templates[I].second;
7926 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7927 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007928 }
Richard Smith4841ca52013-04-10 05:48:59 +00007929
7930 return NonTemplate;
7931 }
7932 };
7933
7934 /// Get or create the inheriting constructor record for a constructor.
7935 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7936 QualType CtorType) {
7937 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7938 .getEntry(SemaRef, Ctor);
7939 }
7940
7941 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7942
7943 /// Process all constructors for a class.
7944 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7945 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7946 CtorE = RD->ctor_end();
7947 CtorIt != CtorE; ++CtorIt)
7948 (this->*Callback)(*CtorIt);
7949 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7950 I(RD->decls_begin()), E(RD->decls_end());
7951 I != E; ++I) {
7952 const FunctionDecl *FD = (*I)->getTemplatedDecl();
7953 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7954 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007955 }
7956 }
Richard Smith4841ca52013-04-10 05:48:59 +00007957
7958 /// Note that a constructor (or constructor template) was declared in Derived.
7959 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7960 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7961 }
7962
7963 /// Inherit a single constructor.
7964 void inherit(const CXXConstructorDecl *Ctor) {
7965 const FunctionProtoType *CtorType =
7966 Ctor->getType()->castAs<FunctionProtoType>();
7967 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7968 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7969
7970 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7971
7972 // Core issue (no number yet): the ellipsis is always discarded.
7973 if (EPI.Variadic) {
7974 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7975 SemaRef.Diag(Ctor->getLocation(),
7976 diag::note_using_decl_constructor_ellipsis);
7977 EPI.Variadic = false;
7978 }
7979
7980 // Declare a constructor for each number of parameters.
7981 //
7982 // C++11 [class.inhctor]p1:
7983 // The candidate set of inherited constructors from the class X named in
7984 // the using-declaration consists of [... modulo defects ...] for each
7985 // constructor or constructor template of X, the set of constructors or
7986 // constructor templates that results from omitting any ellipsis parameter
7987 // specification and successively omitting parameters with a default
7988 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00007989 unsigned MinParams = minParamsToInherit(Ctor);
7990 unsigned Params = Ctor->getNumParams();
7991 if (Params >= MinParams) {
7992 do
7993 declareCtor(UsingLoc, Ctor,
7994 SemaRef.Context.getFunctionType(
7995 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7996 while (Params > MinParams &&
7997 Ctor->getParamDecl(--Params)->hasDefaultArg());
7998 }
Richard Smith4841ca52013-04-10 05:48:59 +00007999 }
8000
8001 /// Find the using-declaration which specified that we should inherit the
8002 /// constructors of \p Base.
8003 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8004 // No fancy lookup required; just look for the base constructor name
8005 // directly within the derived class.
8006 ASTContext &Context = SemaRef.Context;
8007 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8008 Context.getCanonicalType(Context.getRecordType(Base)));
8009 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8010 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8011 }
8012
8013 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8014 // C++11 [class.inhctor]p3:
8015 // [F]or each constructor template in the candidate set of inherited
8016 // constructors, a constructor template is implicitly declared
8017 if (Ctor->getDescribedFunctionTemplate())
8018 return 0;
8019
8020 // For each non-template constructor in the candidate set of inherited
8021 // constructors other than a constructor having no parameters or a
8022 // copy/move constructor having a single parameter, a constructor is
8023 // implicitly declared [...]
8024 if (Ctor->getNumParams() == 0)
8025 return 1;
8026 if (Ctor->isCopyOrMoveConstructor())
8027 return 2;
8028
8029 // Per discussion on core reflector, never inherit a constructor which
8030 // would become a default, copy, or move constructor of Derived either.
8031 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8032 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8033 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8034 }
8035
8036 /// Declare a single inheriting constructor, inheriting the specified
8037 /// constructor, with the given type.
8038 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8039 QualType DerivedType) {
8040 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8041
8042 // C++11 [class.inhctor]p3:
8043 // ... a constructor is implicitly declared with the same constructor
8044 // characteristics unless there is a user-declared constructor with
8045 // the same signature in the class where the using-declaration appears
8046 if (Entry.DeclaredInDerived)
8047 return;
8048
8049 // C++11 [class.inhctor]p7:
8050 // If two using-declarations declare inheriting constructors with the
8051 // same signature, the program is ill-formed
8052 if (Entry.DerivedCtor) {
8053 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8054 // Only diagnose this once per constructor.
8055 if (Entry.DerivedCtor->isInvalidDecl())
8056 return;
8057 Entry.DerivedCtor->setInvalidDecl();
8058
8059 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8060 SemaRef.Diag(BaseCtor->getLocation(),
8061 diag::note_using_decl_constructor_conflict_current_ctor);
8062 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8063 diag::note_using_decl_constructor_conflict_previous_ctor);
8064 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8065 diag::note_using_decl_constructor_conflict_previous_using);
8066 } else {
8067 // Core issue (no number): if the same inheriting constructor is
8068 // produced by multiple base class constructors from the same base
8069 // class, the inheriting constructor is defined as deleted.
8070 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8071 }
8072
8073 return;
8074 }
8075
8076 ASTContext &Context = SemaRef.Context;
8077 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8078 Context.getCanonicalType(Context.getRecordType(Derived)));
8079 DeclarationNameInfo NameInfo(Name, UsingLoc);
8080
8081 TemplateParameterList *TemplateParams = 0;
8082 if (const FunctionTemplateDecl *FTD =
8083 BaseCtor->getDescribedFunctionTemplate()) {
8084 TemplateParams = FTD->getTemplateParameters();
8085 // We're reusing template parameters from a different DeclContext. This
8086 // is questionable at best, but works out because the template depth in
8087 // both places is guaranteed to be 0.
8088 // FIXME: Rebuild the template parameters in the new context, and
8089 // transform the function type to refer to them.
8090 }
8091
8092 // Build type source info pointing at the using-declaration. This is
8093 // required by template instantiation.
8094 TypeSourceInfo *TInfo =
8095 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8096 FunctionProtoTypeLoc ProtoLoc =
8097 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8098
8099 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8100 Context, Derived, UsingLoc, NameInfo, DerivedType,
8101 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8102 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8103
8104 // Build an unevaluated exception specification for this constructor.
8105 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8106 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8107 EPI.ExceptionSpecType = EST_Unevaluated;
8108 EPI.ExceptionSpecDecl = DerivedCtor;
8109 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8110 FPT->getArgTypes(), EPI));
8111
8112 // Build the parameter declarations.
8113 SmallVector<ParmVarDecl *, 16> ParamDecls;
8114 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8115 TypeSourceInfo *TInfo =
8116 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8117 ParmVarDecl *PD = ParmVarDecl::Create(
8118 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8119 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8120 PD->setScopeInfo(0, I);
8121 PD->setImplicit();
8122 ParamDecls.push_back(PD);
8123 ProtoLoc.setArg(I, PD);
8124 }
8125
8126 // Set up the new constructor.
8127 DerivedCtor->setAccess(BaseCtor->getAccess());
8128 DerivedCtor->setParams(ParamDecls);
8129 DerivedCtor->setInheritedConstructor(BaseCtor);
8130 if (BaseCtor->isDeleted())
8131 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8132
8133 // If this is a constructor template, build the template declaration.
8134 if (TemplateParams) {
8135 FunctionTemplateDecl *DerivedTemplate =
8136 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8137 TemplateParams, DerivedCtor);
8138 DerivedTemplate->setAccess(BaseCtor->getAccess());
8139 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8140 Derived->addDecl(DerivedTemplate);
8141 } else {
8142 Derived->addDecl(DerivedCtor);
8143 }
8144
8145 Entry.BaseCtor = BaseCtor;
8146 Entry.DerivedCtor = DerivedCtor;
8147 }
8148
8149 Sema &SemaRef;
8150 CXXRecordDecl *Derived;
8151 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8152 MapType Map;
8153};
8154}
8155
8156void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8157 // Defer declaring the inheriting constructors until the class is
8158 // instantiated.
8159 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008160 return;
8161
Richard Smith4841ca52013-04-10 05:48:59 +00008162 // Find base classes from which we might inherit constructors.
8163 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8164 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8165 BaseE = ClassDecl->bases_end();
8166 BaseIt != BaseE; ++BaseIt)
8167 if (BaseIt->getInheritConstructors())
8168 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008169
Richard Smith4841ca52013-04-10 05:48:59 +00008170 // Go no further if we're not inheriting any constructors.
8171 if (InheritedBases.empty())
8172 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008173
Richard Smith4841ca52013-04-10 05:48:59 +00008174 // Declare the inherited constructors.
8175 InheritingConstructorInfo ICI(*this, ClassDecl);
8176 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8177 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008178}
8179
Richard Smith07b0fdc2013-03-18 21:12:30 +00008180void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8181 CXXConstructorDecl *Constructor) {
8182 CXXRecordDecl *ClassDecl = Constructor->getParent();
8183 assert(Constructor->getInheritedConstructor() &&
8184 !Constructor->doesThisDeclarationHaveABody() &&
8185 !Constructor->isDeleted());
8186
8187 SynthesizedFunctionScope Scope(*this, Constructor);
8188 DiagnosticErrorTrap Trap(Diags);
8189 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8190 Trap.hasErrorOccurred()) {
8191 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8192 << Context.getTagDeclType(ClassDecl);
8193 Constructor->setInvalidDecl();
8194 return;
8195 }
8196
8197 SourceLocation Loc = Constructor->getLocation();
8198 Constructor->setBody(new (Context) CompoundStmt(Loc));
8199
8200 Constructor->setUsed();
8201 MarkVTableUsed(CurrentLocation, ClassDecl);
8202
8203 if (ASTMutationListener *L = getASTMutationListener()) {
8204 L->CompletedImplicitDefinition(Constructor);
8205 }
8206}
8207
8208
Sean Huntcb45a0f2011-05-12 22:46:25 +00008209Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008210Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8211 CXXRecordDecl *ClassDecl = MD->getParent();
8212
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008213 // C++ [except.spec]p14:
8214 // An implicitly declared special member function (Clause 12) shall have
8215 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008216 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008217 if (ClassDecl->isInvalidDecl())
8218 return ExceptSpec;
8219
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008220 // Direct base-class destructors.
8221 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8222 BEnd = ClassDecl->bases_end();
8223 B != BEnd; ++B) {
8224 if (B->isVirtual()) // Handled below.
8225 continue;
8226
8227 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008228 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008229 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008230 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008231
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008232 // Virtual base-class destructors.
8233 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8234 BEnd = ClassDecl->vbases_end();
8235 B != BEnd; ++B) {
8236 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008237 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008238 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008239 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008240
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008241 // Field destructors.
8242 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8243 FEnd = ClassDecl->field_end();
8244 F != FEnd; ++F) {
8245 if (const RecordType *RecordTy
8246 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008247 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008248 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008249 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008250
Sean Huntcb45a0f2011-05-12 22:46:25 +00008251 return ExceptSpec;
8252}
8253
8254CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8255 // C++ [class.dtor]p2:
8256 // If a class has no user-declared destructor, a destructor is
8257 // declared implicitly. An implicitly-declared destructor is an
8258 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008259 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008260
Richard Smithafb49182012-11-29 01:34:07 +00008261 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8262 if (DSM.isAlreadyBeingDeclared())
8263 return 0;
8264
Douglas Gregor4923aa22010-07-02 20:37:36 +00008265 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008266 CanQualType ClassType
8267 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008268 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008269 DeclarationName Name
8270 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008271 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008272 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008273 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8274 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008275 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008276 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008277 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008278 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008279
8280 // Build an exception specification pointing back at this destructor.
8281 FunctionProtoType::ExtProtoInfo EPI;
8282 EPI.ExceptionSpecType = EST_Unevaluated;
8283 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008284 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008285
Richard Smithbc2a35d2012-12-08 08:32:28 +00008286 AddOverriddenMethods(ClassDecl, Destructor);
8287
8288 // We don't need to use SpecialMemberIsTrivial here; triviality for
8289 // destructors is easy to compute.
8290 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8291
8292 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008293 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008294
Douglas Gregor4923aa22010-07-02 20:37:36 +00008295 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008296 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008297
Douglas Gregor4923aa22010-07-02 20:37:36 +00008298 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008299 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008300 PushOnScopeChains(Destructor, S, false);
8301 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008302
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008303 return Destructor;
8304}
8305
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008306void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008307 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008308 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008309 !Destructor->doesThisDeclarationHaveABody() &&
8310 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008311 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008312 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008313 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008314
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008315 if (Destructor->isInvalidDecl())
8316 return;
8317
Eli Friedman9a14db32012-10-18 20:14:08 +00008318 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008319
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008320 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008321 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8322 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008323
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008324 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008325 Diag(CurrentLocation, diag::note_member_synthesized_at)
8326 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8327
8328 Destructor->setInvalidDecl();
8329 return;
8330 }
8331
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008332 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008333 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008334 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008335 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008336 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008337
8338 if (ASTMutationListener *L = getASTMutationListener()) {
8339 L->CompletedImplicitDefinition(Destructor);
8340 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008341}
8342
Richard Smitha4156b82012-04-21 18:42:51 +00008343/// \brief Perform any semantic analysis which needs to be delayed until all
8344/// pending class member declarations have been parsed.
8345void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008346 // If the context is an invalid C++ class, just suppress these checks.
8347 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8348 if (Record->isInvalidDecl()) {
8349 DelayedDestructorExceptionSpecChecks.clear();
8350 return;
8351 }
8352 }
8353
Richard Smitha4156b82012-04-21 18:42:51 +00008354 // Perform any deferred checking of exception specifications for virtual
8355 // destructors.
8356 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8357 i != e; ++i) {
8358 const CXXDestructorDecl *Dtor =
8359 DelayedDestructorExceptionSpecChecks[i].first;
8360 assert(!Dtor->getParent()->isDependentType() &&
8361 "Should not ever add destructors of templates into the list.");
8362 CheckOverridingFunctionExceptionSpec(Dtor,
8363 DelayedDestructorExceptionSpecChecks[i].second);
8364 }
8365 DelayedDestructorExceptionSpecChecks.clear();
8366}
8367
Richard Smithb9d0b762012-07-27 04:22:15 +00008368void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8369 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008370 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008371 "adjusting dtor exception specs was introduced in c++11");
8372
Sebastian Redl0ee33912011-05-19 05:13:44 +00008373 // C++11 [class.dtor]p3:
8374 // A declaration of a destructor that does not have an exception-
8375 // specification is implicitly considered to have the same exception-
8376 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008377 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008378 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008379 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008380 return;
8381
Chandler Carruth3f224b22011-09-20 04:55:26 +00008382 // Replace the destructor's type, building off the existing one. Fortunately,
8383 // the only thing of interest in the destructor type is its extended info.
8384 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008385 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8386 EPI.ExceptionSpecType = EST_Unevaluated;
8387 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008388 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008389
Sebastian Redl0ee33912011-05-19 05:13:44 +00008390 // FIXME: If the destructor has a body that could throw, and the newly created
8391 // spec doesn't allow exceptions, we should emit a warning, because this
8392 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008393 // However, we don't have a body or an exception specification yet, so it
8394 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008395}
8396
Richard Smith8c889532012-11-14 00:50:40 +00008397/// When generating a defaulted copy or move assignment operator, if a field
8398/// should be copied with __builtin_memcpy rather than via explicit assignments,
8399/// do so. This optimization only applies for arrays of scalars, and for arrays
8400/// of class type where the selected copy/move-assignment operator is trivial.
8401static StmtResult
8402buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8403 Expr *To, Expr *From) {
8404 // Compute the size of the memory buffer to be copied.
8405 QualType SizeType = S.Context.getSizeType();
8406 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8407 S.Context.getTypeSizeInChars(T).getQuantity());
8408
8409 // Take the address of the field references for "from" and "to". We
8410 // directly construct UnaryOperators here because semantic analysis
8411 // does not permit us to take the address of an xvalue.
8412 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8413 S.Context.getPointerType(From->getType()),
8414 VK_RValue, OK_Ordinary, Loc);
8415 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8416 S.Context.getPointerType(To->getType()),
8417 VK_RValue, OK_Ordinary, Loc);
8418
8419 const Type *E = T->getBaseElementTypeUnsafe();
8420 bool NeedsCollectableMemCpy =
8421 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8422
8423 // Create a reference to the __builtin_objc_memmove_collectable function
8424 StringRef MemCpyName = NeedsCollectableMemCpy ?
8425 "__builtin_objc_memmove_collectable" :
8426 "__builtin_memcpy";
8427 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8428 Sema::LookupOrdinaryName);
8429 S.LookupName(R, S.TUScope, true);
8430
8431 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8432 if (!MemCpy)
8433 // Something went horribly wrong earlier, and we will have complained
8434 // about it.
8435 return StmtError();
8436
8437 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8438 VK_RValue, Loc, 0);
8439 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8440
8441 Expr *CallArgs[] = {
8442 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8443 };
8444 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8445 Loc, CallArgs, Loc);
8446
8447 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8448 return S.Owned(Call.takeAs<Stmt>());
8449}
8450
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008451/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008452/// \c To.
8453///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008454/// This routine is used to copy/move the members of a class with an
8455/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008456/// copied are arrays, this routine builds for loops to copy them.
8457///
8458/// \param S The Sema object used for type-checking.
8459///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008460/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008461///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008462/// \param T The type of the expressions being copied/moved. Both expressions
8463/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008464///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008465/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008466///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008467/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008468///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008469/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008470/// Otherwise, it's a non-static member subobject.
8471///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008472/// \param Copying Whether we're copying or moving.
8473///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008474/// \param Depth Internal parameter recording the depth of the recursion.
8475///
Richard Smith8c889532012-11-14 00:50:40 +00008476/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8477/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008478static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008479buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8480 Expr *To, Expr *From,
8481 bool CopyingBaseSubobject, bool Copying,
8482 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008483 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008484 // Each subobject is assigned in the manner appropriate to its type:
8485 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008486 // - if the subobject is of class type, as if by a call to operator= with
8487 // the subobject as the object expression and the corresponding
8488 // subobject of x as a single function argument (as if by explicit
8489 // qualification; that is, ignoring any possible virtual overriding
8490 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008491 //
8492 // C++03 [class.copy]p13:
8493 // - if the subobject is of class type, the copy assignment operator for
8494 // the class is used (as if by explicit qualification; that is,
8495 // ignoring any possible virtual overriding functions in more derived
8496 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008497 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8498 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008499
Douglas Gregor06a9f362010-05-01 20:49:11 +00008500 // Look for operator=.
8501 DeclarationName Name
8502 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8503 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8504 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008505
Richard Smith044c8aa2012-11-13 00:54:12 +00008506 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8507 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008508 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008509 LookupResult::Filter F = OpLookup.makeFilter();
8510 while (F.hasNext()) {
8511 NamedDecl *D = F.next();
8512 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8513 if (Method->isCopyAssignmentOperator() ||
8514 (!Copying && Method->isMoveAssignmentOperator()))
8515 continue;
8516
8517 F.erase();
8518 }
8519 F.done();
John McCallb0207482010-03-16 06:11:48 +00008520 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008521
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008522 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008523 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008524 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008525 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008526 // ambiguities), we need to cast "this" to that subobject type; to
8527 // ensure that we don't go through the virtual call mechanism, we need
8528 // to qualify the operator= name with the base class (see below). However,
8529 // this means that if the base class has a protected copy assignment
8530 // operator, the protected member access check will fail. So, we
8531 // rewrite "protected" access to "public" access in this case, since we
8532 // know by construction that we're calling from a derived class.
8533 if (CopyingBaseSubobject) {
8534 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8535 L != LEnd; ++L) {
8536 if (L.getAccess() == AS_protected)
8537 L.setAccess(AS_public);
8538 }
8539 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008540
Douglas Gregor06a9f362010-05-01 20:49:11 +00008541 // Create the nested-name-specifier that will be used to qualify the
8542 // reference to operator=; this is required to suppress the virtual
8543 // call mechanism.
8544 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008545 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008546 SS.MakeTrivial(S.Context,
8547 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008548 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008549 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008550
Douglas Gregor06a9f362010-05-01 20:49:11 +00008551 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008552 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008553 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008554 /*TemplateKWLoc=*/SourceLocation(),
8555 /*FirstQualifierInScope=*/0,
8556 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008557 /*TemplateArgs=*/0,
8558 /*SuppressQualifierCheck=*/true);
8559 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008560 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008561
Douglas Gregor06a9f362010-05-01 20:49:11 +00008562 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008563
Richard Smith044c8aa2012-11-13 00:54:12 +00008564 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008565 OpEqualRef.takeAs<Expr>(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00008566 Loc, From, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008567 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008568 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008569
Richard Smith8c889532012-11-14 00:50:40 +00008570 // If we built a call to a trivial 'operator=' while copying an array,
8571 // bail out. We'll replace the whole shebang with a memcpy.
8572 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8573 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8574 return StmtResult((Stmt*)0);
8575
Richard Smith044c8aa2012-11-13 00:54:12 +00008576 // Convert to an expression-statement, and clean up any produced
8577 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008578 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008579 }
John McCallb0207482010-03-16 06:11:48 +00008580
Richard Smith044c8aa2012-11-13 00:54:12 +00008581 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008582 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008583 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008584 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008585 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008586 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008587 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008588 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008589 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008590
8591 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008592 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008593
Douglas Gregor06a9f362010-05-01 20:49:11 +00008594 // Construct a loop over the array bounds, e.g.,
8595 //
8596 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8597 //
8598 // that will copy each of the array elements.
8599 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008600
Douglas Gregor06a9f362010-05-01 20:49:11 +00008601 // Create the iteration variable.
8602 IdentifierInfo *IterationVarName = 0;
8603 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008604 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008605 llvm::raw_svector_ostream OS(Str);
8606 OS << "__i" << Depth;
8607 IterationVarName = &S.Context.Idents.get(OS.str());
8608 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008609 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008610 IterationVarName, SizeType,
8611 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008612 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008613
Douglas Gregor06a9f362010-05-01 20:49:11 +00008614 // Initialize the iteration variable to zero.
8615 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008616 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008617
8618 // Create a reference to the iteration variable; we'll use this several
8619 // times throughout.
8620 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008621 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008622 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008623 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8624 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8625
Douglas Gregor06a9f362010-05-01 20:49:11 +00008626 // Create the DeclStmt that holds the iteration variable.
8627 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008628
Douglas Gregor06a9f362010-05-01 20:49:11 +00008629 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008630 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008631 IterationVarRefRVal,
8632 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008633 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008634 IterationVarRefRVal,
8635 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008636 if (!Copying) // Cast to rvalue
8637 From = CastForMoving(S, From);
8638
8639 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008640 StmtResult Copy =
8641 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8642 To, From, CopyingBaseSubobject,
8643 Copying, Depth + 1);
8644 // Bail out if copying fails or if we determined that we should use memcpy.
8645 if (Copy.isInvalid() || !Copy.get())
8646 return Copy;
8647
8648 // Create the comparison against the array bound.
8649 llvm::APInt Upper
8650 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8651 Expr *Comparison
8652 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8653 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8654 BO_NE, S.Context.BoolTy,
8655 VK_RValue, OK_Ordinary, Loc, false);
8656
8657 // Create the pre-increment of the iteration variable.
8658 Expr *Increment
8659 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8660 VK_LValue, OK_Ordinary, Loc);
8661
Douglas Gregor06a9f362010-05-01 20:49:11 +00008662 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008663 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008664 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008665 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008666 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008667}
8668
Richard Smith8c889532012-11-14 00:50:40 +00008669static StmtResult
8670buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8671 Expr *To, Expr *From,
8672 bool CopyingBaseSubobject, bool Copying) {
8673 // Maybe we should use a memcpy?
8674 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8675 T.isTriviallyCopyableType(S.Context))
8676 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8677
8678 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8679 CopyingBaseSubobject,
8680 Copying, 0));
8681
8682 // If we ended up picking a trivial assignment operator for an array of a
8683 // non-trivially-copyable class type, just emit a memcpy.
8684 if (!Result.isInvalid() && !Result.get())
8685 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8686
8687 return Result;
8688}
8689
Richard Smithb9d0b762012-07-27 04:22:15 +00008690Sema::ImplicitExceptionSpecification
8691Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8692 CXXRecordDecl *ClassDecl = MD->getParent();
8693
8694 ImplicitExceptionSpecification ExceptSpec(*this);
8695 if (ClassDecl->isInvalidDecl())
8696 return ExceptSpec;
8697
8698 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8699 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8700 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8701
Douglas Gregorb87786f2010-07-01 17:48:08 +00008702 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008703 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008704 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008705
8706 // It is unspecified whether or not an implicit copy assignment operator
8707 // attempts to deduplicate calls to assignment operators of virtual bases are
8708 // made. As such, this exception specification is effectively unspecified.
8709 // Based on a similar decision made for constness in C++0x, we're erring on
8710 // the side of assuming such calls to be made regardless of whether they
8711 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008712 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8713 BaseEnd = ClassDecl->bases_end();
8714 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008715 if (Base->isVirtual())
8716 continue;
8717
Douglas Gregora376d102010-07-02 21:50:04 +00008718 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008719 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008720 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8721 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008722 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008723 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008724
8725 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8726 BaseEnd = ClassDecl->vbases_end();
8727 Base != BaseEnd; ++Base) {
8728 CXXRecordDecl *BaseClassDecl
8729 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8730 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8731 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008732 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008733 }
8734
Douglas Gregorb87786f2010-07-01 17:48:08 +00008735 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8736 FieldEnd = ClassDecl->field_end();
8737 Field != FieldEnd;
8738 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008739 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008740 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8741 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008742 LookupCopyingAssignment(FieldClassDecl,
8743 ArgQuals | FieldType.getCVRQualifiers(),
8744 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008745 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008746 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008747 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008748
Richard Smithb9d0b762012-07-27 04:22:15 +00008749 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008750}
8751
8752CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8753 // Note: The following rules are largely analoguous to the copy
8754 // constructor rules. Note that virtual bases are not taken into account
8755 // for determining the argument type of the operator. Note also that
8756 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008757 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008758
Richard Smithafb49182012-11-29 01:34:07 +00008759 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8760 if (DSM.isAlreadyBeingDeclared())
8761 return 0;
8762
Sean Hunt30de05c2011-05-14 05:23:20 +00008763 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8764 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00008765 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
8766 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00008767 ArgType = ArgType.withConst();
8768 ArgType = Context.getLValueReferenceType(ArgType);
8769
Richard Smitha8942d72013-05-07 03:19:20 +00008770 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8771 CXXCopyAssignment,
8772 Const);
8773
Douglas Gregord3c35902010-07-01 16:36:15 +00008774 // An implicitly-declared copy assignment operator is an inline public
8775 // member of its class.
8776 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008777 SourceLocation ClassLoc = ClassDecl->getLocation();
8778 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00008779 CXXMethodDecl *CopyAssignment =
8780 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8781 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
8782 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008783 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008784 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008785 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008786
8787 // Build an exception specification pointing back at this member.
8788 FunctionProtoType::ExtProtoInfo EPI;
8789 EPI.ExceptionSpecType = EST_Unevaluated;
8790 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008791 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008792
Douglas Gregord3c35902010-07-01 16:36:15 +00008793 // Add the parameter to the operator.
8794 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008795 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008796 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008797 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008798 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008799
Richard Smithbc2a35d2012-12-08 08:32:28 +00008800 AddOverriddenMethods(ClassDecl, CopyAssignment);
8801
8802 CopyAssignment->setTrivial(
8803 ClassDecl->needsOverloadResolutionForCopyAssignment()
8804 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8805 : ClassDecl->hasTrivialCopyAssignment());
8806
Richard Smitha8942d72013-05-07 03:19:20 +00008807 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00008808 // .... If the class definition does not explicitly declare a copy
8809 // assignment operator, there is no user-declared move constructor, and
8810 // there is no user-declared move assignment operator, a copy assignment
8811 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008812 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008813 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008814
Richard Smithbc2a35d2012-12-08 08:32:28 +00008815 // Note that we have added this copy-assignment operator.
8816 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8817
8818 if (Scope *S = getScopeForContext(ClassDecl))
8819 PushOnScopeChains(CopyAssignment, S, false);
8820 ClassDecl->addDecl(CopyAssignment);
8821
Douglas Gregord3c35902010-07-01 16:36:15 +00008822 return CopyAssignment;
8823}
8824
Douglas Gregor06a9f362010-05-01 20:49:11 +00008825void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8826 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008827 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008828 CopyAssignOperator->isOverloadedOperator() &&
8829 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008830 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8831 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008832 "DefineImplicitCopyAssignment called for wrong function");
8833
8834 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8835
8836 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8837 CopyAssignOperator->setInvalidDecl();
8838 return;
8839 }
8840
8841 CopyAssignOperator->setUsed();
8842
Eli Friedman9a14db32012-10-18 20:14:08 +00008843 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008844 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008845
8846 // C++0x [class.copy]p30:
8847 // The implicitly-defined or explicitly-defaulted copy assignment operator
8848 // for a non-union class X performs memberwise copy assignment of its
8849 // subobjects. The direct base classes of X are assigned first, in the
8850 // order of their declaration in the base-specifier-list, and then the
8851 // immediate non-static data members of X are assigned, in the order in
8852 // which they were declared in the class definition.
8853
8854 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008855 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008856
8857 // The parameter for the "other" object, which we are copying from.
8858 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8859 Qualifiers OtherQuals = Other->getType().getQualifiers();
8860 QualType OtherRefType = Other->getType();
8861 if (const LValueReferenceType *OtherRef
8862 = OtherRefType->getAs<LValueReferenceType>()) {
8863 OtherRefType = OtherRef->getPointeeType();
8864 OtherQuals = OtherRefType.getQualifiers();
8865 }
8866
8867 // Our location for everything implicitly-generated.
8868 SourceLocation Loc = CopyAssignOperator->getLocation();
8869
8870 // Construct a reference to the "other" object. We'll be using this
8871 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008872 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008873 assert(OtherRef && "Reference to parameter cannot fail!");
8874
8875 // Construct the "this" pointer. We'll be using this throughout the generated
8876 // ASTs.
8877 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8878 assert(This && "Reference to this cannot fail!");
8879
8880 // Assign base classes.
8881 bool Invalid = false;
8882 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8883 E = ClassDecl->bases_end(); Base != E; ++Base) {
8884 // Form the assignment:
8885 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8886 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008887 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008888 Invalid = true;
8889 continue;
8890 }
8891
John McCallf871d0c2010-08-07 06:22:56 +00008892 CXXCastPath BasePath;
8893 BasePath.push_back(Base);
8894
Douglas Gregor06a9f362010-05-01 20:49:11 +00008895 // Construct the "from" expression, which is an implicit cast to the
8896 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008897 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008898 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8899 CK_UncheckedDerivedToBase,
8900 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008901
8902 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008903 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008904
8905 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008906 To = ImpCastExprToType(To.take(),
8907 Context.getCVRQualifiedType(BaseType,
8908 CopyAssignOperator->getTypeQualifiers()),
8909 CK_UncheckedDerivedToBase,
8910 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008911
8912 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008913 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008914 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008915 /*CopyingBaseSubobject=*/true,
8916 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008917 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008918 Diag(CurrentLocation, diag::note_member_synthesized_at)
8919 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8920 CopyAssignOperator->setInvalidDecl();
8921 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008922 }
8923
8924 // Success! Record the copy.
8925 Statements.push_back(Copy.takeAs<Expr>());
8926 }
8927
Douglas Gregor06a9f362010-05-01 20:49:11 +00008928 // Assign non-static members.
8929 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8930 FieldEnd = ClassDecl->field_end();
8931 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008932 if (Field->isUnnamedBitfield())
8933 continue;
8934
Douglas Gregor06a9f362010-05-01 20:49:11 +00008935 // Check for members of reference type; we can't copy those.
8936 if (Field->getType()->isReferenceType()) {
8937 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8938 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8939 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008940 Diag(CurrentLocation, diag::note_member_synthesized_at)
8941 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008942 Invalid = true;
8943 continue;
8944 }
8945
8946 // Check for members of const-qualified, non-class type.
8947 QualType BaseType = Context.getBaseElementType(Field->getType());
8948 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8949 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8950 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8951 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008952 Diag(CurrentLocation, diag::note_member_synthesized_at)
8953 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008954 Invalid = true;
8955 continue;
8956 }
John McCallb77115d2011-06-17 00:18:42 +00008957
8958 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008959 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8960 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008961
8962 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008963 if (FieldType->isIncompleteArrayType()) {
8964 assert(ClassDecl->hasFlexibleArrayMember() &&
8965 "Incomplete array type is not valid");
8966 continue;
8967 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008968
8969 // Build references to the field in the object we're copying from and to.
8970 CXXScopeSpec SS; // Intentionally empty
8971 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8972 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008973 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008974 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008975 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008976 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008977 SS, SourceLocation(), 0,
8978 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008979 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008980 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008981 SS, SourceLocation(), 0,
8982 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008983 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8984 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008985
Douglas Gregor06a9f362010-05-01 20:49:11 +00008986 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008987 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008988 To.get(), From.get(),
8989 /*CopyingBaseSubobject=*/false,
8990 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008991 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008992 Diag(CurrentLocation, diag::note_member_synthesized_at)
8993 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8994 CopyAssignOperator->setInvalidDecl();
8995 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008996 }
8997
8998 // Success! Record the copy.
8999 Statements.push_back(Copy.takeAs<Stmt>());
9000 }
9001
9002 if (!Invalid) {
9003 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00009004 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009005
John McCall60d7b3a2010-08-24 06:29:42 +00009006 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009007 if (Return.isInvalid())
9008 Invalid = true;
9009 else {
9010 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009011
9012 if (Trap.hasErrorOccurred()) {
9013 Diag(CurrentLocation, diag::note_member_synthesized_at)
9014 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9015 Invalid = true;
9016 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009017 }
9018 }
9019
9020 if (Invalid) {
9021 CopyAssignOperator->setInvalidDecl();
9022 return;
9023 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009024
9025 StmtResult Body;
9026 {
9027 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009028 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009029 /*isStmtExpr=*/false);
9030 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9031 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009032 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009033
9034 if (ASTMutationListener *L = getASTMutationListener()) {
9035 L->CompletedImplicitDefinition(CopyAssignOperator);
9036 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009037}
9038
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009039Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009040Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9041 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009042
Richard Smithb9d0b762012-07-27 04:22:15 +00009043 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009044 if (ClassDecl->isInvalidDecl())
9045 return ExceptSpec;
9046
9047 // C++0x [except.spec]p14:
9048 // An implicitly declared special member function (Clause 12) shall have an
9049 // exception-specification. [...]
9050
9051 // It is unspecified whether or not an implicit move assignment operator
9052 // attempts to deduplicate calls to assignment operators of virtual bases are
9053 // made. As such, this exception specification is effectively unspecified.
9054 // Based on a similar decision made for constness in C++0x, we're erring on
9055 // the side of assuming such calls to be made regardless of whether they
9056 // actually happen.
9057 // Note that a move constructor is not implicitly declared when there are
9058 // virtual bases, but it can still be user-declared and explicitly defaulted.
9059 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9060 BaseEnd = ClassDecl->bases_end();
9061 Base != BaseEnd; ++Base) {
9062 if (Base->isVirtual())
9063 continue;
9064
9065 CXXRecordDecl *BaseClassDecl
9066 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9067 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009068 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009069 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009070 }
9071
9072 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9073 BaseEnd = ClassDecl->vbases_end();
9074 Base != BaseEnd; ++Base) {
9075 CXXRecordDecl *BaseClassDecl
9076 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9077 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009078 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009079 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009080 }
9081
9082 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9083 FieldEnd = ClassDecl->field_end();
9084 Field != FieldEnd;
9085 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009086 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009087 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009088 if (CXXMethodDecl *MoveAssign =
9089 LookupMovingAssignment(FieldClassDecl,
9090 FieldType.getCVRQualifiers(),
9091 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009092 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009093 }
9094 }
9095
9096 return ExceptSpec;
9097}
9098
Richard Smith1c931be2012-04-02 18:40:40 +00009099/// Determine whether the class type has any direct or indirect virtual base
9100/// classes which have a non-trivial move assignment operator.
9101static bool
9102hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9103 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9104 BaseEnd = ClassDecl->vbases_end();
9105 Base != BaseEnd; ++Base) {
9106 CXXRecordDecl *BaseClass =
9107 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9108
9109 // Try to declare the move assignment. If it would be deleted, then the
9110 // class does not have a non-trivial move assignment.
9111 if (BaseClass->needsImplicitMoveAssignment())
9112 S.DeclareImplicitMoveAssignment(BaseClass);
9113
Richard Smith426391c2012-11-16 00:53:38 +00009114 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009115 return true;
9116 }
9117
9118 return false;
9119}
9120
9121/// Determine whether the given type either has a move constructor or is
9122/// trivially copyable.
9123static bool
9124hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9125 Type = S.Context.getBaseElementType(Type);
9126
9127 // FIXME: Technically, non-trivially-copyable non-class types, such as
9128 // reference types, are supposed to return false here, but that appears
9129 // to be a standard defect.
9130 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009131 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009132 return true;
9133
9134 if (Type.isTriviallyCopyableType(S.Context))
9135 return true;
9136
9137 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009138 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9139 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009140 if (ClassDecl->needsImplicitMoveConstructor())
9141 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009142 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009143 }
9144
Richard Smithe5411b72012-12-01 02:35:44 +00009145 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9146 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009147 if (ClassDecl->needsImplicitMoveAssignment())
9148 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009149 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009150}
9151
9152/// Determine whether all non-static data members and direct or virtual bases
9153/// of class \p ClassDecl have either a move operation, or are trivially
9154/// copyable.
9155static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9156 bool IsConstructor) {
9157 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9158 BaseEnd = ClassDecl->bases_end();
9159 Base != BaseEnd; ++Base) {
9160 if (Base->isVirtual())
9161 continue;
9162
9163 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9164 return false;
9165 }
9166
9167 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9168 BaseEnd = ClassDecl->vbases_end();
9169 Base != BaseEnd; ++Base) {
9170 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9171 return false;
9172 }
9173
9174 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9175 FieldEnd = ClassDecl->field_end();
9176 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009177 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009178 return false;
9179 }
9180
9181 return true;
9182}
9183
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009184CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009185 // C++11 [class.copy]p20:
9186 // If the definition of a class X does not explicitly declare a move
9187 // assignment operator, one will be implicitly declared as defaulted
9188 // if and only if:
9189 //
9190 // - [first 4 bullets]
9191 assert(ClassDecl->needsImplicitMoveAssignment());
9192
Richard Smithafb49182012-11-29 01:34:07 +00009193 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9194 if (DSM.isAlreadyBeingDeclared())
9195 return 0;
9196
Richard Smith1c931be2012-04-02 18:40:40 +00009197 // [Checked after we build the declaration]
9198 // - the move assignment operator would not be implicitly defined as
9199 // deleted,
9200
9201 // [DR1402]:
9202 // - X has no direct or indirect virtual base class with a non-trivial
9203 // move assignment operator, and
9204 // - each of X's non-static data members and direct or virtual base classes
9205 // has a type that either has a move assignment operator or is trivially
9206 // copyable.
9207 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9208 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9209 ClassDecl->setFailedImplicitMoveAssignment();
9210 return 0;
9211 }
9212
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009213 // Note: The following rules are largely analoguous to the move
9214 // constructor rules.
9215
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009216 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9217 QualType RetType = Context.getLValueReferenceType(ArgType);
9218 ArgType = Context.getRValueReferenceType(ArgType);
9219
Richard Smitha8942d72013-05-07 03:19:20 +00009220 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9221 CXXMoveAssignment,
9222 false);
9223
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009224 // An implicitly-declared move assignment operator is an inline public
9225 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009226 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9227 SourceLocation ClassLoc = ClassDecl->getLocation();
9228 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009229 CXXMethodDecl *MoveAssignment =
9230 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9231 /*TInfo=*/0, /*StorageClass=*/SC_None,
9232 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009233 MoveAssignment->setAccess(AS_public);
9234 MoveAssignment->setDefaulted();
9235 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009236
Richard Smithb9d0b762012-07-27 04:22:15 +00009237 // Build an exception specification pointing back at this member.
9238 FunctionProtoType::ExtProtoInfo EPI;
9239 EPI.ExceptionSpecType = EST_Unevaluated;
9240 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009241 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009242
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009243 // Add the parameter to the operator.
9244 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9245 ClassLoc, ClassLoc, /*Id=*/0,
9246 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009247 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009248 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009249
Richard Smithbc2a35d2012-12-08 08:32:28 +00009250 AddOverriddenMethods(ClassDecl, MoveAssignment);
9251
9252 MoveAssignment->setTrivial(
9253 ClassDecl->needsOverloadResolutionForMoveAssignment()
9254 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9255 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009256
9257 // C++0x [class.copy]p9:
9258 // If the definition of a class X does not explicitly declare a move
9259 // assignment operator, one will be implicitly declared as defaulted if and
9260 // only if:
9261 // [...]
9262 // - the move assignment operator would not be implicitly defined as
9263 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009264 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009265 // Cache this result so that we don't try to generate this over and over
9266 // on every lookup, leaking memory and wasting time.
9267 ClassDecl->setFailedImplicitMoveAssignment();
9268 return 0;
9269 }
9270
Richard Smithbc2a35d2012-12-08 08:32:28 +00009271 // Note that we have added this copy-assignment operator.
9272 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9273
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009274 if (Scope *S = getScopeForContext(ClassDecl))
9275 PushOnScopeChains(MoveAssignment, S, false);
9276 ClassDecl->addDecl(MoveAssignment);
9277
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009278 return MoveAssignment;
9279}
9280
9281void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9282 CXXMethodDecl *MoveAssignOperator) {
9283 assert((MoveAssignOperator->isDefaulted() &&
9284 MoveAssignOperator->isOverloadedOperator() &&
9285 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009286 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9287 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009288 "DefineImplicitMoveAssignment called for wrong function");
9289
9290 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9291
9292 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9293 MoveAssignOperator->setInvalidDecl();
9294 return;
9295 }
9296
9297 MoveAssignOperator->setUsed();
9298
Eli Friedman9a14db32012-10-18 20:14:08 +00009299 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009300 DiagnosticErrorTrap Trap(Diags);
9301
9302 // C++0x [class.copy]p28:
9303 // The implicitly-defined or move assignment operator for a non-union class
9304 // X performs memberwise move assignment of its subobjects. The direct base
9305 // classes of X are assigned first, in the order of their declaration in the
9306 // base-specifier-list, and then the immediate non-static data members of X
9307 // are assigned, in the order in which they were declared in the class
9308 // definition.
9309
9310 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009311 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009312
9313 // The parameter for the "other" object, which we are move from.
9314 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9315 QualType OtherRefType = Other->getType()->
9316 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009317 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009318 "Bad argument type of defaulted move assignment");
9319
9320 // Our location for everything implicitly-generated.
9321 SourceLocation Loc = MoveAssignOperator->getLocation();
9322
9323 // Construct a reference to the "other" object. We'll be using this
9324 // throughout the generated ASTs.
9325 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9326 assert(OtherRef && "Reference to parameter cannot fail!");
9327 // Cast to rvalue.
9328 OtherRef = CastForMoving(*this, OtherRef);
9329
9330 // Construct the "this" pointer. We'll be using this throughout the generated
9331 // ASTs.
9332 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9333 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009334
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009335 // Assign base classes.
9336 bool Invalid = false;
9337 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9338 E = ClassDecl->bases_end(); Base != E; ++Base) {
9339 // Form the assignment:
9340 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9341 QualType BaseType = Base->getType().getUnqualifiedType();
9342 if (!BaseType->isRecordType()) {
9343 Invalid = true;
9344 continue;
9345 }
9346
9347 CXXCastPath BasePath;
9348 BasePath.push_back(Base);
9349
9350 // Construct the "from" expression, which is an implicit cast to the
9351 // appropriately-qualified base type.
9352 Expr *From = OtherRef;
9353 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009354 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009355
9356 // Dereference "this".
9357 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9358
9359 // Implicitly cast "this" to the appropriately-qualified base type.
9360 To = ImpCastExprToType(To.take(),
9361 Context.getCVRQualifiedType(BaseType,
9362 MoveAssignOperator->getTypeQualifiers()),
9363 CK_UncheckedDerivedToBase,
9364 VK_LValue, &BasePath);
9365
9366 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009367 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009368 To.get(), From,
9369 /*CopyingBaseSubobject=*/true,
9370 /*Copying=*/false);
9371 if (Move.isInvalid()) {
9372 Diag(CurrentLocation, diag::note_member_synthesized_at)
9373 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9374 MoveAssignOperator->setInvalidDecl();
9375 return;
9376 }
9377
9378 // Success! Record the move.
9379 Statements.push_back(Move.takeAs<Expr>());
9380 }
9381
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009382 // Assign non-static members.
9383 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9384 FieldEnd = ClassDecl->field_end();
9385 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009386 if (Field->isUnnamedBitfield())
9387 continue;
9388
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009389 // Check for members of reference type; we can't move those.
9390 if (Field->getType()->isReferenceType()) {
9391 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9392 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9393 Diag(Field->getLocation(), diag::note_declared_at);
9394 Diag(CurrentLocation, diag::note_member_synthesized_at)
9395 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9396 Invalid = true;
9397 continue;
9398 }
9399
9400 // Check for members of const-qualified, non-class type.
9401 QualType BaseType = Context.getBaseElementType(Field->getType());
9402 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9403 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9404 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9405 Diag(Field->getLocation(), diag::note_declared_at);
9406 Diag(CurrentLocation, diag::note_member_synthesized_at)
9407 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9408 Invalid = true;
9409 continue;
9410 }
9411
9412 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009413 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9414 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009415
9416 QualType FieldType = Field->getType().getNonReferenceType();
9417 if (FieldType->isIncompleteArrayType()) {
9418 assert(ClassDecl->hasFlexibleArrayMember() &&
9419 "Incomplete array type is not valid");
9420 continue;
9421 }
9422
9423 // Build references to the field in the object we're copying from and to.
9424 CXXScopeSpec SS; // Intentionally empty
9425 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9426 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009427 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009428 MemberLookup.resolveKind();
9429 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9430 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009431 SS, SourceLocation(), 0,
9432 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009433 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9434 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009435 SS, SourceLocation(), 0,
9436 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009437 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9438 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9439
9440 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9441 "Member reference with rvalue base must be rvalue except for reference "
9442 "members, which aren't allowed for move assignment.");
9443
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009444 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009445 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009446 To.get(), From.get(),
9447 /*CopyingBaseSubobject=*/false,
9448 /*Copying=*/false);
9449 if (Move.isInvalid()) {
9450 Diag(CurrentLocation, diag::note_member_synthesized_at)
9451 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9452 MoveAssignOperator->setInvalidDecl();
9453 return;
9454 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009455
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009456 // Success! Record the copy.
9457 Statements.push_back(Move.takeAs<Stmt>());
9458 }
9459
9460 if (!Invalid) {
9461 // Add a "return *this;"
9462 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9463
9464 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9465 if (Return.isInvalid())
9466 Invalid = true;
9467 else {
9468 Statements.push_back(Return.takeAs<Stmt>());
9469
9470 if (Trap.hasErrorOccurred()) {
9471 Diag(CurrentLocation, diag::note_member_synthesized_at)
9472 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9473 Invalid = true;
9474 }
9475 }
9476 }
9477
9478 if (Invalid) {
9479 MoveAssignOperator->setInvalidDecl();
9480 return;
9481 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009482
9483 StmtResult Body;
9484 {
9485 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009486 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009487 /*isStmtExpr=*/false);
9488 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9489 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009490 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9491
9492 if (ASTMutationListener *L = getASTMutationListener()) {
9493 L->CompletedImplicitDefinition(MoveAssignOperator);
9494 }
9495}
9496
Richard Smithb9d0b762012-07-27 04:22:15 +00009497Sema::ImplicitExceptionSpecification
9498Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9499 CXXRecordDecl *ClassDecl = MD->getParent();
9500
9501 ImplicitExceptionSpecification ExceptSpec(*this);
9502 if (ClassDecl->isInvalidDecl())
9503 return ExceptSpec;
9504
9505 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9506 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9507 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9508
Douglas Gregor0d405db2010-07-01 20:59:04 +00009509 // C++ [except.spec]p14:
9510 // An implicitly declared special member function (Clause 12) shall have an
9511 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009512 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9513 BaseEnd = ClassDecl->bases_end();
9514 Base != BaseEnd;
9515 ++Base) {
9516 // Virtual bases are handled below.
9517 if (Base->isVirtual())
9518 continue;
9519
Douglas Gregor22584312010-07-02 23:41:54 +00009520 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009521 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009522 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009523 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009524 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009525 }
9526 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9527 BaseEnd = ClassDecl->vbases_end();
9528 Base != BaseEnd;
9529 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009530 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009531 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009532 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009533 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009534 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009535 }
9536 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9537 FieldEnd = ClassDecl->field_end();
9538 Field != FieldEnd;
9539 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009540 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009541 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9542 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009543 LookupCopyingConstructor(FieldClassDecl,
9544 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009545 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009546 }
9547 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009548
Richard Smithb9d0b762012-07-27 04:22:15 +00009549 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009550}
9551
9552CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9553 CXXRecordDecl *ClassDecl) {
9554 // C++ [class.copy]p4:
9555 // If the class definition does not explicitly declare a copy
9556 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009557 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009558
Richard Smithafb49182012-11-29 01:34:07 +00009559 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9560 if (DSM.isAlreadyBeingDeclared())
9561 return 0;
9562
Sean Hunt49634cf2011-05-13 06:10:58 +00009563 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9564 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009565 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009566 if (Const)
9567 ArgType = ArgType.withConst();
9568 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009569
Richard Smith7756afa2012-06-10 05:43:50 +00009570 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9571 CXXCopyConstructor,
9572 Const);
9573
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009574 DeclarationName Name
9575 = Context.DeclarationNames.getCXXConstructorName(
9576 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009577 SourceLocation ClassLoc = ClassDecl->getLocation();
9578 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009579
9580 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009581 // member of its class.
9582 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009583 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009584 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009585 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009586 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009587 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009588
Richard Smithb9d0b762012-07-27 04:22:15 +00009589 // Build an exception specification pointing back at this member.
9590 FunctionProtoType::ExtProtoInfo EPI;
9591 EPI.ExceptionSpecType = EST_Unevaluated;
9592 EPI.ExceptionSpecDecl = CopyConstructor;
9593 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009594 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009595
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009596 // Add the parameter to the constructor.
9597 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009598 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009599 /*IdentifierInfo=*/0,
9600 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009601 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009602 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009603
Richard Smithbc2a35d2012-12-08 08:32:28 +00009604 CopyConstructor->setTrivial(
9605 ClassDecl->needsOverloadResolutionForCopyConstructor()
9606 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9607 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009608
Nico Weberafcc96a2012-01-23 03:19:29 +00009609 // C++11 [class.copy]p8:
9610 // ... If the class definition does not explicitly declare a copy
9611 // constructor, there is no user-declared move constructor, and there is no
9612 // user-declared move assignment operator, a copy constructor is implicitly
9613 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009614 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009615 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009616
Richard Smithbc2a35d2012-12-08 08:32:28 +00009617 // Note that we have declared this constructor.
9618 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9619
9620 if (Scope *S = getScopeForContext(ClassDecl))
9621 PushOnScopeChains(CopyConstructor, S, false);
9622 ClassDecl->addDecl(CopyConstructor);
9623
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009624 return CopyConstructor;
9625}
9626
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009627void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009628 CXXConstructorDecl *CopyConstructor) {
9629 assert((CopyConstructor->isDefaulted() &&
9630 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009631 !CopyConstructor->doesThisDeclarationHaveABody() &&
9632 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009633 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009634
Anders Carlsson63010a72010-04-23 16:24:12 +00009635 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009636 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009637
Eli Friedman9a14db32012-10-18 20:14:08 +00009638 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009639 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009640
David Blaikie93c86172013-01-17 05:26:25 +00009641 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009642 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009643 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009644 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009645 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009646 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009647 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009648 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9649 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009650 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009651 /*isStmtExpr=*/false)
9652 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009653 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009654 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009655
9656 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009657 if (ASTMutationListener *L = getASTMutationListener()) {
9658 L->CompletedImplicitDefinition(CopyConstructor);
9659 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009660}
9661
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009662Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009663Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9664 CXXRecordDecl *ClassDecl = MD->getParent();
9665
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009666 // C++ [except.spec]p14:
9667 // An implicitly declared special member function (Clause 12) shall have an
9668 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009669 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009670 if (ClassDecl->isInvalidDecl())
9671 return ExceptSpec;
9672
9673 // Direct base-class constructors.
9674 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9675 BEnd = ClassDecl->bases_end();
9676 B != BEnd; ++B) {
9677 if (B->isVirtual()) // Handled below.
9678 continue;
9679
9680 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9681 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009682 CXXConstructorDecl *Constructor =
9683 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009684 // If this is a deleted function, add it anyway. This might be conformant
9685 // with the standard. This might not. I'm not sure. It might not matter.
9686 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009687 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009688 }
9689 }
9690
9691 // Virtual base-class constructors.
9692 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9693 BEnd = ClassDecl->vbases_end();
9694 B != BEnd; ++B) {
9695 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9696 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009697 CXXConstructorDecl *Constructor =
9698 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009699 // If this is a deleted function, add it anyway. This might be conformant
9700 // with the standard. This might not. I'm not sure. It might not matter.
9701 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009702 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009703 }
9704 }
9705
9706 // Field constructors.
9707 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9708 FEnd = ClassDecl->field_end();
9709 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009710 QualType FieldType = Context.getBaseElementType(F->getType());
9711 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9712 CXXConstructorDecl *Constructor =
9713 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009714 // If this is a deleted function, add it anyway. This might be conformant
9715 // with the standard. This might not. I'm not sure. It might not matter.
9716 // In particular, the problem is that this function never gets called. It
9717 // might just be ill-formed because this function attempts to refer to
9718 // a deleted function here.
9719 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009720 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009721 }
9722 }
9723
9724 return ExceptSpec;
9725}
9726
9727CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9728 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009729 // C++11 [class.copy]p9:
9730 // If the definition of a class X does not explicitly declare a move
9731 // constructor, one will be implicitly declared as defaulted if and only if:
9732 //
9733 // - [first 4 bullets]
9734 assert(ClassDecl->needsImplicitMoveConstructor());
9735
Richard Smithafb49182012-11-29 01:34:07 +00009736 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9737 if (DSM.isAlreadyBeingDeclared())
9738 return 0;
9739
Richard Smith1c931be2012-04-02 18:40:40 +00009740 // [Checked after we build the declaration]
9741 // - the move assignment operator would not be implicitly defined as
9742 // deleted,
9743
9744 // [DR1402]:
9745 // - each of X's non-static data members and direct or virtual base classes
9746 // has a type that either has a move constructor or is trivially copyable.
9747 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9748 ClassDecl->setFailedImplicitMoveConstructor();
9749 return 0;
9750 }
9751
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009752 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9753 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009754
Richard Smith7756afa2012-06-10 05:43:50 +00009755 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9756 CXXMoveConstructor,
9757 false);
9758
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009759 DeclarationName Name
9760 = Context.DeclarationNames.getCXXConstructorName(
9761 Context.getCanonicalType(ClassType));
9762 SourceLocation ClassLoc = ClassDecl->getLocation();
9763 DeclarationNameInfo NameInfo(Name, ClassLoc);
9764
Richard Smitha8942d72013-05-07 03:19:20 +00009765 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009766 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009767 // member of its class.
9768 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009769 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009770 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009771 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009772 MoveConstructor->setAccess(AS_public);
9773 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009774
Richard Smithb9d0b762012-07-27 04:22:15 +00009775 // Build an exception specification pointing back at this member.
9776 FunctionProtoType::ExtProtoInfo EPI;
9777 EPI.ExceptionSpecType = EST_Unevaluated;
9778 EPI.ExceptionSpecDecl = MoveConstructor;
9779 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009780 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009781
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009782 // Add the parameter to the constructor.
9783 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9784 ClassLoc, ClassLoc,
9785 /*IdentifierInfo=*/0,
9786 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009787 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009788 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009789
Richard Smithbc2a35d2012-12-08 08:32:28 +00009790 MoveConstructor->setTrivial(
9791 ClassDecl->needsOverloadResolutionForMoveConstructor()
9792 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9793 : ClassDecl->hasTrivialMoveConstructor());
9794
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009795 // C++0x [class.copy]p9:
9796 // If the definition of a class X does not explicitly declare a move
9797 // constructor, one will be implicitly declared as defaulted if and only if:
9798 // [...]
9799 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009800 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009801 // Cache this result so that we don't try to generate this over and over
9802 // on every lookup, leaking memory and wasting time.
9803 ClassDecl->setFailedImplicitMoveConstructor();
9804 return 0;
9805 }
9806
9807 // Note that we have declared this constructor.
9808 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9809
9810 if (Scope *S = getScopeForContext(ClassDecl))
9811 PushOnScopeChains(MoveConstructor, S, false);
9812 ClassDecl->addDecl(MoveConstructor);
9813
9814 return MoveConstructor;
9815}
9816
9817void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9818 CXXConstructorDecl *MoveConstructor) {
9819 assert((MoveConstructor->isDefaulted() &&
9820 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009821 !MoveConstructor->doesThisDeclarationHaveABody() &&
9822 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009823 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9824
9825 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9826 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9827
Eli Friedman9a14db32012-10-18 20:14:08 +00009828 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009829 DiagnosticErrorTrap Trap(Diags);
9830
David Blaikie93c86172013-01-17 05:26:25 +00009831 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009832 Trap.hasErrorOccurred()) {
9833 Diag(CurrentLocation, diag::note_member_synthesized_at)
9834 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9835 MoveConstructor->setInvalidDecl();
9836 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009837 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009838 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9839 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009840 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009841 /*isStmtExpr=*/false)
9842 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009843 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009844 }
9845
9846 MoveConstructor->setUsed();
9847
9848 if (ASTMutationListener *L = getASTMutationListener()) {
9849 L->CompletedImplicitDefinition(MoveConstructor);
9850 }
9851}
9852
Douglas Gregore4e68d42012-02-15 19:33:52 +00009853bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9854 return FD->isDeleted() &&
9855 (FD->isDefaulted() || FD->isImplicit()) &&
9856 isa<CXXMethodDecl>(FD);
9857}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009858
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009859/// \brief Mark the call operator of the given lambda closure type as "used".
9860static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9861 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009862 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009863 Lambda->lookup(
9864 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009865 CallOperator->setReferenced();
9866 CallOperator->setUsed();
9867}
9868
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009869void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9870 SourceLocation CurrentLocation,
9871 CXXConversionDecl *Conv)
9872{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009873 CXXRecordDecl *Lambda = Conv->getParent();
9874
9875 // Make sure that the lambda call operator is marked used.
9876 markLambdaCallOperatorUsed(*this, Lambda);
9877
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009878 Conv->setUsed();
9879
Eli Friedman9a14db32012-10-18 20:14:08 +00009880 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009881 DiagnosticErrorTrap Trap(Diags);
9882
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009883 // Return the address of the __invoke function.
9884 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9885 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009886 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009887 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9888 VK_LValue, Conv->getLocation()).take();
9889 assert(FunctionRef && "Can't refer to __invoke function?");
9890 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009891 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009892 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009893 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009894
9895 // Fill in the __invoke function with a dummy implementation. IR generation
9896 // will fill in the actual details.
9897 Invoke->setUsed();
9898 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009899 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009900
9901 if (ASTMutationListener *L = getASTMutationListener()) {
9902 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009903 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009904 }
9905}
9906
9907void Sema::DefineImplicitLambdaToBlockPointerConversion(
9908 SourceLocation CurrentLocation,
9909 CXXConversionDecl *Conv)
9910{
9911 Conv->setUsed();
9912
Eli Friedman9a14db32012-10-18 20:14:08 +00009913 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009914 DiagnosticErrorTrap Trap(Diags);
9915
Douglas Gregorac1303e2012-02-22 05:02:47 +00009916 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009917 Expr *This = ActOnCXXThis(CurrentLocation).take();
9918 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009919
Eli Friedman23f02672012-03-01 04:01:32 +00009920 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9921 Conv->getLocation(),
9922 Conv, DerefThis);
9923
9924 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9925 // behavior. Note that only the general conversion function does this
9926 // (since it's unusable otherwise); in the case where we inline the
9927 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009928 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009929 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9930 CK_CopyAndAutoreleaseBlockObject,
9931 BuildBlock.get(), 0, VK_RValue);
9932
9933 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009934 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009935 Conv->setInvalidDecl();
9936 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009937 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009938
Douglas Gregorac1303e2012-02-22 05:02:47 +00009939 // Create the return statement that returns the block from the conversion
9940 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009941 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009942 if (Return.isInvalid()) {
9943 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9944 Conv->setInvalidDecl();
9945 return;
9946 }
9947
9948 // Set the body of the conversion function.
9949 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009950 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009951 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009952 Conv->getLocation()));
9953
Douglas Gregorac1303e2012-02-22 05:02:47 +00009954 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009955 if (ASTMutationListener *L = getASTMutationListener()) {
9956 L->CompletedImplicitDefinition(Conv);
9957 }
9958}
9959
Douglas Gregorf52757d2012-03-10 06:53:13 +00009960/// \brief Determine whether the given list arguments contains exactly one
9961/// "real" (non-default) argument.
9962static bool hasOneRealArgument(MultiExprArg Args) {
9963 switch (Args.size()) {
9964 case 0:
9965 return false;
9966
9967 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009968 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009969 return false;
9970
9971 // fall through
9972 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009973 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009974 }
9975
9976 return false;
9977}
9978
John McCall60d7b3a2010-08-24 06:29:42 +00009979ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009980Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009981 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009982 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009983 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009984 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009985 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009986 unsigned ConstructKind,
9987 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009988 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009989
Douglas Gregor2f599792010-04-02 18:24:57 +00009990 // C++0x [class.copy]p34:
9991 // When certain criteria are met, an implementation is allowed to
9992 // omit the copy/move construction of a class object, even if the
9993 // copy/move constructor and/or destructor for the object have
9994 // side effects. [...]
9995 // - when a temporary class object that has not been bound to a
9996 // reference (12.2) would be copied/moved to a class object
9997 // with the same cv-unqualified type, the copy/move operation
9998 // can be omitted by constructing the temporary object
9999 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010000 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010001 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010002 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010003 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010004 }
Mike Stump1eb44332009-09-09 15:08:12 +000010005
10006 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010007 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010008 IsListInitialization, RequiresZeroInit,
10009 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010010}
10011
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010012/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10013/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010014ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010015Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10016 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010017 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010018 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010019 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010020 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010021 unsigned ConstructKind,
10022 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010023 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010024 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010025 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010026 HadMultipleCandidates,
10027 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010028 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10029 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010030}
10031
John McCall68c6c9a2010-02-02 09:10:11 +000010032void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010033 if (VD->isInvalidDecl()) return;
10034
John McCall68c6c9a2010-02-02 09:10:11 +000010035 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010036 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010037 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010038 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010039
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010040 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010041 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010042 CheckDestructorAccess(VD->getLocation(), Destructor,
10043 PDiag(diag::err_access_dtor_var)
10044 << VD->getDeclName()
10045 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010046 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010047
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010048 if (!VD->hasGlobalStorage()) return;
10049
10050 // Emit warning for non-trivial dtor in global scope (a real global,
10051 // class-static, function-static).
10052 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10053
10054 // TODO: this should be re-enabled for static locals by !CXAAtExit
10055 if (!VD->isStaticLocal())
10056 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010057}
10058
Douglas Gregor39da0b82009-09-09 23:08:42 +000010059/// \brief Given a constructor and the set of arguments provided for the
10060/// constructor, convert the arguments and add any required default arguments
10061/// to form a proper call to this constructor.
10062///
10063/// \returns true if an error occurred, false otherwise.
10064bool
10065Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10066 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010067 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010068 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010069 bool AllowExplicit,
10070 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010071 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10072 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010073 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010074
10075 const FunctionProtoType *Proto
10076 = Constructor->getType()->getAs<FunctionProtoType>();
10077 assert(Proto && "Constructor without a prototype?");
10078 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010079
10080 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010081 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010082 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010083 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010084 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010085
10086 VariadicCallType CallType =
10087 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010088 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010089 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010090 Proto, 0,
10091 llvm::makeArrayRef(Args, NumArgs),
10092 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010093 CallType, AllowExplicit,
10094 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010095 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010096
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010097 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010098
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010099 CheckConstructorCall(Constructor,
10100 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10101 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010102 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010103
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010104 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010105}
10106
Anders Carlsson20d45d22009-12-12 00:32:00 +000010107static inline bool
10108CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10109 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010110 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010111 if (isa<NamespaceDecl>(DC)) {
10112 return SemaRef.Diag(FnDecl->getLocation(),
10113 diag::err_operator_new_delete_declared_in_namespace)
10114 << FnDecl->getDeclName();
10115 }
10116
10117 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010118 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010119 return SemaRef.Diag(FnDecl->getLocation(),
10120 diag::err_operator_new_delete_declared_static)
10121 << FnDecl->getDeclName();
10122 }
10123
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010124 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010125}
10126
Anders Carlsson156c78e2009-12-13 17:53:43 +000010127static inline bool
10128CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10129 CanQualType ExpectedResultType,
10130 CanQualType ExpectedFirstParamType,
10131 unsigned DependentParamTypeDiag,
10132 unsigned InvalidParamTypeDiag) {
10133 QualType ResultType =
10134 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10135
10136 // Check that the result type is not dependent.
10137 if (ResultType->isDependentType())
10138 return SemaRef.Diag(FnDecl->getLocation(),
10139 diag::err_operator_new_delete_dependent_result_type)
10140 << FnDecl->getDeclName() << ExpectedResultType;
10141
10142 // Check that the result type is what we expect.
10143 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10144 return SemaRef.Diag(FnDecl->getLocation(),
10145 diag::err_operator_new_delete_invalid_result_type)
10146 << FnDecl->getDeclName() << ExpectedResultType;
10147
10148 // A function template must have at least 2 parameters.
10149 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10150 return SemaRef.Diag(FnDecl->getLocation(),
10151 diag::err_operator_new_delete_template_too_few_parameters)
10152 << FnDecl->getDeclName();
10153
10154 // The function decl must have at least 1 parameter.
10155 if (FnDecl->getNumParams() == 0)
10156 return SemaRef.Diag(FnDecl->getLocation(),
10157 diag::err_operator_new_delete_too_few_parameters)
10158 << FnDecl->getDeclName();
10159
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010160 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010161 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10162 if (FirstParamType->isDependentType())
10163 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10164 << FnDecl->getDeclName() << ExpectedFirstParamType;
10165
10166 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010167 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010168 ExpectedFirstParamType)
10169 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10170 << FnDecl->getDeclName() << ExpectedFirstParamType;
10171
10172 return false;
10173}
10174
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010175static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010176CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010177 // C++ [basic.stc.dynamic.allocation]p1:
10178 // A program is ill-formed if an allocation function is declared in a
10179 // namespace scope other than global scope or declared static in global
10180 // scope.
10181 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10182 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010183
10184 CanQualType SizeTy =
10185 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10186
10187 // C++ [basic.stc.dynamic.allocation]p1:
10188 // The return type shall be void*. The first parameter shall have type
10189 // std::size_t.
10190 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10191 SizeTy,
10192 diag::err_operator_new_dependent_param_type,
10193 diag::err_operator_new_param_type))
10194 return true;
10195
10196 // C++ [basic.stc.dynamic.allocation]p1:
10197 // The first parameter shall not have an associated default argument.
10198 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010199 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010200 diag::err_operator_new_default_arg)
10201 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10202
10203 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010204}
10205
10206static bool
Richard Smith444d3842012-10-20 08:26:51 +000010207CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010208 // C++ [basic.stc.dynamic.deallocation]p1:
10209 // A program is ill-formed if deallocation functions are declared in a
10210 // namespace scope other than global scope or declared static in global
10211 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010212 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10213 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010214
10215 // C++ [basic.stc.dynamic.deallocation]p2:
10216 // Each deallocation function shall return void and its first parameter
10217 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010218 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10219 SemaRef.Context.VoidPtrTy,
10220 diag::err_operator_delete_dependent_param_type,
10221 diag::err_operator_delete_param_type))
10222 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010223
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010224 return false;
10225}
10226
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010227/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10228/// of this overloaded operator is well-formed. If so, returns false;
10229/// otherwise, emits appropriate diagnostics and returns true.
10230bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010231 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010232 "Expected an overloaded operator declaration");
10233
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010234 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10235
Mike Stump1eb44332009-09-09 15:08:12 +000010236 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010237 // The allocation and deallocation functions, operator new,
10238 // operator new[], operator delete and operator delete[], are
10239 // described completely in 3.7.3. The attributes and restrictions
10240 // found in the rest of this subclause do not apply to them unless
10241 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010242 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010243 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010244
Anders Carlssona3ccda52009-12-12 00:26:23 +000010245 if (Op == OO_New || Op == OO_Array_New)
10246 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010247
10248 // C++ [over.oper]p6:
10249 // An operator function shall either be a non-static member
10250 // function or be a non-member function and have at least one
10251 // parameter whose type is a class, a reference to a class, an
10252 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010253 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10254 if (MethodDecl->isStatic())
10255 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010256 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010257 } else {
10258 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010259 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10260 ParamEnd = FnDecl->param_end();
10261 Param != ParamEnd; ++Param) {
10262 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010263 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10264 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010265 ClassOrEnumParam = true;
10266 break;
10267 }
10268 }
10269
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010270 if (!ClassOrEnumParam)
10271 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010272 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010273 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010274 }
10275
10276 // C++ [over.oper]p8:
10277 // An operator function cannot have default arguments (8.3.6),
10278 // except where explicitly stated below.
10279 //
Mike Stump1eb44332009-09-09 15:08:12 +000010280 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010281 // (C++ [over.call]p1).
10282 if (Op != OO_Call) {
10283 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10284 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010285 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010286 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010287 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010288 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010289 }
10290 }
10291
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010292 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10293 { false, false, false }
10294#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10295 , { Unary, Binary, MemberOnly }
10296#include "clang/Basic/OperatorKinds.def"
10297 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010298
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010299 bool CanBeUnaryOperator = OperatorUses[Op][0];
10300 bool CanBeBinaryOperator = OperatorUses[Op][1];
10301 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010302
10303 // C++ [over.oper]p8:
10304 // [...] Operator functions cannot have more or fewer parameters
10305 // than the number required for the corresponding operator, as
10306 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010307 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010308 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010309 if (Op != OO_Call &&
10310 ((NumParams == 1 && !CanBeUnaryOperator) ||
10311 (NumParams == 2 && !CanBeBinaryOperator) ||
10312 (NumParams < 1) || (NumParams > 2))) {
10313 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010314 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010315 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010316 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010317 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010318 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010319 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010320 assert(CanBeBinaryOperator &&
10321 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010322 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010323 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010324
Chris Lattner416e46f2008-11-21 07:57:12 +000010325 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010326 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010327 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010328
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010329 // Overloaded operators other than operator() cannot be variadic.
10330 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010331 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010332 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010333 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010334 }
10335
10336 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010337 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10338 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010339 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010340 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010341 }
10342
10343 // C++ [over.inc]p1:
10344 // The user-defined function called operator++ implements the
10345 // prefix and postfix ++ operator. If this function is a member
10346 // function with no parameters, or a non-member function with one
10347 // parameter of class or enumeration type, it defines the prefix
10348 // increment operator ++ for objects of that type. If the function
10349 // is a member function with one parameter (which shall be of type
10350 // int) or a non-member function with two parameters (the second
10351 // of which shall be of type int), it defines the postfix
10352 // increment operator ++ for objects of that type.
10353 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10354 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10355 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010356 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010357 ParamIsInt = BT->getKind() == BuiltinType::Int;
10358
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010359 if (!ParamIsInt)
10360 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010361 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010362 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010363 }
10364
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010365 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010366}
Chris Lattner5a003a42008-12-17 07:09:26 +000010367
Sean Hunta6c058d2010-01-13 09:01:02 +000010368/// CheckLiteralOperatorDeclaration - Check whether the declaration
10369/// of this literal operator function is well-formed. If so, returns
10370/// false; otherwise, emits appropriate diagnostics and returns true.
10371bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010372 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010373 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10374 << FnDecl->getDeclName();
10375 return true;
10376 }
10377
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010378 if (FnDecl->isExternC()) {
10379 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10380 return true;
10381 }
10382
Sean Hunta6c058d2010-01-13 09:01:02 +000010383 bool Valid = false;
10384
Richard Smith36f5cfe2012-03-09 08:00:36 +000010385 // This might be the definition of a literal operator template.
10386 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10387 // This might be a specialization of a literal operator template.
10388 if (!TpDecl)
10389 TpDecl = FnDecl->getPrimaryTemplate();
10390
Sean Hunt216c2782010-04-07 23:11:06 +000010391 // template <char...> type operator "" name() is the only valid template
10392 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010393 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010394 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010395 // Must have only one template parameter
10396 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10397 if (Params->size() == 1) {
10398 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010399 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010400
Sean Hunt216c2782010-04-07 23:11:06 +000010401 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010402 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10403 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10404 Valid = true;
10405 }
10406 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010407 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010408 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010409 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10410
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010411 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010412
Sean Hunt30019c02010-04-07 22:57:35 +000010413 // unsigned long long int, long double, and any character type are allowed
10414 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010415 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10416 Context.hasSameType(T, Context.LongDoubleTy) ||
10417 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010418 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010419 Context.hasSameType(T, Context.Char16Ty) ||
10420 Context.hasSameType(T, Context.Char32Ty)) {
10421 if (++Param == FnDecl->param_end())
10422 Valid = true;
10423 goto FinishedParams;
10424 }
10425
Sean Hunt30019c02010-04-07 22:57:35 +000010426 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010427 const PointerType *PT = T->getAs<PointerType>();
10428 if (!PT)
10429 goto FinishedParams;
10430 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010431 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010432 goto FinishedParams;
10433 T = T.getUnqualifiedType();
10434
10435 // Move on to the second parameter;
10436 ++Param;
10437
10438 // If there is no second parameter, the first must be a const char *
10439 if (Param == FnDecl->param_end()) {
10440 if (Context.hasSameType(T, Context.CharTy))
10441 Valid = true;
10442 goto FinishedParams;
10443 }
10444
10445 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10446 // are allowed as the first parameter to a two-parameter function
10447 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010448 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010449 Context.hasSameType(T, Context.Char16Ty) ||
10450 Context.hasSameType(T, Context.Char32Ty)))
10451 goto FinishedParams;
10452
10453 // The second and final parameter must be an std::size_t
10454 T = (*Param)->getType().getUnqualifiedType();
10455 if (Context.hasSameType(T, Context.getSizeType()) &&
10456 ++Param == FnDecl->param_end())
10457 Valid = true;
10458 }
10459
10460 // FIXME: This diagnostic is absolutely terrible.
10461FinishedParams:
10462 if (!Valid) {
10463 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10464 << FnDecl->getDeclName();
10465 return true;
10466 }
10467
Richard Smitha9e88b22012-03-09 08:16:22 +000010468 // A parameter-declaration-clause containing a default argument is not
10469 // equivalent to any of the permitted forms.
10470 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10471 ParamEnd = FnDecl->param_end();
10472 Param != ParamEnd; ++Param) {
10473 if ((*Param)->hasDefaultArg()) {
10474 Diag((*Param)->getDefaultArgRange().getBegin(),
10475 diag::err_literal_operator_default_argument)
10476 << (*Param)->getDefaultArgRange();
10477 break;
10478 }
10479 }
10480
Richard Smith2fb4ae32012-03-08 02:39:21 +000010481 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010482 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10483 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010484 // C++11 [usrlit.suffix]p1:
10485 // Literal suffix identifiers that do not start with an underscore
10486 // are reserved for future standardization.
10487 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010488 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010489
Sean Hunta6c058d2010-01-13 09:01:02 +000010490 return false;
10491}
10492
Douglas Gregor074149e2009-01-05 19:45:36 +000010493/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10494/// linkage specification, including the language and (if present)
10495/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10496/// the location of the language string literal, which is provided
10497/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10498/// the '{' brace. Otherwise, this linkage specification does not
10499/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010500Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10501 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010502 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010503 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010504 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010505 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010506 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010507 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010508 Language = LinkageSpecDecl::lang_cxx;
10509 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010510 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010511 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010512 }
Mike Stump1eb44332009-09-09 15:08:12 +000010513
Chris Lattnercc98eac2008-12-17 07:13:27 +000010514 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010515
Douglas Gregor074149e2009-01-05 19:45:36 +000010516 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010517 ExternLoc, LangLoc, Language,
10518 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010519 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010520 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010521 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010522}
10523
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010524/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010525/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10526/// valid, it's the position of the closing '}' brace in a linkage
10527/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010528Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010529 Decl *LinkageSpec,
10530 SourceLocation RBraceLoc) {
10531 if (LinkageSpec) {
10532 if (RBraceLoc.isValid()) {
10533 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10534 LSDecl->setRBraceLoc(RBraceLoc);
10535 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010536 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010537 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010538 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010539}
10540
Michael Han684aa732013-02-22 17:15:32 +000010541Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10542 AttributeList *AttrList,
10543 SourceLocation SemiLoc) {
10544 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10545 // Attribute declarations appertain to empty declaration so we handle
10546 // them here.
10547 if (AttrList)
10548 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010549
Michael Han684aa732013-02-22 17:15:32 +000010550 CurContext->addDecl(ED);
10551 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010552}
10553
Douglas Gregord308e622009-05-18 20:51:54 +000010554/// \brief Perform semantic analysis for the variable declaration that
10555/// occurs within a C++ catch clause, returning the newly-created
10556/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010557VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010558 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010559 SourceLocation StartLoc,
10560 SourceLocation Loc,
10561 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010562 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010563 QualType ExDeclType = TInfo->getType();
10564
Sebastian Redl4b07b292008-12-22 19:15:10 +000010565 // Arrays and functions decay.
10566 if (ExDeclType->isArrayType())
10567 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10568 else if (ExDeclType->isFunctionType())
10569 ExDeclType = Context.getPointerType(ExDeclType);
10570
10571 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10572 // The exception-declaration shall not denote a pointer or reference to an
10573 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010574 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010575 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010576 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010577 Invalid = true;
10578 }
Douglas Gregord308e622009-05-18 20:51:54 +000010579
Sebastian Redl4b07b292008-12-22 19:15:10 +000010580 QualType BaseType = ExDeclType;
10581 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010582 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010583 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010584 BaseType = Ptr->getPointeeType();
10585 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010586 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010587 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010588 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010589 BaseType = Ref->getPointeeType();
10590 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010591 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010592 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010593 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010594 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010595 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010596
Mike Stump1eb44332009-09-09 15:08:12 +000010597 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010598 RequireNonAbstractType(Loc, ExDeclType,
10599 diag::err_abstract_type_in_decl,
10600 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010601 Invalid = true;
10602
John McCall5a180392010-07-24 00:37:23 +000010603 // Only the non-fragile NeXT runtime currently supports C++ catches
10604 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010605 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010606 QualType T = ExDeclType;
10607 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10608 T = RT->getPointeeType();
10609
10610 if (T->isObjCObjectType()) {
10611 Diag(Loc, diag::err_objc_object_catch);
10612 Invalid = true;
10613 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010614 // FIXME: should this be a test for macosx-fragile specifically?
10615 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010616 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010617 }
10618 }
10619
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010620 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010621 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010622 ExDecl->setExceptionVariable(true);
10623
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010624 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010625 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010626 Invalid = true;
10627
Douglas Gregorc41b8782011-07-06 18:14:43 +000010628 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010629 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010630 // Insulate this from anything else we might currently be parsing.
10631 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10632
Douglas Gregor6d182892010-03-05 23:38:39 +000010633 // C++ [except.handle]p16:
10634 // The object declared in an exception-declaration or, if the
10635 // exception-declaration does not specify a name, a temporary (12.2) is
10636 // copy-initialized (8.5) from the exception object. [...]
10637 // The object is destroyed when the handler exits, after the destruction
10638 // of any automatic objects initialized within the handler.
10639 //
10640 // We just pretend to initialize the object with itself, then make sure
10641 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010642 QualType initType = ExDeclType;
10643
10644 InitializedEntity entity =
10645 InitializedEntity::InitializeVariable(ExDecl);
10646 InitializationKind initKind =
10647 InitializationKind::CreateCopy(Loc, SourceLocation());
10648
10649 Expr *opaqueValue =
10650 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000010651 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10652 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000010653 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010654 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010655 else {
10656 // If the constructor used was non-trivial, set this as the
10657 // "initializer".
10658 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10659 if (!construct->getConstructor()->isTrivial()) {
10660 Expr *init = MaybeCreateExprWithCleanups(construct);
10661 ExDecl->setInit(init);
10662 }
10663
10664 // And make sure it's destructable.
10665 FinalizeVarWithDestructor(ExDecl, recordType);
10666 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010667 }
10668 }
10669
Douglas Gregord308e622009-05-18 20:51:54 +000010670 if (Invalid)
10671 ExDecl->setInvalidDecl();
10672
10673 return ExDecl;
10674}
10675
10676/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10677/// handler.
John McCalld226f652010-08-21 09:40:31 +000010678Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010679 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010680 bool Invalid = D.isInvalidType();
10681
10682 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010683 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10684 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010685 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10686 D.getIdentifierLoc());
10687 Invalid = true;
10688 }
10689
Sebastian Redl4b07b292008-12-22 19:15:10 +000010690 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010691 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010692 LookupOrdinaryName,
10693 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010694 // The scope should be freshly made just for us. There is just no way
10695 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010696 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010697 if (PrevDecl->isTemplateParameter()) {
10698 // Maybe we will complain about the shadowed template parameter.
10699 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010700 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010701 }
10702 }
10703
Chris Lattnereaaebc72009-04-25 08:06:05 +000010704 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010705 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10706 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010707 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010708 }
10709
Douglas Gregor83cb9422010-09-09 17:09:21 +000010710 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010711 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010712 D.getIdentifierLoc(),
10713 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010714 if (Invalid)
10715 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010716
Sebastian Redl4b07b292008-12-22 19:15:10 +000010717 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010718 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010719 PushOnScopeChains(ExDecl, S);
10720 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010721 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010722
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010723 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010724 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010725}
Anders Carlssonfb311762009-03-14 00:25:26 +000010726
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010727Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010728 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010729 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010730 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010731 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010732
Richard Smithe3f470a2012-07-11 22:37:56 +000010733 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10734 return 0;
10735
10736 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10737 AssertMessage, RParenLoc, false);
10738}
10739
10740Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10741 Expr *AssertExpr,
10742 StringLiteral *AssertMessage,
10743 SourceLocation RParenLoc,
10744 bool Failed) {
10745 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10746 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010747 // In a static_assert-declaration, the constant-expression shall be a
10748 // constant expression that can be contextually converted to bool.
10749 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10750 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010751 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010752
Richard Smithdaaefc52011-12-14 23:32:26 +000010753 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010754 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010755 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010756 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010757 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010758
Richard Smithe3f470a2012-07-11 22:37:56 +000010759 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010760 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010761 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010762 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010763 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010764 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010765 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010766 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010767 }
Mike Stump1eb44332009-09-09 15:08:12 +000010768
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010769 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010770 AssertExpr, AssertMessage, RParenLoc,
10771 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010772
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010773 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010774 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010775}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010776
Douglas Gregor1d869352010-04-07 16:53:43 +000010777/// \brief Perform semantic analysis of the given friend type declaration.
10778///
10779/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010780FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010781 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010782 TypeSourceInfo *TSInfo) {
10783 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10784
10785 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010786 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010787
Richard Smith6b130222011-10-18 21:39:00 +000010788 // C++03 [class.friend]p2:
10789 // An elaborated-type-specifier shall be used in a friend declaration
10790 // for a class.*
10791 //
10792 // * The class-key of the elaborated-type-specifier is required.
10793 if (!ActiveTemplateInstantiations.empty()) {
10794 // Do not complain about the form of friend template types during
10795 // template instantiation; we will already have complained when the
10796 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010797 } else {
10798 if (!T->isElaboratedTypeSpecifier()) {
10799 // If we evaluated the type to a record type, suggest putting
10800 // a tag in front.
10801 if (const RecordType *RT = T->getAs<RecordType>()) {
10802 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010803
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010804 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010805
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010806 Diag(TypeRange.getBegin(),
10807 getLangOpts().CPlusPlus11 ?
10808 diag::warn_cxx98_compat_unelaborated_friend_type :
10809 diag::ext_unelaborated_friend_type)
10810 << (unsigned) RD->getTagKind()
10811 << T
10812 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10813 InsertionText);
10814 } else {
10815 Diag(FriendLoc,
10816 getLangOpts().CPlusPlus11 ?
10817 diag::warn_cxx98_compat_nonclass_type_friend :
10818 diag::ext_nonclass_type_friend)
10819 << T
10820 << TypeRange;
10821 }
10822 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010823 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010824 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010825 diag::warn_cxx98_compat_enum_friend :
10826 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010827 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010828 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010829 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010830
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010831 // C++11 [class.friend]p3:
10832 // A friend declaration that does not declare a function shall have one
10833 // of the following forms:
10834 // friend elaborated-type-specifier ;
10835 // friend simple-type-specifier ;
10836 // friend typename-specifier ;
10837 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10838 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10839 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010840
Douglas Gregor06245bf2010-04-07 17:57:12 +000010841 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010842 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010843 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010844 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010845}
10846
John McCall9a34edb2010-10-19 01:40:49 +000010847/// Handle a friend tag declaration where the scope specifier was
10848/// templated.
10849Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10850 unsigned TagSpec, SourceLocation TagLoc,
10851 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010852 IdentifierInfo *Name,
10853 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010854 AttributeList *Attr,
10855 MultiTemplateParamsArg TempParamLists) {
10856 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10857
10858 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010859 bool Invalid = false;
10860
10861 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010862 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010863 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010864 TempParamLists.size(),
10865 /*friend*/ true,
10866 isExplicitSpecialization,
10867 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010868 if (TemplateParams->size() > 0) {
10869 // This is a declaration of a class template.
10870 if (Invalid)
10871 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010872
Eric Christopher4110e132011-07-21 05:34:24 +000010873 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10874 SS, Name, NameLoc, Attr,
10875 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010876 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010877 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010878 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010879 } else {
10880 // The "template<>" header is extraneous.
10881 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10882 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10883 isExplicitSpecialization = true;
10884 }
10885 }
10886
10887 if (Invalid) return 0;
10888
John McCall9a34edb2010-10-19 01:40:49 +000010889 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010890 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010891 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010892 isAllExplicitSpecializations = false;
10893 break;
10894 }
10895 }
10896
10897 // FIXME: don't ignore attributes.
10898
10899 // If it's explicit specializations all the way down, just forget
10900 // about the template header and build an appropriate non-templated
10901 // friend. TODO: for source fidelity, remember the headers.
10902 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010903 if (SS.isEmpty()) {
10904 bool Owned = false;
10905 bool IsDependent = false;
10906 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10907 Attr, AS_public,
10908 /*ModulePrivateLoc=*/SourceLocation(),
10909 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010910 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010911 /*ScopedEnumUsesClassTag=*/false,
10912 /*UnderlyingType=*/TypeResult());
10913 }
10914
Douglas Gregor2494dd02011-03-01 01:34:45 +000010915 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010916 ElaboratedTypeKeyword Keyword
10917 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010918 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010919 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010920 if (T.isNull())
10921 return 0;
10922
10923 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10924 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010925 DependentNameTypeLoc TL =
10926 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010927 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010928 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010929 TL.setNameLoc(NameLoc);
10930 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010931 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010932 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010933 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010934 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010935 }
10936
10937 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010938 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010939 Friend->setAccess(AS_public);
10940 CurContext->addDecl(Friend);
10941 return Friend;
10942 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010943
10944 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10945
10946
John McCall9a34edb2010-10-19 01:40:49 +000010947
10948 // Handle the case of a templated-scope friend class. e.g.
10949 // template <class T> class A<T>::B;
10950 // FIXME: we don't support these right now.
10951 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10952 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10953 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010954 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010955 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010956 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010957 TL.setNameLoc(NameLoc);
10958
10959 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010960 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010961 Friend->setAccess(AS_public);
10962 Friend->setUnsupportedFriend(true);
10963 CurContext->addDecl(Friend);
10964 return Friend;
10965}
10966
10967
John McCalldd4a3b02009-09-16 22:47:08 +000010968/// Handle a friend type declaration. This works in tandem with
10969/// ActOnTag.
10970///
10971/// Notes on friend class templates:
10972///
10973/// We generally treat friend class declarations as if they were
10974/// declaring a class. So, for example, the elaborated type specifier
10975/// in a friend declaration is required to obey the restrictions of a
10976/// class-head (i.e. no typedefs in the scope chain), template
10977/// parameters are required to match up with simple template-ids, &c.
10978/// However, unlike when declaring a template specialization, it's
10979/// okay to refer to a template specialization without an empty
10980/// template parameter declaration, e.g.
10981/// friend class A<T>::B<unsigned>;
10982/// We permit this as a special case; if there are any template
10983/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010984/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010985Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010986 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010987 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010988
10989 assert(DS.isFriendSpecified());
10990 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10991
John McCalldd4a3b02009-09-16 22:47:08 +000010992 // Try to convert the decl specifier to a type. This works for
10993 // friend templates because ActOnTag never produces a ClassTemplateDecl
10994 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010995 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010996 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10997 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010998 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010999 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011000
Douglas Gregor6ccab972010-12-16 01:14:37 +000011001 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11002 return 0;
11003
John McCalldd4a3b02009-09-16 22:47:08 +000011004 // This is definitely an error in C++98. It's probably meant to
11005 // be forbidden in C++0x, too, but the specification is just
11006 // poorly written.
11007 //
11008 // The problem is with declarations like the following:
11009 // template <T> friend A<T>::foo;
11010 // where deciding whether a class C is a friend or not now hinges
11011 // on whether there exists an instantiation of A that causes
11012 // 'foo' to equal C. There are restrictions on class-heads
11013 // (which we declare (by fiat) elaborated friend declarations to
11014 // be) that makes this tractable.
11015 //
11016 // FIXME: handle "template <> friend class A<T>;", which
11017 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011018 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011019 Diag(Loc, diag::err_tagless_friend_type_template)
11020 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011021 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011022 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011023
John McCall02cace72009-08-28 07:59:38 +000011024 // C++98 [class.friend]p1: A friend of a class is a function
11025 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011026 // This is fixed in DR77, which just barely didn't make the C++03
11027 // deadline. It's also a very silly restriction that seriously
11028 // affects inner classes and which nobody else seems to implement;
11029 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011030 //
11031 // But note that we could warn about it: it's always useless to
11032 // friend one of your own members (it's not, however, worthless to
11033 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011034
John McCalldd4a3b02009-09-16 22:47:08 +000011035 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011036 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011037 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011038 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011039 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011040 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011041 DS.getFriendSpecLoc());
11042 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011043 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011044
11045 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011046 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011047
John McCalldd4a3b02009-09-16 22:47:08 +000011048 D->setAccess(AS_public);
11049 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011050
John McCalld226f652010-08-21 09:40:31 +000011051 return D;
John McCall02cace72009-08-28 07:59:38 +000011052}
11053
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011054NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11055 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011056 const DeclSpec &DS = D.getDeclSpec();
11057
11058 assert(DS.isFriendSpecified());
11059 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11060
11061 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011062 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011063
11064 // C++ [class.friend]p1
11065 // A friend of a class is a function or class....
11066 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011067 // It *doesn't* see through dependent types, which is correct
11068 // according to [temp.arg.type]p3:
11069 // If a declaration acquires a function type through a
11070 // type dependent on a template-parameter and this causes
11071 // a declaration that does not use the syntactic form of a
11072 // function declarator to have a function type, the program
11073 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011074 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011075 Diag(Loc, diag::err_unexpected_friend);
11076
11077 // It might be worthwhile to try to recover by creating an
11078 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011079 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011080 }
11081
11082 // C++ [namespace.memdef]p3
11083 // - If a friend declaration in a non-local class first declares a
11084 // class or function, the friend class or function is a member
11085 // of the innermost enclosing namespace.
11086 // - The name of the friend is not found by simple name lookup
11087 // until a matching declaration is provided in that namespace
11088 // scope (either before or after the class declaration granting
11089 // friendship).
11090 // - If a friend function is called, its name may be found by the
11091 // name lookup that considers functions from namespaces and
11092 // classes associated with the types of the function arguments.
11093 // - When looking for a prior declaration of a class or a function
11094 // declared as a friend, scopes outside the innermost enclosing
11095 // namespace scope are not considered.
11096
John McCall337ec3d2010-10-12 23:13:28 +000011097 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011098 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11099 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011100 assert(Name);
11101
Douglas Gregor6ccab972010-12-16 01:14:37 +000011102 // Check for unexpanded parameter packs.
11103 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11104 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11105 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11106 return 0;
11107
John McCall67d1a672009-08-06 02:15:43 +000011108 // The context we found the declaration in, or in which we should
11109 // create the declaration.
11110 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011111 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011112 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011113 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011114
John McCall337ec3d2010-10-12 23:13:28 +000011115 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000011116
John McCall337ec3d2010-10-12 23:13:28 +000011117 // There are four cases here.
11118 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000011119 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000011120 // there as appropriate.
11121 // Recover from invalid scope qualifiers as if they just weren't there.
11122 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000011123 // C++0x [namespace.memdef]p3:
11124 // If the name in a friend declaration is neither qualified nor
11125 // a template-id and the declaration is a function or an
11126 // elaborated-type-specifier, the lookup to determine whether
11127 // the entity has been previously declared shall not consider
11128 // any scopes outside the innermost enclosing namespace.
11129 // C++0x [class.friend]p11:
11130 // If a friend declaration appears in a local class and the name
11131 // specified is an unqualified name, a prior declaration is
11132 // looked up without considering scopes that are outside the
11133 // innermost enclosing non-class scope. For a friend function
11134 // declaration, if there is no prior declaration, the program is
11135 // ill-formed.
11136 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000011137 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011138
John McCall29ae6e52010-10-13 05:45:15 +000011139 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011140 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011141
Rafael Espindola11dc6342013-04-25 20:12:36 +000011142 // Skip class contexts. If someone can cite chapter and verse
11143 // for this behavior, that would be nice --- it's what GCC and
11144 // EDG do, and it seems like a reasonable intent, but the spec
11145 // really only says that checks for unqualified existing
11146 // declarations should stop at the nearest enclosing namespace,
11147 // not that they should only consider the nearest enclosing
11148 // namespace.
11149 while (DC->isRecord())
11150 DC = DC->getParent();
11151
11152 DeclContext *LookupDC = DC;
11153 while (LookupDC->isTransparentContext())
11154 LookupDC = LookupDC->getParent();
11155
11156 while (true) {
11157 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011158
11159 // TODO: decide what we think about using declarations.
Rafael Espindola11dc6342013-04-25 20:12:36 +000011160 if (isLocal)
John McCall67d1a672009-08-06 02:15:43 +000011161 break;
John McCall29ae6e52010-10-13 05:45:15 +000011162
Rafael Espindola11dc6342013-04-25 20:12:36 +000011163 if (!Previous.empty()) {
11164 DC = LookupDC;
11165 break;
John McCall8a407372010-10-14 22:22:28 +000011166 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011167
11168 if (isTemplateId) {
11169 if (isa<TranslationUnitDecl>(LookupDC)) break;
11170 } else {
11171 if (LookupDC->isFileContext()) break;
11172 }
11173 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011174 }
11175
John McCall380aaa42010-10-13 06:22:15 +000011176 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011177
Douglas Gregor883af832011-10-10 01:11:59 +000011178 // C++ [class.friend]p6:
11179 // A function can be defined in a friend declaration of a class if and
11180 // only if the class is a non-local class (9.8), the function name is
11181 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011182 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011183 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11184 }
11185
John McCall337ec3d2010-10-12 23:13:28 +000011186 // - There's a non-dependent scope specifier, in which case we
11187 // compute it and do a previous lookup there for a function
11188 // or function template.
11189 } else if (!SS.getScopeRep()->isDependent()) {
11190 DC = computeDeclContext(SS);
11191 if (!DC) return 0;
11192
11193 if (RequireCompleteDeclContext(SS, DC)) return 0;
11194
11195 LookupQualifiedName(Previous, DC);
11196
11197 // Ignore things found implicitly in the wrong scope.
11198 // TODO: better diagnostics for this case. Suggesting the right
11199 // qualified scope would be nice...
11200 LookupResult::Filter F = Previous.makeFilter();
11201 while (F.hasNext()) {
11202 NamedDecl *D = F.next();
11203 if (!DC->InEnclosingNamespaceSetOf(
11204 D->getDeclContext()->getRedeclContext()))
11205 F.erase();
11206 }
11207 F.done();
11208
11209 if (Previous.empty()) {
11210 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011211 Diag(Loc, diag::err_qualified_friend_not_found)
11212 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011213 return 0;
11214 }
11215
11216 // C++ [class.friend]p1: A friend of a class is a function or
11217 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011218 if (DC->Equals(CurContext))
11219 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011220 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011221 diag::warn_cxx98_compat_friend_is_member :
11222 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011223
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011224 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011225 // C++ [class.friend]p6:
11226 // A function can be defined in a friend declaration of a class if and
11227 // only if the class is a non-local class (9.8), the function name is
11228 // unqualified, and the function has namespace scope.
11229 SemaDiagnosticBuilder DB
11230 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11231
11232 DB << SS.getScopeRep();
11233 if (DC->isFileContext())
11234 DB << FixItHint::CreateRemoval(SS.getRange());
11235 SS.clear();
11236 }
John McCall337ec3d2010-10-12 23:13:28 +000011237
11238 // - There's a scope specifier that does not match any template
11239 // parameter lists, in which case we use some arbitrary context,
11240 // create a method or method template, and wait for instantiation.
11241 // - There's a scope specifier that does match some template
11242 // parameter lists, which we don't handle right now.
11243 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011244 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011245 // C++ [class.friend]p6:
11246 // A function can be defined in a friend declaration of a class if and
11247 // only if the class is a non-local class (9.8), the function name is
11248 // unqualified, and the function has namespace scope.
11249 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11250 << SS.getScopeRep();
11251 }
11252
John McCall337ec3d2010-10-12 23:13:28 +000011253 DC = CurContext;
11254 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011255 }
Douglas Gregor883af832011-10-10 01:11:59 +000011256
John McCall29ae6e52010-10-13 05:45:15 +000011257 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011258 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011259 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11260 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11261 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011262 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011263 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11264 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011265 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011266 }
John McCall67d1a672009-08-06 02:15:43 +000011267 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011268
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011269 // FIXME: This is an egregious hack to cope with cases where the scope stack
11270 // does not contain the declaration context, i.e., in an out-of-line
11271 // definition of a class.
11272 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11273 if (!DCScope) {
11274 FakeDCScope.setEntity(DC);
11275 DCScope = &FakeDCScope;
11276 }
11277
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011278 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011279 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011280 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011281 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011282
Douglas Gregor182ddf02009-09-28 00:08:27 +000011283 assert(ND->getDeclContext() == DC);
11284 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011285
John McCallab88d972009-08-31 22:39:49 +000011286 // Add the function declaration to the appropriate lookup tables,
11287 // adjusting the redeclarations list as necessary. We don't
11288 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011289 //
John McCallab88d972009-08-31 22:39:49 +000011290 // Also update the scope-based lookup if the target context's
11291 // lookup context is in lexical scope.
11292 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011293 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011294 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011295 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011296 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011297 }
John McCall02cace72009-08-28 07:59:38 +000011298
11299 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011300 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011301 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011302 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011303 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011304
John McCall1f2e1a92012-08-10 03:15:35 +000011305 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011306 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011307 } else {
11308 if (DC->isRecord()) CheckFriendAccess(ND);
11309
John McCall6102ca12010-10-16 06:59:13 +000011310 FunctionDecl *FD;
11311 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11312 FD = FTD->getTemplatedDecl();
11313 else
11314 FD = cast<FunctionDecl>(ND);
11315
11316 // Mark templated-scope function declarations as unsupported.
11317 if (FD->getNumTemplateParameterLists())
11318 FrD->setUnsupportedFriend(true);
11319 }
John McCall337ec3d2010-10-12 23:13:28 +000011320
John McCalld226f652010-08-21 09:40:31 +000011321 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011322}
11323
John McCalld226f652010-08-21 09:40:31 +000011324void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11325 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011326
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011327 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011328 if (!Fn) {
11329 Diag(DelLoc, diag::err_deleted_non_function);
11330 return;
11331 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011332
Douglas Gregoref96ee02012-01-14 16:38:05 +000011333 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011334 // Don't consider the implicit declaration we generate for explicit
11335 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011336 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11337 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011338 Diag(DelLoc, diag::err_deleted_decl_not_first);
11339 Diag(Prev->getLocation(), diag::note_previous_declaration);
11340 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011341 // If the declaration wasn't the first, we delete the function anyway for
11342 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011343 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011344 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011345
11346 if (Fn->isDeleted())
11347 return;
11348
11349 // See if we're deleting a function which is already known to override a
11350 // non-deleted virtual function.
11351 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11352 bool IssuedDiagnostic = false;
11353 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11354 E = MD->end_overridden_methods();
11355 I != E; ++I) {
11356 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11357 if (!IssuedDiagnostic) {
11358 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11359 IssuedDiagnostic = true;
11360 }
11361 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11362 }
11363 }
11364 }
11365
Sean Hunt10620eb2011-05-06 20:44:56 +000011366 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011367}
Sebastian Redl13e88542009-04-27 21:33:24 +000011368
Sean Hunte4246a62011-05-12 06:15:49 +000011369void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011370 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011371
11372 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011373 if (MD->getParent()->isDependentType()) {
11374 MD->setDefaulted();
11375 MD->setExplicitlyDefaulted();
11376 return;
11377 }
11378
Sean Hunte4246a62011-05-12 06:15:49 +000011379 CXXSpecialMember Member = getSpecialMember(MD);
11380 if (Member == CXXInvalid) {
11381 Diag(DefaultLoc, diag::err_default_special_members);
11382 return;
11383 }
11384
11385 MD->setDefaulted();
11386 MD->setExplicitlyDefaulted();
11387
Sean Huntcd10dec2011-05-23 23:14:04 +000011388 // If this definition appears within the record, do the checking when
11389 // the record is complete.
11390 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011391 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011392 // Find the uninstantiated declaration that actually had the '= default'
11393 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011394 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011395
Richard Smith12fef492013-03-27 00:22:47 +000011396 // If the method was defaulted on its first declaration, we will have
11397 // already performed the checking in CheckCompletedCXXClass. Such a
11398 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011399 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011400 return;
11401
Richard Smithb9d0b762012-07-27 04:22:15 +000011402 CheckExplicitlyDefaultedSpecialMember(MD);
11403
Richard Smith1d28caf2012-12-11 01:14:52 +000011404 // The exception specification is needed because we are defining the
11405 // function.
11406 ResolveExceptionSpec(DefaultLoc,
11407 MD->getType()->castAs<FunctionProtoType>());
11408
Sean Hunte4246a62011-05-12 06:15:49 +000011409 switch (Member) {
11410 case CXXDefaultConstructor: {
11411 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011412 if (!CD->isInvalidDecl())
11413 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11414 break;
11415 }
11416
11417 case CXXCopyConstructor: {
11418 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011419 if (!CD->isInvalidDecl())
11420 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011421 break;
11422 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011423
Sean Hunt2b188082011-05-14 05:23:28 +000011424 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011425 if (!MD->isInvalidDecl())
11426 DefineImplicitCopyAssignment(DefaultLoc, MD);
11427 break;
11428 }
11429
Sean Huntcb45a0f2011-05-12 22:46:25 +000011430 case CXXDestructor: {
11431 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011432 if (!DD->isInvalidDecl())
11433 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011434 break;
11435 }
11436
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011437 case CXXMoveConstructor: {
11438 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011439 if (!CD->isInvalidDecl())
11440 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011441 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011442 }
Sean Hunt82713172011-05-25 23:16:36 +000011443
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011444 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011445 if (!MD->isInvalidDecl())
11446 DefineImplicitMoveAssignment(DefaultLoc, MD);
11447 break;
11448 }
11449
11450 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011451 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011452 }
11453 } else {
11454 Diag(DefaultLoc, diag::err_default_special_members);
11455 }
11456}
11457
Sebastian Redl13e88542009-04-27 21:33:24 +000011458static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011459 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011460 Stmt *SubStmt = *CI;
11461 if (!SubStmt)
11462 continue;
11463 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011464 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011465 diag::err_return_in_constructor_handler);
11466 if (!isa<Expr>(SubStmt))
11467 SearchForReturnInStmt(Self, SubStmt);
11468 }
11469}
11470
11471void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11472 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11473 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11474 SearchForReturnInStmt(*this, Handler);
11475 }
11476}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011477
David Blaikie299adab2013-01-18 23:03:15 +000011478bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011479 const CXXMethodDecl *Old) {
11480 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11481 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11482
11483 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11484
11485 // If the calling conventions match, everything is fine
11486 if (NewCC == OldCC)
11487 return false;
11488
11489 // If either of the calling conventions are set to "default", we need to pick
11490 // something more sensible based on the target. This supports code where the
11491 // one method explicitly sets thiscall, and another has no explicit calling
11492 // convention.
11493 CallingConv Default =
11494 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11495 if (NewCC == CC_Default)
11496 NewCC = Default;
11497 if (OldCC == CC_Default)
11498 OldCC = Default;
11499
11500 // If the calling conventions still don't match, then report the error
11501 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011502 Diag(New->getLocation(),
11503 diag::err_conflicting_overriding_cc_attributes)
11504 << New->getDeclName() << New->getType() << Old->getType();
11505 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11506 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011507 }
11508
11509 return false;
11510}
11511
Mike Stump1eb44332009-09-09 15:08:12 +000011512bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011513 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011514 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11515 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011516
Chandler Carruth73857792010-02-15 11:53:20 +000011517 if (Context.hasSameType(NewTy, OldTy) ||
11518 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011519 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011520
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011521 // Check if the return types are covariant
11522 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011523
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011524 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011525 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11526 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011527 NewClassTy = NewPT->getPointeeType();
11528 OldClassTy = OldPT->getPointeeType();
11529 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011530 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11531 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11532 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11533 NewClassTy = NewRT->getPointeeType();
11534 OldClassTy = OldRT->getPointeeType();
11535 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011536 }
11537 }
Mike Stump1eb44332009-09-09 15:08:12 +000011538
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011539 // The return types aren't either both pointers or references to a class type.
11540 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011541 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011542 diag::err_different_return_type_for_overriding_virtual_function)
11543 << New->getDeclName() << NewTy << OldTy;
11544 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011545
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011546 return true;
11547 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011548
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011549 // C++ [class.virtual]p6:
11550 // If the return type of D::f differs from the return type of B::f, the
11551 // class type in the return type of D::f shall be complete at the point of
11552 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011553 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11554 if (!RT->isBeingDefined() &&
11555 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011556 diag::err_covariant_return_incomplete,
11557 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011558 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011559 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011560
Douglas Gregora4923eb2009-11-16 21:35:15 +000011561 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011562 // Check if the new class derives from the old class.
11563 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11564 Diag(New->getLocation(),
11565 diag::err_covariant_return_not_derived)
11566 << New->getDeclName() << NewTy << OldTy;
11567 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11568 return true;
11569 }
Mike Stump1eb44332009-09-09 15:08:12 +000011570
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011571 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011572 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011573 diag::err_covariant_return_inaccessible_base,
11574 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11575 // FIXME: Should this point to the return type?
11576 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011577 // FIXME: this note won't trigger for delayed access control
11578 // diagnostics, and it's impossible to get an undelayed error
11579 // here from access control during the original parse because
11580 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011581 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11582 return true;
11583 }
11584 }
Mike Stump1eb44332009-09-09 15:08:12 +000011585
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011586 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011587 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011588 Diag(New->getLocation(),
11589 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011590 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011591 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11592 return true;
11593 };
Mike Stump1eb44332009-09-09 15:08:12 +000011594
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011595
11596 // The new class type must have the same or less qualifiers as the old type.
11597 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11598 Diag(New->getLocation(),
11599 diag::err_covariant_return_type_class_type_more_qualified)
11600 << New->getDeclName() << NewTy << OldTy;
11601 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11602 return true;
11603 };
Mike Stump1eb44332009-09-09 15:08:12 +000011604
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011605 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011606}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011607
Douglas Gregor4ba31362009-12-01 17:24:26 +000011608/// \brief Mark the given method pure.
11609///
11610/// \param Method the method to be marked pure.
11611///
11612/// \param InitRange the source range that covers the "0" initializer.
11613bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011614 SourceLocation EndLoc = InitRange.getEnd();
11615 if (EndLoc.isValid())
11616 Method->setRangeEnd(EndLoc);
11617
Douglas Gregor4ba31362009-12-01 17:24:26 +000011618 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11619 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011620 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011621 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011622
11623 if (!Method->isInvalidDecl())
11624 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11625 << Method->getDeclName() << InitRange;
11626 return true;
11627}
11628
Douglas Gregor552e2992012-02-21 02:22:07 +000011629/// \brief Determine whether the given declaration is a static data member.
11630static bool isStaticDataMember(Decl *D) {
11631 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11632 if (!Var)
11633 return false;
11634
11635 return Var->isStaticDataMember();
11636}
John McCall731ad842009-12-19 09:28:58 +000011637/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11638/// an initializer for the out-of-line declaration 'Dcl'. The scope
11639/// is a fresh scope pushed for just this purpose.
11640///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011641/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11642/// static data member of class X, names should be looked up in the scope of
11643/// class X.
John McCalld226f652010-08-21 09:40:31 +000011644void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011645 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011646 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011647
John McCall731ad842009-12-19 09:28:58 +000011648 // We should only get called for declarations with scope specifiers, like:
11649 // int foo::bar;
11650 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011651 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011652
11653 // If we are parsing the initializer for a static data member, push a
11654 // new expression evaluation context that is associated with this static
11655 // data member.
11656 if (isStaticDataMember(D))
11657 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011658}
11659
11660/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011661/// initializer for the out-of-line declaration 'D'.
11662void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011663 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011664 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011665
Douglas Gregor552e2992012-02-21 02:22:07 +000011666 if (isStaticDataMember(D))
11667 PopExpressionEvaluationContext();
11668
John McCall731ad842009-12-19 09:28:58 +000011669 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011670 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011671}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011672
11673/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11674/// C++ if/switch/while/for statement.
11675/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011676DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011677 // C++ 6.4p2:
11678 // The declarator shall not specify a function or an array.
11679 // The type-specifier-seq shall not contain typedef and shall not declare a
11680 // new class or enumeration.
11681 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11682 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011683
11684 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011685 if (!Dcl)
11686 return true;
11687
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011688 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11689 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011690 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011691 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011692 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011693
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011694 return Dcl;
11695}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011696
Douglas Gregordfe65432011-07-28 19:11:31 +000011697void Sema::LoadExternalVTableUses() {
11698 if (!ExternalSource)
11699 return;
11700
11701 SmallVector<ExternalVTableUse, 4> VTables;
11702 ExternalSource->ReadUsedVTables(VTables);
11703 SmallVector<VTableUse, 4> NewUses;
11704 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11705 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11706 = VTablesUsed.find(VTables[I].Record);
11707 // Even if a definition wasn't required before, it may be required now.
11708 if (Pos != VTablesUsed.end()) {
11709 if (!Pos->second && VTables[I].DefinitionRequired)
11710 Pos->second = true;
11711 continue;
11712 }
11713
11714 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11715 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11716 }
11717
11718 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11719}
11720
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011721void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11722 bool DefinitionRequired) {
11723 // Ignore any vtable uses in unevaluated operands or for classes that do
11724 // not have a vtable.
11725 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000011726 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011727 return;
11728
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011729 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011730 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011731 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11732 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11733 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11734 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011735 // If we already had an entry, check to see if we are promoting this vtable
11736 // to required a definition. If so, we need to reappend to the VTableUses
11737 // list, since we may have already processed the first entry.
11738 if (DefinitionRequired && !Pos.first->second) {
11739 Pos.first->second = true;
11740 } else {
11741 // Otherwise, we can early exit.
11742 return;
11743 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011744 }
11745
11746 // Local classes need to have their virtual members marked
11747 // immediately. For all other classes, we mark their virtual members
11748 // at the end of the translation unit.
11749 if (Class->isLocalClass())
11750 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011751 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011752 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011753}
11754
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011755bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011756 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011757 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011758 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011759
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011760 // Note: The VTableUses vector could grow as a result of marking
11761 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011762 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011763 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011764 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011765 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011766 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011767 if (!Class)
11768 continue;
11769
11770 SourceLocation Loc = VTableUses[I].second;
11771
Richard Smithb9d0b762012-07-27 04:22:15 +000011772 bool DefineVTable = true;
11773
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011774 // If this class has a key function, but that key function is
11775 // defined in another translation unit, we don't need to emit the
11776 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011777 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011778 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011779 switch (KeyFunction->getTemplateSpecializationKind()) {
11780 case TSK_Undeclared:
11781 case TSK_ExplicitSpecialization:
11782 case TSK_ExplicitInstantiationDeclaration:
11783 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011784 DefineVTable = false;
11785 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011786
11787 case TSK_ExplicitInstantiationDefinition:
11788 case TSK_ImplicitInstantiation:
11789 // We will be instantiating the key function.
11790 break;
11791 }
11792 } else if (!KeyFunction) {
11793 // If we have a class with no key function that is the subject
11794 // of an explicit instantiation declaration, suppress the
11795 // vtable; it will live with the explicit instantiation
11796 // definition.
11797 bool IsExplicitInstantiationDeclaration
11798 = Class->getTemplateSpecializationKind()
11799 == TSK_ExplicitInstantiationDeclaration;
11800 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11801 REnd = Class->redecls_end();
11802 R != REnd; ++R) {
11803 TemplateSpecializationKind TSK
11804 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11805 if (TSK == TSK_ExplicitInstantiationDeclaration)
11806 IsExplicitInstantiationDeclaration = true;
11807 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11808 IsExplicitInstantiationDeclaration = false;
11809 break;
11810 }
11811 }
11812
11813 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011814 DefineVTable = false;
11815 }
11816
11817 // The exception specifications for all virtual members may be needed even
11818 // if we are not providing an authoritative form of the vtable in this TU.
11819 // We may choose to emit it available_externally anyway.
11820 if (!DefineVTable) {
11821 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11822 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011823 }
11824
11825 // Mark all of the virtual members of this class as referenced, so
11826 // that we can build a vtable. Then, tell the AST consumer that a
11827 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011828 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011829 MarkVirtualMembersReferenced(Loc, Class);
11830 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11831 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11832
11833 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000011834 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011835 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011836 const FunctionDecl *KeyFunctionDef = 0;
11837 if (!KeyFunction ||
11838 (KeyFunction->hasBody(KeyFunctionDef) &&
11839 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011840 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11841 TSK_ExplicitInstantiationDefinition
11842 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11843 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011844 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011845 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011846 VTableUses.clear();
11847
Douglas Gregor78844032011-04-22 22:25:37 +000011848 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011849}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011850
Richard Smithb9d0b762012-07-27 04:22:15 +000011851void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11852 const CXXRecordDecl *RD) {
11853 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11854 E = RD->method_end(); I != E; ++I)
11855 if ((*I)->isVirtual() && !(*I)->isPure())
11856 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11857}
11858
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011859void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11860 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011861 // Mark all functions which will appear in RD's vtable as used.
11862 CXXFinalOverriderMap FinalOverriders;
11863 RD->getFinalOverriders(FinalOverriders);
11864 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11865 E = FinalOverriders.end();
11866 I != E; ++I) {
11867 for (OverridingMethods::const_iterator OI = I->second.begin(),
11868 OE = I->second.end();
11869 OI != OE; ++OI) {
11870 assert(OI->second.size() > 0 && "no final overrider");
11871 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011872
Richard Smithff817f72012-07-07 06:59:51 +000011873 // C++ [basic.def.odr]p2:
11874 // [...] A virtual member function is used if it is not pure. [...]
11875 if (!Overrider->isPure())
11876 MarkFunctionReferenced(Loc, Overrider);
11877 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011878 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011879
11880 // Only classes that have virtual bases need a VTT.
11881 if (RD->getNumVBases() == 0)
11882 return;
11883
11884 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11885 e = RD->bases_end(); i != e; ++i) {
11886 const CXXRecordDecl *Base =
11887 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011888 if (Base->getNumVBases() == 0)
11889 continue;
11890 MarkVirtualMembersReferenced(Loc, Base);
11891 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011892}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011893
11894/// SetIvarInitializers - This routine builds initialization ASTs for the
11895/// Objective-C implementation whose ivars need be initialized.
11896void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011897 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011898 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011899 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011900 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011901 CollectIvarsToConstructOrDestruct(OID, ivars);
11902 if (ivars.empty())
11903 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011904 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011905 for (unsigned i = 0; i < ivars.size(); i++) {
11906 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011907 if (Field->isInvalidDecl())
11908 continue;
11909
Sean Huntcbb67482011-01-08 20:30:50 +000011910 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011911 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11912 InitializationKind InitKind =
11913 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000011914
11915 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
11916 ExprResult MemberInit =
11917 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000011918 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011919 // Note, MemberInit could actually come back empty if no initialization
11920 // is required (e.g., because it would call a trivial default constructor)
11921 if (!MemberInit.get() || MemberInit.isInvalid())
11922 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011923
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011924 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011925 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11926 SourceLocation(),
11927 MemberInit.takeAs<Expr>(),
11928 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011929 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011930
11931 // Be sure that the destructor is accessible and is marked as referenced.
11932 if (const RecordType *RecordTy
11933 = Context.getBaseElementType(Field->getType())
11934 ->getAs<RecordType>()) {
11935 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011936 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011937 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011938 CheckDestructorAccess(Field->getLocation(), Destructor,
11939 PDiag(diag::err_access_dtor_ivar)
11940 << Context.getBaseElementType(Field->getType()));
11941 }
11942 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011943 }
11944 ObjCImplementation->setIvarInitializers(Context,
11945 AllToInit.data(), AllToInit.size());
11946 }
11947}
Sean Huntfe57eef2011-05-04 05:57:24 +000011948
Sean Huntebcbe1d2011-05-04 23:29:54 +000011949static
11950void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11951 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11952 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11953 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11954 Sema &S) {
11955 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11956 CE = Current.end();
11957 if (Ctor->isInvalidDecl())
11958 return;
11959
Richard Smitha8eaf002012-08-23 06:16:52 +000011960 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11961
11962 // Target may not be determinable yet, for instance if this is a dependent
11963 // call in an uninstantiated template.
11964 if (Target) {
11965 const FunctionDecl *FNTarget = 0;
11966 (void)Target->hasBody(FNTarget);
11967 Target = const_cast<CXXConstructorDecl*>(
11968 cast_or_null<CXXConstructorDecl>(FNTarget));
11969 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011970
11971 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11972 // Avoid dereferencing a null pointer here.
11973 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11974
11975 if (!Current.insert(Canonical))
11976 return;
11977
11978 // We know that beyond here, we aren't chaining into a cycle.
11979 if (!Target || !Target->isDelegatingConstructor() ||
11980 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11981 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11982 Valid.insert(*CI);
11983 Current.clear();
11984 // We've hit a cycle.
11985 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11986 Current.count(TCanonical)) {
11987 // If we haven't diagnosed this cycle yet, do so now.
11988 if (!Invalid.count(TCanonical)) {
11989 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011990 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011991 << Ctor;
11992
Richard Smitha8eaf002012-08-23 06:16:52 +000011993 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011994 if (TCanonical != Canonical)
11995 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11996
11997 CXXConstructorDecl *C = Target;
11998 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011999 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012000 (void)C->getTargetConstructor()->hasBody(FNTarget);
12001 assert(FNTarget && "Ctor cycle through bodiless function");
12002
Richard Smitha8eaf002012-08-23 06:16:52 +000012003 C = const_cast<CXXConstructorDecl*>(
12004 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012005 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12006 }
12007 }
12008
12009 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12010 Invalid.insert(*CI);
12011 Current.clear();
12012 } else {
12013 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12014 }
12015}
12016
12017
Sean Huntfe57eef2011-05-04 05:57:24 +000012018void Sema::CheckDelegatingCtorCycles() {
12019 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12020
Sean Huntebcbe1d2011-05-04 23:29:54 +000012021 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12022 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000012023
Douglas Gregor0129b562011-07-27 21:57:17 +000012024 for (DelegatingCtorDeclsType::iterator
12025 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012026 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012027 I != E; ++I)
12028 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012029
12030 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
12031 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012032}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012033
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012034namespace {
12035 /// \brief AST visitor that finds references to the 'this' expression.
12036 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12037 Sema &S;
12038
12039 public:
12040 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12041
12042 bool VisitCXXThisExpr(CXXThisExpr *E) {
12043 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12044 << E->isImplicit();
12045 return false;
12046 }
12047 };
12048}
12049
12050bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12051 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12052 if (!TSInfo)
12053 return false;
12054
12055 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012056 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012057 if (!ProtoTL)
12058 return false;
12059
12060 // C++11 [expr.prim.general]p3:
12061 // [The expression this] shall not appear before the optional
12062 // cv-qualifier-seq and it shall not appear within the declaration of a
12063 // static member function (although its type and value category are defined
12064 // within a static member function as they are within a non-static member
12065 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012066 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012067 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012068 FindCXXThisExpr Finder(*this);
12069
12070 // If the return type came after the cv-qualifier-seq, check it now.
12071 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012072 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012073 return true;
12074
12075 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012076 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12077 return true;
12078
12079 return checkThisInStaticMemberFunctionAttributes(Method);
12080}
12081
12082bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12083 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12084 if (!TSInfo)
12085 return false;
12086
12087 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012088 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012089 if (!ProtoTL)
12090 return false;
12091
David Blaikie39e6ab42013-02-18 22:06:02 +000012092 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012093 FindCXXThisExpr Finder(*this);
12094
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012095 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012096 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012097 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012098 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012099 case EST_DynamicNone:
12100 case EST_MSAny:
12101 case EST_None:
12102 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012103
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012104 case EST_ComputedNoexcept:
12105 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12106 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012107
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012108 case EST_Dynamic:
12109 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012110 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012111 E != EEnd; ++E) {
12112 if (!Finder.TraverseType(*E))
12113 return true;
12114 }
12115 break;
12116 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012117
12118 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012119}
12120
12121bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12122 FindCXXThisExpr Finder(*this);
12123
12124 // Check attributes.
12125 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12126 A != AEnd; ++A) {
12127 // FIXME: This should be emitted by tblgen.
12128 Expr *Arg = 0;
12129 ArrayRef<Expr *> Args;
12130 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12131 Arg = G->getArg();
12132 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12133 Arg = G->getArg();
12134 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12135 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12136 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12137 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12138 else if (ExclusiveLockFunctionAttr *ELF
12139 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12140 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12141 else if (SharedLockFunctionAttr *SLF
12142 = dyn_cast<SharedLockFunctionAttr>(*A))
12143 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12144 else if (ExclusiveTrylockFunctionAttr *ETLF
12145 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12146 Arg = ETLF->getSuccessValue();
12147 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12148 } else if (SharedTrylockFunctionAttr *STLF
12149 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12150 Arg = STLF->getSuccessValue();
12151 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12152 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12153 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12154 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12155 Arg = LR->getArg();
12156 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12157 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12158 else if (ExclusiveLocksRequiredAttr *ELR
12159 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12160 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12161 else if (SharedLocksRequiredAttr *SLR
12162 = dyn_cast<SharedLocksRequiredAttr>(*A))
12163 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12164
12165 if (Arg && !Finder.TraverseStmt(Arg))
12166 return true;
12167
12168 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12169 if (!Finder.TraverseStmt(Args[I]))
12170 return true;
12171 }
12172 }
12173
12174 return false;
12175}
12176
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012177void
12178Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12179 ArrayRef<ParsedType> DynamicExceptions,
12180 ArrayRef<SourceRange> DynamicExceptionRanges,
12181 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012182 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012183 FunctionProtoType::ExtProtoInfo &EPI) {
12184 Exceptions.clear();
12185 EPI.ExceptionSpecType = EST;
12186 if (EST == EST_Dynamic) {
12187 Exceptions.reserve(DynamicExceptions.size());
12188 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12189 // FIXME: Preserve type source info.
12190 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12191
12192 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12193 collectUnexpandedParameterPacks(ET, Unexpanded);
12194 if (!Unexpanded.empty()) {
12195 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12196 UPPC_ExceptionType,
12197 Unexpanded);
12198 continue;
12199 }
12200
12201 // Check that the type is valid for an exception spec, and
12202 // drop it if not.
12203 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12204 Exceptions.push_back(ET);
12205 }
12206 EPI.NumExceptions = Exceptions.size();
12207 EPI.Exceptions = Exceptions.data();
12208 return;
12209 }
12210
12211 if (EST == EST_ComputedNoexcept) {
12212 // If an error occurred, there's no expression here.
12213 if (NoexceptExpr) {
12214 assert((NoexceptExpr->isTypeDependent() ||
12215 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12216 Context.BoolTy) &&
12217 "Parser should have made sure that the expression is boolean");
12218 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12219 EPI.ExceptionSpecType = EST_BasicNoexcept;
12220 return;
12221 }
12222
12223 if (!NoexceptExpr->isValueDependent())
12224 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012225 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012226 /*AllowFold*/ false).take();
12227 EPI.NoexceptExpr = NoexceptExpr;
12228 }
12229 return;
12230 }
12231}
12232
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012233/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12234Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12235 // Implicitly declared functions (e.g. copy constructors) are
12236 // __host__ __device__
12237 if (D->isImplicit())
12238 return CFT_HostDevice;
12239
12240 if (D->hasAttr<CUDAGlobalAttr>())
12241 return CFT_Global;
12242
12243 if (D->hasAttr<CUDADeviceAttr>()) {
12244 if (D->hasAttr<CUDAHostAttr>())
12245 return CFT_HostDevice;
12246 else
12247 return CFT_Device;
12248 }
12249
12250 return CFT_Host;
12251}
12252
12253bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12254 CUDAFunctionTarget CalleeTarget) {
12255 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12256 // Callable from the device only."
12257 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12258 return true;
12259
12260 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12261 // Callable from the host only."
12262 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12263 // Callable from the host only."
12264 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12265 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12266 return true;
12267
12268 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12269 return true;
12270
12271 return false;
12272}
John McCall76da55d2013-04-16 07:28:30 +000012273
12274/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12275///
12276MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12277 SourceLocation DeclStart,
12278 Declarator &D, Expr *BitWidth,
12279 InClassInitStyle InitStyle,
12280 AccessSpecifier AS,
12281 AttributeList *MSPropertyAttr) {
12282 IdentifierInfo *II = D.getIdentifier();
12283 if (!II) {
12284 Diag(DeclStart, diag::err_anonymous_property);
12285 return NULL;
12286 }
12287 SourceLocation Loc = D.getIdentifierLoc();
12288
12289 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12290 QualType T = TInfo->getType();
12291 if (getLangOpts().CPlusPlus) {
12292 CheckExtraCXXDefaultArguments(D);
12293
12294 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12295 UPPC_DataMemberType)) {
12296 D.setInvalidType();
12297 T = Context.IntTy;
12298 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12299 }
12300 }
12301
12302 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12303
12304 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12305 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12306 diag::err_invalid_thread)
12307 << DeclSpec::getSpecifierName(TSCS);
12308
12309 // Check to see if this name was declared as a member previously
12310 NamedDecl *PrevDecl = 0;
12311 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12312 LookupName(Previous, S);
12313 switch (Previous.getResultKind()) {
12314 case LookupResult::Found:
12315 case LookupResult::FoundUnresolvedValue:
12316 PrevDecl = Previous.getAsSingle<NamedDecl>();
12317 break;
12318
12319 case LookupResult::FoundOverloaded:
12320 PrevDecl = Previous.getRepresentativeDecl();
12321 break;
12322
12323 case LookupResult::NotFound:
12324 case LookupResult::NotFoundInCurrentInstantiation:
12325 case LookupResult::Ambiguous:
12326 break;
12327 }
12328
12329 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12330 // Maybe we will complain about the shadowed template parameter.
12331 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12332 // Just pretend that we didn't see the previous declaration.
12333 PrevDecl = 0;
12334 }
12335
12336 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12337 PrevDecl = 0;
12338
12339 SourceLocation TSSL = D.getLocStart();
12340 MSPropertyDecl *NewPD;
12341 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12342 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12343 II, T, TInfo, TSSL,
12344 Data.GetterId, Data.SetterId);
12345 ProcessDeclAttributes(TUScope, NewPD, D);
12346 NewPD->setAccess(AS);
12347
12348 if (NewPD->isInvalidDecl())
12349 Record->setInvalidDecl();
12350
12351 if (D.getDeclSpec().isModulePrivateSpecified())
12352 NewPD->setModulePrivate();
12353
12354 if (NewPD->isInvalidDecl() && PrevDecl) {
12355 // Don't introduce NewFD into scope; there's already something
12356 // with the same name in the same scope.
12357 } else if (II) {
12358 PushOnScopeChains(NewPD, S);
12359 } else
12360 Record->addDecl(NewPD);
12361
12362 return NewPD;
12363}