blob: 2f9f9824fef480c933cb2c7e966ab90f97bcf534 [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"
Faisal Valifad9e132013-09-26 19:54:12 +000017#include "clang/AST/ASTLambda.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.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"
Richard Smith4ac537b2013-07-23 08:14:48 +000030#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000040#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000041#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000042#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000043
44using namespace clang;
45
Chris Lattner8123a952008-04-10 02:22:51 +000046//===----------------------------------------------------------------------===//
47// CheckDefaultArgumentVisitor
48//===----------------------------------------------------------------------===//
49
Chris Lattner9e979552008-04-12 23:52:44 +000050namespace {
51 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
52 /// the default argument of a parameter to determine whether it
53 /// contains any ill-formed subexpressions. For example, this will
54 /// diagnose the use of local variables or parameters within the
55 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000056 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000057 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000058 Expr *DefaultArg;
59 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000060
Chris Lattner9e979552008-04-12 23:52:44 +000061 public:
Mike Stump1eb44332009-09-09 15:08:12 +000062 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000063 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000064
Chris Lattner9e979552008-04-12 23:52:44 +000065 bool VisitExpr(Expr *Node);
66 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000067 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000068 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000069 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000070 };
Chris Lattner8123a952008-04-10 02:22:51 +000071
Chris Lattner9e979552008-04-12 23:52:44 +000072 /// VisitExpr - Visit all of the children of this expression.
73 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
74 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000075 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000076 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000077 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000078 }
79
Chris Lattner9e979552008-04-12 23:52:44 +000080 /// VisitDeclRefExpr - Visit a reference to a declaration, to
81 /// determine whether this declaration can be used in the default
82 /// argument expression.
83 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000084 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000085 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
86 // C++ [dcl.fct.default]p9
87 // Default arguments are evaluated each time the function is
88 // called. The order of evaluation of function arguments is
89 // unspecified. Consequently, parameters of a function shall not
90 // be used in default argument expressions, even if they are not
91 // evaluated. Parameters of a function declared before a default
92 // argument expression are in scope and can hide namespace and
93 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000094 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000096 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000097 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000098 // C++ [dcl.fct.default]p7
99 // Local variables shall not be used in default argument
100 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000101 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000102 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000103 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000104 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000105 }
Chris Lattner8123a952008-04-10 02:22:51 +0000106
Douglas Gregor3996f232008-11-04 13:41:56 +0000107 return false;
108 }
Chris Lattner9e979552008-04-12 23:52:44 +0000109
Douglas Gregor796da182008-11-04 14:32:21 +0000110 /// VisitCXXThisExpr - Visit a C++ "this" expression.
111 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
112 // C++ [dcl.fct.default]p8:
113 // The keyword this shall not be used in a default argument of a
114 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000115 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000116 diag::err_param_default_argument_references_this)
117 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000118 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000119
John McCall045d2522013-04-09 01:56:28 +0000120 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
121 bool Invalid = false;
122 for (PseudoObjectExpr::semantics_iterator
123 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
124 Expr *E = *i;
125
126 // Look through bindings.
127 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
128 E = OVE->getSourceExpr();
129 assert(E && "pseudo-object binding without source expression?");
130 }
131
132 Invalid |= Visit(E);
133 }
134 return Invalid;
135 }
136
Douglas Gregorf0459f82012-02-10 23:30:22 +0000137 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
138 // C++11 [expr.lambda.prim]p13:
139 // A lambda-expression appearing in a default argument shall not
140 // implicitly or explicitly capture any entity.
141 if (Lambda->capture_begin() == Lambda->capture_end())
142 return false;
143
144 return S->Diag(Lambda->getLocStart(),
145 diag::err_lambda_capture_default_arg);
146 }
Chris Lattner8123a952008-04-10 02:22:51 +0000147}
148
Richard Smith0b0ca472013-04-10 06:11:48 +0000149void
150Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
151 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000152 // If we have an MSAny spec already, don't bother.
153 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000154 return;
155
156 const FunctionProtoType *Proto
157 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000158 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
159 if (!Proto)
160 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000161
162 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
163
164 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000165 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000166 ClearExceptions();
167 ComputedEST = EST;
168 return;
169 }
170
Richard Smith7a614d82011-06-11 17:19:42 +0000171 // FIXME: If the call to this decl is using any of its default arguments, we
172 // need to search them for potentially-throwing calls.
173
Sean Hunt001cad92011-05-10 00:49:42 +0000174 // If this function has a basic noexcept, it doesn't affect the outcome.
175 if (EST == EST_BasicNoexcept)
176 return;
177
178 // If we have a throw-all spec at this point, ignore the function.
179 if (ComputedEST == EST_None)
180 return;
181
182 // If we're still at noexcept(true) and there's a nothrow() callee,
183 // change to that specification.
184 if (EST == EST_DynamicNone) {
185 if (ComputedEST == EST_BasicNoexcept)
186 ComputedEST = EST_DynamicNone;
187 return;
188 }
189
190 // Check out noexcept specs.
191 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000192 FunctionProtoType::NoexceptResult NR =
193 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000194 assert(NR != FunctionProtoType::NR_NoNoexcept &&
195 "Must have noexcept result for EST_ComputedNoexcept.");
196 assert(NR != FunctionProtoType::NR_Dependent &&
197 "Should not generate implicit declarations for dependent cases, "
198 "and don't know how to handle them anyway.");
199
200 // noexcept(false) -> no spec on the new function
201 if (NR == FunctionProtoType::NR_Throw) {
202 ClearExceptions();
203 ComputedEST = EST_None;
204 }
205 // noexcept(true) won't change anything either.
206 return;
207 }
208
209 assert(EST == EST_Dynamic && "EST case not considered earlier.");
210 assert(ComputedEST != EST_None &&
211 "Shouldn't collect exceptions when throw-all is guaranteed.");
212 ComputedEST = EST_Dynamic;
213 // Record the exceptions in this function's exception specification.
Stephen Hines651f13c2014-04-23 16:59:28 -0700214 for (const auto &E : Proto->exceptions())
215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)))
216 Exceptions.push_back(E);
Sean Hunt001cad92011-05-10 00:49:42 +0000217}
218
Richard Smith7a614d82011-06-11 17:19:42 +0000219void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000220 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000221 return;
222
223 // FIXME:
224 //
225 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000226 // [An] implicit exception-specification specifies the type-id T if and
227 // only if T is allowed by the exception-specification of a function directly
228 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000229 // function it directly invokes allows all exceptions, and f shall allow no
230 // exceptions if every function it directly invokes allows no exceptions.
231 //
232 // Note in particular that if an implicit exception-specification is generated
233 // for a function containing a throw-expression, that specification can still
234 // be noexcept(true).
235 //
236 // Note also that 'directly invoked' is not defined in the standard, and there
237 // is no indication that we should only consider potentially-evaluated calls.
238 //
239 // Ultimately we should implement the intent of the standard: the exception
240 // specification should be the set of exceptions which can be thrown by the
241 // implicit definition. For now, we assume that any non-nothrow expression can
242 // throw any exception.
243
Richard Smithe6975e92012-04-17 00:58:00 +0000244 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000245 ComputedEST = EST_None;
246}
247
Anders Carlssoned961f92009-08-25 02:29:20 +0000248bool
John McCall9ae2f072010-08-23 23:25:46 +0000249Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000250 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000251 if (RequireCompleteType(Param->getLocation(), Param->getType(),
252 diag::err_typecheck_decl_incomplete_type)) {
253 Param->setInvalidDecl();
254 return true;
255 }
256
Anders Carlssoned961f92009-08-25 02:29:20 +0000257 // C++ [dcl.fct.default]p5
258 // A default argument expression is implicitly converted (clause
259 // 4) to the parameter type. The default argument expression has
260 // the same semantic constraints as the initializer expression in
261 // a declaration of a variable of the parameter type, using the
262 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000267 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000269 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000270 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000271 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000272
Richard Smith6c3af3d2013-01-17 01:17:56 +0000273 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000274 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000275
Anders Carlssoned961f92009-08-25 02:29:20 +0000276 // Okay: add the default argument to the parameter
277 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000279 // We have already instantiated this parameter; provide each of the
280 // instantiations with the uninstantiated default argument.
281 UnparsedDefaultArgInstantiationsMap::iterator InstPos
282 = UnparsedDefaultArgInstantiations.find(Param);
283 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286
287 // We're done tracking this parameter's instantiations.
288 UnparsedDefaultArgInstantiations.erase(InstPos);
289 }
290
Anders Carlsson9351c172009-08-25 03:18:48 +0000291 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000292}
293
Chris Lattner8123a952008-04-10 02:22:51 +0000294/// ActOnParamDefaultArgument - Check whether the default argument
295/// provided for a function parameter is well-formed. If so, attach it
296/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000297void
John McCalld226f652010-08-21 09:40:31 +0000298Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000299 Expr *DefaultArg) {
300 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000301 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000302
John McCalld226f652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000304 UnparsedDefaultArgLocs.erase(Param);
305
Chris Lattner3d1cee32008-04-08 05:04:30 +0000306 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000307 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000308 Diag(EqualLoc, diag::err_param_default_argument)
309 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000310 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000311 return;
312 }
313
Douglas Gregor6f526752010-12-16 08:48:57 +0000314 // Check for unexpanded parameter packs.
315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316 Param->setInvalidDecl();
317 return;
318 }
319
Anders Carlsson66e30672009-08-25 01:02:06 +0000320 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000321 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
322 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000323 Param->setInvalidDecl();
324 return;
325 }
Mike Stump1eb44332009-09-09 15:08:12 +0000326
John McCall9ae2f072010-08-23 23:25:46 +0000327 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000328}
329
Douglas Gregor61366e92008-12-24 00:01:03 +0000330/// ActOnParamUnparsedDefaultArgument - We've seen a default
331/// argument for a function parameter, but we can't parse it yet
332/// because we're inside a class definition. Note that this default
333/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000334void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000335 SourceLocation EqualLoc,
336 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000337 if (!param)
338 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000339
John McCalld226f652010-08-21 09:40:31 +0000340 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +0000341 Param->setUnparsedDefaultArg();
Anders Carlsson5e300d12009-06-12 16:51:40 +0000342 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000343}
344
Douglas Gregor72b505b2008-12-16 21:30:33 +0000345/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
346/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000347void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000348 if (!param)
349 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000350
John McCalld226f652010-08-21 09:40:31 +0000351 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000352 Param->setInvalidDecl();
Anders Carlsson5e300d12009-06-12 16:51:40 +0000353 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000354}
355
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000356/// CheckExtraCXXDefaultArguments - Check for any extra default
357/// arguments in the declarator, which is not a function declaration
358/// or definition and therefore is not permitted to have default
359/// arguments. This routine should be invoked for every declarator
360/// that is not a function declaration or definition.
361void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
362 // C++ [dcl.fct.default]p3
363 // A default argument expression shall be specified only in the
364 // parameter-declaration-clause of a function declaration or in a
365 // template-parameter (14.1). It shall not be specified for a
366 // parameter pack. If it is specified in a
367 // parameter-declaration-clause, it shall not occur within a
368 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000369 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000370 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000371 DeclaratorChunk &chunk = D.getTypeObject(i);
372 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000373 if (MightBeFunction) {
374 // This is a function declaration. It can have default arguments, but
375 // keep looking in case its return type is a function type with default
376 // arguments.
377 MightBeFunction = false;
378 continue;
379 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700380 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
381 ++argIdx) {
382 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000383 if (Param->hasUnparsedDefaultArg()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700384 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000385 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000386 << SourceRange((*Toks)[1].getLocation(),
387 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000388 delete Toks;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700389 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor61366e92008-12-24 00:01:03 +0000390 } else if (Param->getDefaultArg()) {
391 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
392 << Param->getDefaultArg()->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700393 Param->setDefaultArg(nullptr);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000394 }
395 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000396 } else if (chunk.Kind != DeclaratorChunk::Paren) {
397 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000398 }
399 }
400}
401
David Majnemerf6a144f2013-06-25 23:09:30 +0000402static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
403 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
404 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
405 if (!PVD->hasDefaultArg())
406 return false;
407 if (!PVD->hasInheritedDefaultArg())
408 return true;
409 }
410 return false;
411}
412
Craig Topper1a6eac82012-09-21 04:33:26 +0000413/// MergeCXXFunctionDecl - Merge two declarations of the same C++
414/// function, once we already know that they have the same
415/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
416/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000417bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
418 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000419 bool Invalid = false;
420
Chris Lattner3d1cee32008-04-08 05:04:30 +0000421 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000422 // For non-template functions, default arguments can be added in
423 // later declarations of a function in the same
424 // scope. Declarations in different scopes have completely
425 // distinct sets of default arguments. That is, declarations in
426 // inner scopes do not acquire default arguments from
427 // declarations in outer scopes, and vice versa. In a given
428 // function declaration, all parameters subsequent to a
429 // parameter with a default argument shall have default
430 // arguments supplied in this or previous declarations. A
431 // default argument shall not be redefined by a later
432 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000433 //
434 // C++ [dcl.fct.default]p6:
Richard Smitha41c97a2013-09-20 01:15:31 +0000435 // Except for member functions of class templates, the default arguments
436 // in a member function definition that appears outside of the class
437 // definition are added to the set of default arguments provided by the
Douglas Gregor6cc15182009-09-11 18:44:32 +0000438 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000439 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
440 ParmVarDecl *OldParam = Old->getParamDecl(p);
441 ParmVarDecl *NewParam = New->getParamDecl(p);
442
James Molloy9cda03f2012-03-13 08:55:35 +0000443 bool OldParamHasDfl = OldParam->hasDefaultArg();
444 bool NewParamHasDfl = NewParam->hasDefaultArg();
445
446 NamedDecl *ND = Old;
Richard Smitha41c97a2013-09-20 01:15:31 +0000447
448 // The declaration context corresponding to the scope is the semantic
449 // parent, unless this is a local function declaration, in which case
450 // it is that surrounding function.
451 DeclContext *ScopeDC = New->getLexicalDeclContext();
452 if (!ScopeDC->isFunctionOrMethod())
453 ScopeDC = New->getDeclContext();
454 if (S && !isDeclInScope(ND, ScopeDC, S) &&
455 !New->getDeclContext()->isRecord())
James Molloy9cda03f2012-03-13 08:55:35 +0000456 // Ignore default parameters of old decl if they are not in
Richard Smitha41c97a2013-09-20 01:15:31 +0000457 // the same scope and this is not an out-of-line definition of
458 // a member function.
James Molloy9cda03f2012-03-13 08:55:35 +0000459 OldParamHasDfl = false;
460
461 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000462
Francois Pichet8d051e02011-04-10 03:03:52 +0000463 unsigned DiagDefaultParamID =
464 diag::err_param_default_argument_redefinition;
465
466 // MSVC accepts that default parameters be redefined for member functions
467 // of template class. The new default parameter's value is ignored.
468 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000469 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000470 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
471 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000472 // Merge the old default argument into the new parameter.
473 NewParam->setHasInheritedDefaultArg();
474 if (OldParam->hasUninstantiatedDefaultArg())
475 NewParam->setUninstantiatedDefaultArg(
476 OldParam->getUninstantiatedDefaultArg());
477 else
478 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000479 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000480 Invalid = false;
481 }
482 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000483
Francois Pichet8cf90492011-04-10 04:58:30 +0000484 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
485 // hint here. Alternatively, we could walk the type-source information
486 // for NewParam to find the last source location in the type... but it
487 // isn't worth the effort right now. This is the kind of test case that
488 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000489 // int f(int);
490 // void g(int (*fp)(int) = f);
491 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000492 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000493 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000494
495 // Look for the function declaration where the default argument was
496 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000497 for (FunctionDecl *Older = Old->getPreviousDecl();
498 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000499 if (!Older->getParamDecl(p)->hasDefaultArg())
500 break;
501
502 OldParam = Older->getParamDecl(p);
503 }
504
505 Diag(OldParam->getLocation(), diag::note_previous_definition)
506 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000507 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000508 // Merge the old default argument into the new parameter.
509 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000510 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000511 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000512 if (OldParam->hasUninstantiatedDefaultArg())
513 NewParam->setUninstantiatedDefaultArg(
514 OldParam->getUninstantiatedDefaultArg());
515 else
John McCall3d6c1782010-05-04 01:53:42 +0000516 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000517 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000518 if (New->getDescribedFunctionTemplate()) {
519 // Paragraph 4, quoted above, only applies to non-template functions.
520 Diag(NewParam->getLocation(),
521 diag::err_param_default_argument_template_redecl)
522 << NewParam->getDefaultArgRange();
523 Diag(Old->getLocation(), diag::note_template_prev_declaration)
524 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000525 } else if (New->getTemplateSpecializationKind()
526 != TSK_ImplicitInstantiation &&
527 New->getTemplateSpecializationKind() != TSK_Undeclared) {
528 // C++ [temp.expr.spec]p21:
529 // Default function arguments shall not be specified in a declaration
530 // or a definition for one of the following explicit specializations:
531 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000532 // - the explicit specialization of a member function template;
533 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000534 // template where the class template specialization to which the
535 // member function specialization belongs is implicitly
536 // instantiated.
537 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
538 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
539 << New->getDeclName()
540 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000541 } else if (New->getDeclContext()->isDependentContext()) {
542 // C++ [dcl.fct.default]p6 (DR217):
543 // Default arguments for a member function of a class template shall
544 // be specified on the initial declaration of the member function
545 // within the class template.
546 //
547 // Reading the tea leaves a bit in DR217 and its reference to DR205
548 // leads me to the conclusion that one cannot add default function
549 // arguments for an out-of-line definition of a member function of a
550 // dependent type.
551 int WhichKind = 2;
552 if (CXXRecordDecl *Record
553 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
554 if (Record->getDescribedClassTemplate())
555 WhichKind = 0;
556 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
557 WhichKind = 1;
558 else
559 WhichKind = 2;
560 }
561
562 Diag(NewParam->getLocation(),
563 diag::err_param_default_argument_member_template_redecl)
564 << WhichKind
565 << NewParam->getDefaultArgRange();
566 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000567 }
568 }
569
Richard Smithb8abff62012-11-28 03:45:24 +0000570 // DR1344: If a default argument is added outside a class definition and that
571 // default argument makes the function a special member function, the program
572 // is ill-formed. This can only happen for constructors.
573 if (isa<CXXConstructorDecl>(New) &&
574 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
575 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
576 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
577 if (NewSM != OldSM) {
578 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
579 assert(NewParam->hasDefaultArg());
580 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
581 << NewParam->getDefaultArgRange() << NewSM;
582 Diag(Old->getLocation(), diag::note_previous_declaration);
583 }
584 }
585
Stephen Hines651f13c2014-04-23 16:59:28 -0700586 const FunctionDecl *Def;
Richard Smithff234882012-02-20 23:28:05 +0000587 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000588 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000589 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000590 if (New->isConstexpr() != Old->isConstexpr()) {
591 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
592 << New << New->isConstexpr();
593 Diag(Old->getLocation(), diag::note_previous_declaration);
594 Invalid = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700595 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
596 // C++11 [dcl.fcn.spec]p4:
597 // If the definition of a function appears in a translation unit before its
598 // first declaration as inline, the program is ill-formed.
599 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
600 Diag(Def->getLocation(), diag::note_previous_definition);
601 Invalid = true;
Richard Smith9f569cc2011-10-01 02:31:28 +0000602 }
603
David Majnemerf6a144f2013-06-25 23:09:30 +0000604 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumifd527a42013-07-17 17:57:52 +0000605 // argument expression, that declaration shall be a definition and shall be
David Majnemerf6a144f2013-06-25 23:09:30 +0000606 // the only declaration of the function or function template in the
607 // translation unit.
608 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
609 functionDeclHasDefaultArgument(Old)) {
610 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
611 Diag(Old->getLocation(), diag::note_previous_declaration);
612 Invalid = true;
613 }
614
Douglas Gregore13ad832010-02-12 07:32:17 +0000615 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000616 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000617
Douglas Gregorcda9c672009-02-16 17:45:42 +0000618 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000619}
620
Sebastian Redl60618fa2011-03-12 11:50:43 +0000621/// \brief Merge the exception specifications of two variable declarations.
622///
623/// This is called when there's a redeclaration of a VarDecl. The function
624/// checks if the redeclaration might have an exception specification and
625/// validates compatibility and merges the specs if necessary.
626void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
627 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000628 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000629 return;
630
631 assert(Context.hasSameType(New->getType(), Old->getType()) &&
632 "Should only be called if types are otherwise the same.");
633
634 QualType NewType = New->getType();
635 QualType OldType = Old->getType();
636
637 // We're only interested in pointers and references to functions, as well
638 // as pointers to member functions.
639 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
640 NewType = R->getPointeeType();
641 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
642 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
643 NewType = P->getPointeeType();
644 OldType = OldType->getAs<PointerType>()->getPointeeType();
645 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
646 NewType = M->getPointeeType();
647 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
648 }
649
650 if (!NewType->isFunctionProtoType())
651 return;
652
653 // There's lots of special cases for functions. For function pointers, system
654 // libraries are hopefully not as broken so that we don't need these
655 // workarounds.
656 if (CheckEquivalentExceptionSpec(
657 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
658 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
659 New->setInvalidDecl();
660 }
661}
662
Chris Lattner3d1cee32008-04-08 05:04:30 +0000663/// CheckCXXDefaultArguments - Verify that the default arguments for a
664/// function declaration are well-formed according to C++
665/// [dcl.fct.default].
666void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
667 unsigned NumParams = FD->getNumParams();
668 unsigned p;
669
670 // Find first parameter with a default argument
671 for (p = 0; p < NumParams; ++p) {
672 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000673 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000674 break;
675 }
676
677 // C++ [dcl.fct.default]p4:
678 // In a given function declaration, all parameters
679 // subsequent to a parameter with a default argument shall
680 // have default arguments supplied in this or previous
681 // declarations. A default argument shall not be redefined
682 // by a later declaration (not even to the same value).
683 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000684 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000685 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000686 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000687 if (Param->isInvalidDecl())
688 /* We already complained about this parameter. */;
689 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000690 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000691 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000692 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000693 else
Mike Stump1eb44332009-09-09 15:08:12 +0000694 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000695 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Chris Lattner3d1cee32008-04-08 05:04:30 +0000697 LastMissingDefaultArg = p;
698 }
699 }
700
701 if (LastMissingDefaultArg > 0) {
702 // Some default arguments were missing. Clear out all of the
703 // default arguments up to (and including) the last missing
704 // default argument, so that we leave the function parameters
705 // in a semantically valid state.
706 for (p = 0; p <= LastMissingDefaultArg; ++p) {
707 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000708 if (Param->hasDefaultArg()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700709 Param->setDefaultArg(nullptr);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000710 }
711 }
712 }
713}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000714
Richard Smith9f569cc2011-10-01 02:31:28 +0000715// CheckConstexprParameterTypes - Check whether a function's parameter types
716// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000717// diagnostic and return false.
718static bool CheckConstexprParameterTypes(Sema &SemaRef,
719 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000720 unsigned ArgIndex = 0;
721 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -0700722 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
723 e = FT->param_type_end();
724 i != e; ++i, ++ArgIndex) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000725 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
726 SourceLocation ParamLoc = PD->getLocation();
727 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000728 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000729 diag::err_constexpr_non_literal_param,
730 ArgIndex+1, PD->getSourceRange(),
731 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000732 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000733 }
Joao Matos17d35c32012-08-31 22:18:20 +0000734 return true;
735}
736
737/// \brief Get diagnostic %select index for tag kind for
738/// record diagnostic message.
739/// WARNING: Indexes apply to particular diagnostics only!
740///
741/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000742static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000743 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000744 case TTK_Struct: return 0;
745 case TTK_Interface: return 1;
746 case TTK_Class: return 2;
747 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000748 }
Joao Matos17d35c32012-08-31 22:18:20 +0000749}
750
751// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
752// the requirements of a constexpr function definition or a constexpr
753// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000754// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000755//
Richard Smith86c3ae42012-02-13 03:54:03 +0000756// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
757bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000758 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
759 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000760 // C++11 [dcl.constexpr]p4:
761 // The definition of a constexpr constructor shall satisfy the following
762 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000763 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000764 const CXXRecordDecl *RD = MD->getParent();
765 if (RD->getNumVBases()) {
766 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
767 << isa<CXXConstructorDecl>(NewFD)
768 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Stephen Hines651f13c2014-04-23 16:59:28 -0700769 for (const auto &I : RD->vbases())
770 Diag(I.getLocStart(),
771 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000772 return false;
773 }
Richard Smith35340502012-01-13 04:54:00 +0000774 }
775
776 if (!isa<CXXConstructorDecl>(NewFD)) {
777 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000778 // The definition of a constexpr function shall satisfy the following
779 // constraints:
780 // - it shall not be virtual;
781 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
782 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000783 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000784
Richard Smith86c3ae42012-02-13 03:54:03 +0000785 // If it's not obvious why this function is virtual, find an overridden
786 // function which uses the 'virtual' keyword.
787 const CXXMethodDecl *WrittenVirtual = Method;
788 while (!WrittenVirtual->isVirtualAsWritten())
789 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
790 if (WrittenVirtual != Method)
791 Diag(WrittenVirtual->getLocation(),
792 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000793 return false;
794 }
795
796 // - its return type shall be a literal type;
Stephen Hines651f13c2014-04-23 16:59:28 -0700797 QualType RT = NewFD->getReturnType();
Richard Smith9f569cc2011-10-01 02:31:28 +0000798 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000799 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000800 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000801 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000802 }
803
Richard Smith35340502012-01-13 04:54:00 +0000804 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000805 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000806 return false;
807
Richard Smith9f569cc2011-10-01 02:31:28 +0000808 return true;
809}
810
811/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000812/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000813///
Richard Smitha10b9782013-04-22 15:31:51 +0000814/// \return true if the body is OK (maybe only as an extension), false if we
815/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000816static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000817 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
818 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000819 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
820 // contain only
Stephen Hines651f13c2014-04-23 16:59:28 -0700821 for (const auto *DclIt : DS->decls()) {
822 switch (DclIt->getKind()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000823 case Decl::StaticAssert:
824 case Decl::Using:
825 case Decl::UsingShadow:
826 case Decl::UsingDirective:
827 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000828 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000829 // - static_assert-declarations
830 // - using-declarations,
831 // - using-directives,
832 continue;
833
834 case Decl::Typedef:
835 case Decl::TypeAlias: {
836 // - typedef declarations and alias-declarations that do not define
837 // classes or enumerations,
Stephen Hines651f13c2014-04-23 16:59:28 -0700838 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smith9f569cc2011-10-01 02:31:28 +0000839 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
840 // Don't allow variably-modified types in constexpr functions.
841 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
842 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
843 << TL.getSourceRange() << TL.getType()
844 << isa<CXXConstructorDecl>(Dcl);
845 return false;
846 }
847 continue;
848 }
849
850 case Decl::Enum:
851 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000852 // C++1y allows types to be defined, not just declared.
Stephen Hines651f13c2014-04-23 16:59:28 -0700853 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smitha10b9782013-04-22 15:31:51 +0000854 SemaRef.Diag(DS->getLocStart(),
855 SemaRef.getLangOpts().CPlusPlus1y
856 ? diag::warn_cxx11_compat_constexpr_type_definition
857 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000858 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000859 continue;
860
Richard Smitha10b9782013-04-22 15:31:51 +0000861 case Decl::EnumConstant:
862 case Decl::IndirectField:
863 case Decl::ParmVar:
864 // These can only appear with other declarations which are banned in
865 // C++11 and permitted in C++1y, so ignore them.
866 continue;
867
868 case Decl::Var: {
869 // C++1y [dcl.constexpr]p3 allows anything except:
870 // a definition of a variable of non-literal type or of static or
871 // thread storage duration or for which no initialization is performed.
Stephen Hines651f13c2014-04-23 16:59:28 -0700872 const auto *VD = cast<VarDecl>(DclIt);
Richard Smitha10b9782013-04-22 15:31:51 +0000873 if (VD->isThisDeclarationADefinition()) {
874 if (VD->isStaticLocal()) {
875 SemaRef.Diag(VD->getLocation(),
876 diag::err_constexpr_local_var_static)
877 << isa<CXXConstructorDecl>(Dcl)
878 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
879 return false;
880 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000881 if (!VD->getType()->isDependentType() &&
882 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000883 VD->getLocation(), VD->getType(),
884 diag::err_constexpr_local_var_non_literal_type,
885 isa<CXXConstructorDecl>(Dcl)))
886 return false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700887 if (!VD->getType()->isDependentType() &&
888 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smitha10b9782013-04-22 15:31:51 +0000889 SemaRef.Diag(VD->getLocation(),
890 diag::err_constexpr_local_var_no_init)
891 << isa<CXXConstructorDecl>(Dcl);
892 return false;
893 }
894 }
895 SemaRef.Diag(VD->getLocation(),
896 SemaRef.getLangOpts().CPlusPlus1y
897 ? diag::warn_cxx11_compat_constexpr_local_var
898 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000899 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000900 continue;
901 }
902
903 case Decl::NamespaceAlias:
904 case Decl::Function:
905 // These are disallowed in C++11 and permitted in C++1y. Allow them
906 // everywhere as an extension.
907 if (!Cxx1yLoc.isValid())
908 Cxx1yLoc = DS->getLocStart();
909 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000910
911 default:
912 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
913 << isa<CXXConstructorDecl>(Dcl);
914 return false;
915 }
916 }
917
918 return true;
919}
920
921/// Check that the given field is initialized within a constexpr constructor.
922///
923/// \param Dcl The constexpr constructor being checked.
924/// \param Field The field being checked. This may be a member of an anonymous
925/// struct or union nested within the class being checked.
926/// \param Inits All declarations, including anonymous struct/union members and
927/// indirect members, for which any initialization was provided.
928/// \param Diagnosed Set to true if an error is produced.
929static void CheckConstexprCtorInitializer(Sema &SemaRef,
930 const FunctionDecl *Dcl,
931 FieldDecl *Field,
932 llvm::SmallSet<Decl*, 16> &Inits,
933 bool &Diagnosed) {
Eli Friedman5fb478b2013-06-28 21:07:41 +0000934 if (Field->isInvalidDecl())
935 return;
936
Douglas Gregord61db332011-10-10 17:22:13 +0000937 if (Field->isUnnamedBitfield())
938 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000939
Stephen Hines651f13c2014-04-23 16:59:28 -0700940 // Anonymous unions with no variant members and empty anonymous structs do not
941 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
942 // indirect fields don't need initializing.
Richard Smith30ecfad2012-02-09 06:40:58 +0000943 if (Field->isAnonymousStructOrUnion() &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700944 (Field->getType()->isUnionType()
945 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
946 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith30ecfad2012-02-09 06:40:58 +0000947 return;
948
Richard Smith9f569cc2011-10-01 02:31:28 +0000949 if (!Inits.count(Field)) {
950 if (!Diagnosed) {
951 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
952 Diagnosed = true;
953 }
954 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
955 } else if (Field->isAnonymousStructOrUnion()) {
956 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Stephen Hines651f13c2014-04-23 16:59:28 -0700957 for (auto *I : RD->fields())
Richard Smith9f569cc2011-10-01 02:31:28 +0000958 // If an anonymous union contains an anonymous struct of which any member
959 // is initialized, all members must be initialized.
Stephen Hines651f13c2014-04-23 16:59:28 -0700960 if (!RD->isUnion() || Inits.count(I))
961 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000962 }
963}
964
Richard Smitha10b9782013-04-22 15:31:51 +0000965/// Check the provided statement is allowed in a constexpr function
966/// definition.
967static bool
968CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelme7205c02013-08-10 12:33:24 +0000969 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smitha10b9782013-04-22 15:31:51 +0000970 SourceLocation &Cxx1yLoc) {
971 // - its function-body shall be [...] a compound-statement that contains only
972 switch (S->getStmtClass()) {
973 case Stmt::NullStmtClass:
974 // - null statements,
975 return true;
976
977 case Stmt::DeclStmtClass:
978 // - static_assert-declarations
979 // - using-declarations,
980 // - using-directives,
981 // - typedef declarations and alias-declarations that do not define
982 // classes or enumerations,
983 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
984 return false;
985 return true;
986
987 case Stmt::ReturnStmtClass:
988 // - and exactly one return statement;
989 if (isa<CXXConstructorDecl>(Dcl)) {
990 // C++1y allows return statements in constexpr constructors.
991 if (!Cxx1yLoc.isValid())
992 Cxx1yLoc = S->getLocStart();
993 return true;
994 }
995
996 ReturnStmts.push_back(S->getLocStart());
997 return true;
998
999 case Stmt::CompoundStmtClass: {
1000 // C++1y allows compound-statements.
1001 if (!Cxx1yLoc.isValid())
1002 Cxx1yLoc = S->getLocStart();
1003
1004 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Stephen Hines651f13c2014-04-23 16:59:28 -07001005 for (auto *BodyIt : CompStmt->body()) {
1006 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smitha10b9782013-04-22 15:31:51 +00001007 Cxx1yLoc))
1008 return false;
1009 }
1010 return true;
1011 }
1012
1013 case Stmt::AttributedStmtClass:
1014 if (!Cxx1yLoc.isValid())
1015 Cxx1yLoc = S->getLocStart();
1016 return true;
1017
1018 case Stmt::IfStmtClass: {
1019 // C++1y allows if-statements.
1020 if (!Cxx1yLoc.isValid())
1021 Cxx1yLoc = S->getLocStart();
1022
1023 IfStmt *If = cast<IfStmt>(S);
1024 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1025 Cxx1yLoc))
1026 return false;
1027 if (If->getElse() &&
1028 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1029 Cxx1yLoc))
1030 return false;
1031 return true;
1032 }
1033
1034 case Stmt::WhileStmtClass:
1035 case Stmt::DoStmtClass:
1036 case Stmt::ForStmtClass:
1037 case Stmt::CXXForRangeStmtClass:
1038 case Stmt::ContinueStmtClass:
1039 // C++1y allows all of these. We don't allow them as extensions in C++11,
1040 // because they don't make sense without variable mutation.
1041 if (!SemaRef.getLangOpts().CPlusPlus1y)
1042 break;
1043 if (!Cxx1yLoc.isValid())
1044 Cxx1yLoc = S->getLocStart();
1045 for (Stmt::child_range Children = S->children(); Children; ++Children)
1046 if (*Children &&
1047 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1048 Cxx1yLoc))
1049 return false;
1050 return true;
1051
1052 case Stmt::SwitchStmtClass:
1053 case Stmt::CaseStmtClass:
1054 case Stmt::DefaultStmtClass:
1055 case Stmt::BreakStmtClass:
1056 // C++1y allows switch-statements, and since they don't need variable
1057 // mutation, we can reasonably allow them in C++11 as an extension.
1058 if (!Cxx1yLoc.isValid())
1059 Cxx1yLoc = S->getLocStart();
1060 for (Stmt::child_range Children = S->children(); Children; ++Children)
1061 if (*Children &&
1062 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1063 Cxx1yLoc))
1064 return false;
1065 return true;
1066
1067 default:
1068 if (!isa<Expr>(S))
1069 break;
1070
1071 // C++1y allows expression-statements.
1072 if (!Cxx1yLoc.isValid())
1073 Cxx1yLoc = S->getLocStart();
1074 return true;
1075 }
1076
1077 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1078 << isa<CXXConstructorDecl>(Dcl);
1079 return false;
1080}
1081
Richard Smith9f569cc2011-10-01 02:31:28 +00001082/// Check the body for the given constexpr function declaration only contains
1083/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1084///
1085/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001086bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001087 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001088 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001089 // The definition of a constexpr function shall satisfy the following
1090 // constraints: [...]
1091 // - its function-body shall be = delete, = default, or a
1092 // compound-statement
1093 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001094 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001095 // In the definition of a constexpr constructor, [...]
1096 // - its function-body shall not be a function-try-block;
1097 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1098 << isa<CXXConstructorDecl>(Dcl);
1099 return false;
1100 }
1101
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001102 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001103
1104 // - its function-body shall be [...] a compound-statement that contains only
1105 // [... list of cases ...]
1106 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1107 SourceLocation Cxx1yLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -07001108 for (auto *BodyIt : CompBody->body()) {
1109 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smitha10b9782013-04-22 15:31:51 +00001110 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001111 }
1112
Richard Smitha10b9782013-04-22 15:31:51 +00001113 if (Cxx1yLoc.isValid())
1114 Diag(Cxx1yLoc,
1115 getLangOpts().CPlusPlus1y
1116 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1117 : diag::ext_constexpr_body_invalid_stmt)
1118 << isa<CXXConstructorDecl>(Dcl);
1119
Richard Smith9f569cc2011-10-01 02:31:28 +00001120 if (const CXXConstructorDecl *Constructor
1121 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1122 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001123 // DR1359:
1124 // - every non-variant non-static data member and base class sub-object
1125 // shall be initialized;
Stephen Hines651f13c2014-04-23 16:59:28 -07001126 // DR1460:
1127 // - if the class is a union having variant members, exactly one of them
Richard Smith30ecfad2012-02-09 06:40:58 +00001128 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001129 if (RD->isUnion()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001130 if (Constructor->getNumCtorInitializers() == 0 &&
1131 RD->hasVariantMembers()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001132 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1133 return false;
1134 }
Richard Smith6e433752011-10-10 16:38:04 +00001135 } else if (!Constructor->isDependentContext() &&
1136 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001137 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1138
1139 // Skip detailed checking if we have enough initializers, and we would
1140 // allow at most one initializer per member.
1141 bool AnyAnonStructUnionMembers = false;
1142 unsigned Fields = 0;
1143 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1144 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001145 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001146 AnyAnonStructUnionMembers = true;
1147 break;
1148 }
1149 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001150 // DR1460:
1151 // - if the class is a union-like class, but is not a union, for each of
1152 // its anonymous union members having variant members, exactly one of
1153 // them shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001154 if (AnyAnonStructUnionMembers ||
1155 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1156 // Check initialization of non-static data members. Base classes are
1157 // always initialized so do not need to be checked. Dependent bases
1158 // might not have initializers in the member initializer list.
1159 llvm::SmallSet<Decl*, 16> Inits;
Stephen Hines651f13c2014-04-23 16:59:28 -07001160 for (const auto *I: Constructor->inits()) {
1161 if (FieldDecl *FD = I->getMember())
Richard Smith9f569cc2011-10-01 02:31:28 +00001162 Inits.insert(FD);
Stephen Hines651f13c2014-04-23 16:59:28 -07001163 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smith9f569cc2011-10-01 02:31:28 +00001164 Inits.insert(ID->chain_begin(), ID->chain_end());
1165 }
1166
1167 bool Diagnosed = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07001168 for (auto *I : RD->fields())
1169 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001170 if (Diagnosed)
1171 return false;
1172 }
1173 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001174 } else {
1175 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001176 // C++1y doesn't require constexpr functions to contain a 'return'
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001177 // statement. We still do, unless the return type might be void, because
Richard Smitha10b9782013-04-22 15:31:51 +00001178 // otherwise if there's no return statement, the function cannot
1179 // be used in a core constant expression.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001180 bool OK = getLangOpts().CPlusPlus1y &&
1181 (Dcl->getReturnType()->isVoidType() ||
1182 Dcl->getReturnType()->isDependentType());
Richard Smitha10b9782013-04-22 15:31:51 +00001183 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001184 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1185 : diag::err_constexpr_body_no_return);
1186 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001187 }
1188 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001189 Diag(ReturnStmts.back(),
1190 getLangOpts().CPlusPlus1y
1191 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1192 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001193 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1194 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001195 }
1196 }
1197
Richard Smith5ba73e12012-02-04 00:33:54 +00001198 // C++11 [dcl.constexpr]p5:
1199 // if no function argument values exist such that the function invocation
1200 // substitution would produce a constant expression, the program is
1201 // ill-formed; no diagnostic required.
1202 // C++11 [dcl.constexpr]p3:
1203 // - every constructor call and implicit conversion used in initializing the
1204 // return value shall be one of those allowed in a constant expression.
1205 // C++11 [dcl.constexpr]p4:
1206 // - every constructor involved in initializing non-static data members and
1207 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001208 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001209 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001210 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001211 << isa<CXXConstructorDecl>(Dcl);
1212 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1213 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001214 // Don't return false here: we allow this for compatibility in
1215 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001216 }
1217
Richard Smith9f569cc2011-10-01 02:31:28 +00001218 return true;
1219}
1220
Douglas Gregorb48fe382008-10-31 09:07:45 +00001221/// isCurrentClassName - Determine whether the identifier II is the
1222/// name of the class type currently being defined. In the case of
1223/// nested classes, this will only return true if II is the name of
1224/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001225bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1226 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001227 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001228
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001229 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001230 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001231 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001232 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1233 } else
1234 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1235
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001236 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001237 return &II == CurDecl->getIdentifier();
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00001238 return false;
Douglas Gregorb48fe382008-10-31 09:07:45 +00001239}
1240
Richard Smithb79b17b2013-10-15 00:00:26 +00001241/// \brief Determine whether the identifier II is a typo for the name of
1242/// the class type currently being defined. If so, update it to the identifier
1243/// that should have been used.
1244bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1245 assert(getLangOpts().CPlusPlus && "No class names in C!");
1246
1247 if (!getLangOpts().SpellChecking)
1248 return false;
1249
1250 CXXRecordDecl *CurDecl;
1251 if (SS && SS->isSet() && !SS->isInvalid()) {
1252 DeclContext *DC = computeDeclContext(*SS, true);
1253 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1254 } else
1255 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1256
1257 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1258 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1259 < II->getLength()) {
1260 II = CurDecl->getIdentifier();
1261 return true;
1262 }
1263
1264 return false;
1265}
1266
Douglas Gregor229d47a2012-11-10 07:24:09 +00001267/// \brief Determine whether the given class is a base class of the given
1268/// class, including looking at dependent bases.
1269static bool findCircularInheritance(const CXXRecordDecl *Class,
1270 const CXXRecordDecl *Current) {
1271 SmallVector<const CXXRecordDecl*, 8> Queue;
1272
1273 Class = Class->getCanonicalDecl();
1274 while (true) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001275 for (const auto &I : Current->bases()) {
1276 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregor229d47a2012-11-10 07:24:09 +00001277 if (!Base)
1278 continue;
1279
1280 Base = Base->getDefinition();
1281 if (!Base)
1282 continue;
1283
1284 if (Base->getCanonicalDecl() == Class)
1285 return true;
1286
1287 Queue.push_back(Base);
1288 }
1289
1290 if (Queue.empty())
1291 return false;
1292
Robert Wilhelm344472e2013-08-23 16:11:15 +00001293 Current = Queue.pop_back_val();
Douglas Gregor229d47a2012-11-10 07:24:09 +00001294 }
1295
1296 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001297}
1298
Mike Stump1eb44332009-09-09 15:08:12 +00001299/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001300///
1301/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1302/// and returns NULL otherwise.
1303CXXBaseSpecifier *
1304Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1305 SourceRange SpecifierRange,
1306 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001307 TypeSourceInfo *TInfo,
1308 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001309 QualType BaseType = TInfo->getType();
1310
Douglas Gregor2943aed2009-03-03 04:44:36 +00001311 // C++ [class.union]p1:
1312 // A union shall not have base classes.
1313 if (Class->isUnion()) {
1314 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1315 << SpecifierRange;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001316 return nullptr;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001317 }
1318
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001319 if (EllipsisLoc.isValid() &&
1320 !TInfo->getType()->containsUnexpandedParameterPack()) {
1321 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1322 << TInfo->getTypeLoc().getSourceRange();
1323 EllipsisLoc = SourceLocation();
1324 }
Douglas Gregord777e282012-11-10 01:18:17 +00001325
1326 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1327
1328 if (BaseType->isDependentType()) {
1329 // Make sure that we don't have circular inheritance among our dependent
1330 // bases. For non-dependent bases, the check for completeness below handles
1331 // this.
1332 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1333 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1334 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001335 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001336 Diag(BaseLoc, diag::err_circular_inheritance)
1337 << BaseType << Context.getTypeDeclType(Class);
1338
1339 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1340 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1341 << BaseType;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001342
1343 return nullptr;
Douglas Gregord777e282012-11-10 01:18:17 +00001344 }
1345 }
1346
Mike Stump1eb44332009-09-09 15:08:12 +00001347 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001348 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001349 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001350 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001351
1352 // Base specifiers must be record types.
1353 if (!BaseType->isRecordType()) {
1354 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001355 return nullptr;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001356 }
1357
1358 // C++ [class.union]p1:
1359 // A union shall not be used as a base class.
1360 if (BaseType->isUnionType()) {
1361 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001362 return nullptr;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001363 }
1364
1365 // C++ [class.derived]p2:
1366 // The class-name in a base-specifier shall not be an incompletely
1367 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001368 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001369 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001370 Class->setInvalidDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001371 return nullptr;
John McCall572fc622010-08-17 07:23:57 +00001372 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001373
Eli Friedman1d954f62009-08-15 21:55:26 +00001374 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001375 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001376 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001377 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001378 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001379 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001380 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001381
David Majnemer28165b72013-11-02 12:00:36 +00001382 // A class which contains a flexible array member is not suitable for use as a
1383 // base class:
1384 // - If the layout determines that a base comes before another base,
1385 // the flexible array member would index into the subsequent base.
1386 // - If the layout determines that base comes before the derived class,
1387 // the flexible array member would index into the derived class.
1388 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1389 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1390 << CXXBaseDecl->getDeclName();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001391 return nullptr;
David Majnemer28165b72013-11-02 12:00:36 +00001392 }
1393
Anders Carlsson1d209272011-03-25 14:55:14 +00001394 // C++ [class]p3:
David Majnemer7041fcc2013-11-02 11:24:41 +00001395 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson1d209272011-03-25 14:55:14 +00001396 // base-clause, the program is ill-formed.
David Majnemer7121bdb2013-10-18 00:33:31 +00001397 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer7041fcc2013-11-02 11:24:41 +00001398 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemer7121bdb2013-10-18 00:33:31 +00001399 << CXXBaseDecl->getDeclName()
1400 << FA->isSpelledAsSealed();
Anders Carlssondfc2f102011-01-22 17:51:53 +00001401 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1402 << CXXBaseDecl->getDeclName();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001403 return nullptr;
Anders Carlssondfc2f102011-01-22 17:51:53 +00001404 }
1405
John McCall572fc622010-08-17 07:23:57 +00001406 if (BaseDecl->isInvalidDecl())
1407 Class->setInvalidDecl();
David Majnemer7041fcc2013-11-02 11:24:41 +00001408
Anders Carlsson51f94042009-12-03 17:49:57 +00001409 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001410 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001411 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001412 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001413}
1414
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001415/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1416/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001417/// example:
1418/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001419/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001420BaseResult
John McCalld226f652010-08-21 09:40:31 +00001421Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001422 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001423 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001424 ParsedType basetype, SourceLocation BaseLoc,
1425 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001426 if (!classdecl)
1427 return true;
1428
Douglas Gregor40808ce2009-03-09 23:48:35 +00001429 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001430 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001431 if (!Class)
1432 return true;
1433
Richard Smith05321402013-02-19 23:47:15 +00001434 // We do not support any C++11 attributes on base-specifiers yet.
1435 // Diagnose any attributes we see.
1436 if (!Attributes.empty()) {
1437 for (AttributeList *Attr = Attributes.getList(); Attr;
1438 Attr = Attr->getNext()) {
1439 if (Attr->isInvalid() ||
1440 Attr->getKind() == AttributeList::IgnoredAttribute)
1441 continue;
1442 Diag(Attr->getLoc(),
1443 Attr->getKind() == AttributeList::UnknownAttribute
1444 ? diag::warn_unknown_attribute_ignored
1445 : diag::err_base_specifier_attribute)
1446 << Attr->getName();
1447 }
1448 }
1449
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001450 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky56062202010-07-26 16:56:01 +00001451 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001452
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001453 if (EllipsisLoc.isInvalid() &&
1454 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001455 UPPC_BaseType))
1456 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001457
Douglas Gregor2943aed2009-03-03 04:44:36 +00001458 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001459 Virtual, Access, TInfo,
1460 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001461 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001462 else
1463 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Douglas Gregor2943aed2009-03-03 04:44:36 +00001465 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001466}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001467
Douglas Gregor2943aed2009-03-03 04:44:36 +00001468/// \brief Performs the actual work of attaching the given base class
1469/// specifiers to a C++ class.
1470bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1471 unsigned NumBases) {
1472 if (NumBases == 0)
1473 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001474
1475 // Used to keep track of which base types we have already seen, so
1476 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001477 // that the key is always the unqualified canonical type of the base
1478 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001479 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1480
1481 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001482 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001483 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001484 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001485 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001486 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001487 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001488
1489 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1490 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001491 // C++ [class.mi]p3:
1492 // A class shall not be specified as a direct base class of a
1493 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001494 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001495 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001496 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001497 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001498
1499 // Delete the duplicate base class specifier; we're going to
1500 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001501 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001502
1503 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001504 } else {
1505 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001506 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001507 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001508 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1509 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1510 if (Class->isInterface() &&
1511 (!RD->isInterface() ||
1512 KnownBase->getAccessSpecifier() != AS_public)) {
1513 // The Microsoft extension __interface does not permit bases that
1514 // are not themselves public interfaces.
1515 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1516 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1517 << RD->getSourceRange();
1518 Invalid = true;
1519 }
1520 if (RD->hasAttr<WeakAttr>())
Stephen Hines651f13c2014-04-23 16:59:28 -07001521 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalle402e722012-09-25 07:32:39 +00001522 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001523 }
1524 }
1525
1526 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001527 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001528
1529 // Delete the remaining (good) base class specifiers, since their
1530 // data has been copied into the CXXRecordDecl.
1531 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001532 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001533
1534 return Invalid;
1535}
1536
1537/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1538/// class, after checking whether there are any duplicate base
1539/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001540void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001541 unsigned NumBases) {
1542 if (!ClassDecl || !Bases || !NumBases)
1543 return;
1544
1545 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelm0d317a02013-07-22 05:04:01 +00001546 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001547}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001548
Douglas Gregora8f32e02009-10-06 17:59:45 +00001549/// \brief Determine whether the type \p Derived is a C++ class that is
1550/// derived from the type \p Base.
1551bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001552 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001553 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001554
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001555 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001556 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001557 return false;
1558
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001559 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001560 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001561 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001562
1563 // If either the base or the derived type is invalid, don't try to
1564 // check whether one is derived from the other.
1565 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1566 return false;
1567
John McCall86ff3082010-02-04 22:26:26 +00001568 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1569 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001570}
1571
1572/// \brief Determine whether the type \p Derived is a C++ class that is
1573/// derived from the type \p Base.
1574bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001575 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001576 return false;
1577
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001578 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001579 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001580 return false;
1581
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001582 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001583 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001584 return false;
1585
Douglas Gregora8f32e02009-10-06 17:59:45 +00001586 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1587}
1588
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001589void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001590 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001591 assert(BasePathArray.empty() && "Base path array must be empty!");
1592 assert(Paths.isRecordingPaths() && "Must record paths!");
1593
1594 const CXXBasePath &Path = Paths.front();
1595
1596 // We first go backward and check if we have a virtual base.
1597 // FIXME: It would be better if CXXBasePath had the base specifier for
1598 // the nearest virtual base.
1599 unsigned Start = 0;
1600 for (unsigned I = Path.size(); I != 0; --I) {
1601 if (Path[I - 1].Base->isVirtual()) {
1602 Start = I - 1;
1603 break;
1604 }
1605 }
1606
1607 // Now add all bases.
1608 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001609 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001610}
1611
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001612/// \brief Determine whether the given base path includes a virtual
1613/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001614bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1615 for (CXXCastPath::const_iterator B = BasePath.begin(),
1616 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001617 B != BEnd; ++B)
1618 if ((*B)->isVirtual())
1619 return true;
1620
1621 return false;
1622}
1623
Douglas Gregora8f32e02009-10-06 17:59:45 +00001624/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1625/// conversion (where Derived and Base are class types) is
1626/// well-formed, meaning that the conversion is unambiguous (and
1627/// that all of the base classes are accessible). Returns true
1628/// and emits a diagnostic if the code is ill-formed, returns false
1629/// otherwise. Loc is the location where this routine should point to
1630/// if there is an error, and Range is the source range to highlight
1631/// if there is an error.
1632bool
1633Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001634 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001635 unsigned AmbigiousBaseConvID,
1636 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001637 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001638 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001639 // First, determine whether the path from Derived to Base is
1640 // ambiguous. This is slightly more expensive than checking whether
1641 // the Derived to Base conversion exists, because here we need to
1642 // explore multiple paths to determine if there is an ambiguity.
1643 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1644 /*DetectVirtual=*/false);
1645 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1646 assert(DerivationOkay &&
1647 "Can only be used with a derived-to-base conversion");
1648 (void)DerivationOkay;
1649
1650 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001651 if (InaccessibleBaseID) {
1652 // Check that the base class can be accessed.
1653 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1654 InaccessibleBaseID)) {
1655 case AR_inaccessible:
1656 return true;
1657 case AR_accessible:
1658 case AR_dependent:
1659 case AR_delayed:
1660 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001661 }
John McCall6b2accb2010-02-10 09:31:12 +00001662 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001663
1664 // Build a base path if necessary.
1665 if (BasePath)
1666 BuildBasePathArray(Paths, *BasePath);
1667 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001668 }
1669
David Majnemer2f686692013-06-22 06:43:58 +00001670 if (AmbigiousBaseConvID) {
1671 // We know that the derived-to-base conversion is ambiguous, and
1672 // we're going to produce a diagnostic. Perform the derived-to-base
1673 // search just one more time to compute all of the possible paths so
1674 // that we can print them out. This is more expensive than any of
1675 // the previous derived-to-base checks we've done, but at this point
1676 // performance isn't as much of an issue.
1677 Paths.clear();
1678 Paths.setRecordingPaths(true);
1679 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1680 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1681 (void)StillOkay;
1682
1683 // Build up a textual representation of the ambiguous paths, e.g.,
1684 // D -> B -> A, that will be used to illustrate the ambiguous
1685 // conversions in the diagnostic. We only print one of the paths
1686 // to each base class subobject.
1687 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1688
1689 Diag(Loc, AmbigiousBaseConvID)
1690 << Derived << Base << PathDisplayStr << Range << Name;
1691 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001692 return true;
1693}
1694
1695bool
1696Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001697 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001698 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001699 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001700 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001701 IgnoreAccess ? 0
1702 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001703 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001704 Loc, Range, DeclarationName(),
1705 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001706}
1707
1708
1709/// @brief Builds a string representing ambiguous paths from a
1710/// specific derived class to different subobjects of the same base
1711/// class.
1712///
1713/// This function builds a string that can be used in error messages
1714/// to show the different paths that one can take through the
1715/// inheritance hierarchy to go from the derived class to different
1716/// subobjects of a base class. The result looks something like this:
1717/// @code
1718/// struct D -> struct B -> struct A
1719/// struct D -> struct C -> struct A
1720/// @endcode
1721std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1722 std::string PathDisplayStr;
1723 std::set<unsigned> DisplayedPaths;
1724 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1725 Path != Paths.end(); ++Path) {
1726 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1727 // We haven't displayed a path to this particular base
1728 // class subobject yet.
1729 PathDisplayStr += "\n ";
1730 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1731 for (CXXBasePath::const_iterator Element = Path->begin();
1732 Element != Path->end(); ++Element)
1733 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1734 }
1735 }
1736
1737 return PathDisplayStr;
1738}
1739
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001740//===----------------------------------------------------------------------===//
1741// C++ class member Handling
1742//===----------------------------------------------------------------------===//
1743
Abramo Bagnara6206d532010-06-05 05:09:32 +00001744/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001745bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1746 SourceLocation ASLoc,
1747 SourceLocation ColonLoc,
1748 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001749 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001750 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001751 ASLoc, ColonLoc);
1752 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001753 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001754}
1755
Richard Smitha4b39652012-08-06 03:25:17 +00001756/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmandae92712013-09-05 23:51:03 +00001757void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001758 if (D->isInvalidDecl())
1759 return;
1760
Eli Friedmandae92712013-09-05 23:51:03 +00001761 // We only care about "override" and "final" declarations.
1762 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1763 return;
Anders Carlsson9e682d92011-01-20 05:57:14 +00001764
Eli Friedmandae92712013-09-05 23:51:03 +00001765 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001766
Eli Friedmandae92712013-09-05 23:51:03 +00001767 // We can't check dependent instance methods.
1768 if (MD && MD->isInstance() &&
1769 (MD->getParent()->hasAnyDependentBases() ||
1770 MD->getType()->isDependentType()))
1771 return;
1772
1773 if (MD && !MD->isVirtual()) {
1774 // If we have a non-virtual method, check if if hides a virtual method.
1775 // (In that case, it's most likely the method has the wrong type.)
1776 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1777 FindHiddenVirtualMethods(MD, OverloadedMethods);
1778
1779 if (!OverloadedMethods.empty()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001780 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1781 Diag(OA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001782 diag::override_keyword_hides_virtual_member_function)
1783 << "override" << (OverloadedMethods.size() > 1);
1784 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001785 Diag(FA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001786 diag::override_keyword_hides_virtual_member_function)
David Majnemer7121bdb2013-10-18 00:33:31 +00001787 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1788 << (OverloadedMethods.size() > 1);
Richard Smitha4b39652012-08-06 03:25:17 +00001789 }
Eli Friedmandae92712013-09-05 23:51:03 +00001790 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1791 MD->setInvalidDecl();
1792 return;
1793 }
1794 // Fall through into the general case diagnostic.
1795 // FIXME: We might want to attempt typo correction here.
1796 }
1797
1798 if (!MD || !MD->isVirtual()) {
1799 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1800 Diag(OA->getLocation(),
1801 diag::override_keyword_only_allowed_on_virtual_member_functions)
1802 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1803 D->dropAttr<OverrideAttr>();
1804 }
1805 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1806 Diag(FA->getLocation(),
1807 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemer7121bdb2013-10-18 00:33:31 +00001808 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1809 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmandae92712013-09-05 23:51:03 +00001810 D->dropAttr<FinalAttr>();
Richard Smitha4b39652012-08-06 03:25:17 +00001811 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001812 return;
1813 }
Richard Smitha4b39652012-08-06 03:25:17 +00001814
Richard Smitha4b39652012-08-06 03:25:17 +00001815 // C++11 [class.virtual]p5:
1816 // If a virtual function is marked with the virt-specifier override and
1817 // does not override a member function of a base class, the program is
1818 // ill-formed.
1819 bool HasOverriddenMethods =
1820 MD->begin_overridden_methods() != MD->end_overridden_methods();
1821 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1822 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1823 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001824}
1825
Richard Smitha4b39652012-08-06 03:25:17 +00001826/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001827/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001828/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001829bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1830 const CXXMethodDecl *Old) {
David Majnemer7121bdb2013-10-18 00:33:31 +00001831 FinalAttr *FA = Old->getAttr<FinalAttr>();
1832 if (!FA)
Anders Carlssonf89e0422011-01-23 21:07:30 +00001833 return false;
1834
1835 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemer7121bdb2013-10-18 00:33:31 +00001836 << New->getDeclName()
1837 << FA->isSpelledAsSealed();
Anders Carlssonf89e0422011-01-23 21:07:30 +00001838 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1839 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001840}
1841
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001842static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001843 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1844 // FIXME: Destruction of ObjC lifetime types has side-effects.
1845 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1846 return !RD->isCompleteDefinition() ||
1847 !RD->hasTrivialDefaultConstructor() ||
1848 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001849 return false;
1850}
1851
John McCall76da55d2013-04-16 07:28:30 +00001852static AttributeList *getMSPropertyAttr(AttributeList *list) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001853 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall76da55d2013-04-16 07:28:30 +00001854 if (it->isDeclspecPropertyAttribute())
1855 return it;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001856 return nullptr;
John McCall76da55d2013-04-16 07:28:30 +00001857}
1858
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001859/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1860/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001861/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001862/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1863/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001864NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001865Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001866 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001867 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001868 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001869 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001870 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1871 DeclarationName Name = NameInfo.getName();
1872 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001873
1874 // For anonymous bitfields, the location should point to the type.
1875 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001876 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001877
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001878 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001879
John McCall4bde1e12010-06-04 08:34:12 +00001880 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001881 assert(!DS.isFriendSpecified());
1882
Richard Smith1ab0d902011-06-25 02:28:38 +00001883 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001884
John McCalle402e722012-09-25 07:32:39 +00001885 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1886 // The Microsoft extension __interface only permits public member functions
1887 // and prohibits constructors, destructors, operators, non-public member
1888 // functions, static methods and data members.
1889 unsigned InvalidDecl;
1890 bool ShowDeclName = true;
1891 if (!isFunc)
1892 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1893 else if (AS != AS_public)
1894 InvalidDecl = 2;
1895 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1896 InvalidDecl = 3;
1897 else switch (Name.getNameKind()) {
1898 case DeclarationName::CXXConstructorName:
1899 InvalidDecl = 4;
1900 ShowDeclName = false;
1901 break;
1902
1903 case DeclarationName::CXXDestructorName:
1904 InvalidDecl = 5;
1905 ShowDeclName = false;
1906 break;
1907
1908 case DeclarationName::CXXOperatorName:
1909 case DeclarationName::CXXConversionFunctionName:
1910 InvalidDecl = 6;
1911 break;
1912
1913 default:
1914 InvalidDecl = 0;
1915 break;
1916 }
1917
1918 if (InvalidDecl) {
1919 if (ShowDeclName)
1920 Diag(Loc, diag::err_invalid_member_in_interface)
1921 << (InvalidDecl-1) << Name;
1922 else
1923 Diag(Loc, diag::err_invalid_member_in_interface)
1924 << (InvalidDecl-1) << "";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001925 return nullptr;
John McCalle402e722012-09-25 07:32:39 +00001926 }
1927 }
1928
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001929 // C++ 9.2p6: A member shall not be declared to have automatic storage
1930 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001931 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1932 // data members and cannot be applied to names declared const or static,
1933 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001934 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001935 case DeclSpec::SCS_unspecified:
1936 case DeclSpec::SCS_typedef:
1937 case DeclSpec::SCS_static:
1938 break;
1939 case DeclSpec::SCS_mutable:
1940 if (isFunc) {
1941 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Richard Smithec642442013-04-12 22:46:28 +00001943 // FIXME: It would be nicer if the keyword was ignored only for this
1944 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001945 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001946 }
1947 break;
1948 default:
1949 Diag(DS.getStorageClassSpecLoc(),
1950 diag::err_storageclass_invalid_for_member);
1951 D.getMutableDeclSpec().ClearStorageClassSpecs();
1952 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001953 }
1954
Sebastian Redl669d5d72008-11-14 23:42:31 +00001955 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1956 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001957 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001958
David Blaikie1d87fba2013-01-30 01:22:18 +00001959 if (DS.isConstexprSpecified() && isInstField) {
1960 SemaDiagnosticBuilder B =
1961 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1962 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1963 if (InitStyle == ICIS_NoInit) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001964 B << 0 << 0;
1965 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
1966 B << FixItHint::CreateRemoval(ConstexprLoc);
1967 else {
1968 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
1969 D.getMutableDeclSpec().ClearConstexprSpec();
1970 const char *PrevSpec;
1971 unsigned DiagID;
1972 bool Failed = D.getMutableDeclSpec().SetTypeQual(
1973 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
1974 (void)Failed;
1975 assert(!Failed && "Making a constexpr member const shouldn't fail");
1976 }
David Blaikie1d87fba2013-01-30 01:22:18 +00001977 } else {
1978 B << 1;
1979 const char *PrevSpec;
1980 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001981 if (D.getMutableDeclSpec().SetStorageClassSpec(
Stephen Hines651f13c2014-04-23 16:59:28 -07001982 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
1983 Context.getPrintingPolicy())) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001984 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001985 "This is the only DeclSpec that should fail to be applied");
1986 B << 1;
1987 } else {
1988 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1989 isInstField = false;
1990 }
1991 }
1992 }
1993
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001994 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001995 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001996 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001997
1998 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001999 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00002000 Diag(Loc, diag::err_bad_variable_name)
2001 << Name;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002002 return nullptr;
Douglas Gregorb5a01872011-10-09 18:55:59 +00002003 }
Douglas Gregorf2503652011-09-21 14:40:46 +00002004
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00002005 IdentifierInfo *II = Name.getAsIdentifierInfo();
2006
Douglas Gregorf2503652011-09-21 14:40:46 +00002007 // Member field could not be with "template" keyword.
2008 // So TemplateParameterLists should be empty in this case.
2009 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002010 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00002011 if (TemplateParams->size()) {
2012 // There is no such thing as a member field template.
2013 Diag(D.getIdentifierLoc(), diag::err_template_member)
2014 << II
2015 << SourceRange(TemplateParams->getTemplateLoc(),
2016 TemplateParams->getRAngleLoc());
2017 } else {
2018 // There is an extraneous 'template<>' for this member.
2019 Diag(TemplateParams->getTemplateLoc(),
2020 diag::err_template_member_noparams)
2021 << II
2022 << SourceRange(TemplateParams->getTemplateLoc(),
2023 TemplateParams->getRAngleLoc());
2024 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002025 return nullptr;
Douglas Gregorf2503652011-09-21 14:40:46 +00002026 }
2027
Douglas Gregor922fff22010-10-13 22:19:53 +00002028 if (SS.isSet() && !SS.isInvalid()) {
2029 // The user provided a superfluous scope specifier inside a class
2030 // definition:
2031 //
2032 // class X {
2033 // int X::member;
2034 // };
Douglas Gregor69605872012-03-28 16:01:27 +00002035 if (DeclContext *DC = computeDeclContext(SS, false))
2036 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00002037 else
2038 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2039 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00002040
Douglas Gregor922fff22010-10-13 22:19:53 +00002041 SS.clear();
2042 }
Douglas Gregorf2503652011-09-21 14:40:46 +00002043
John McCall76da55d2013-04-16 07:28:30 +00002044 AttributeList *MSPropertyAttr =
2045 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00002046 if (MSPropertyAttr) {
2047 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2048 BitWidth, InitStyle, AS, MSPropertyAttr);
2049 if (!Member)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002050 return nullptr;
Eli Friedmanb26f0122013-06-28 20:48:34 +00002051 isInstField = false;
2052 } else {
2053 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2054 BitWidth, InitStyle, AS);
2055 assert(Member && "HandleField never returns null");
2056 }
2057 } else {
2058 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2059
2060 Member = HandleDeclarator(S, D, TemplateParameterLists);
2061 if (!Member)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002062 return nullptr;
Eli Friedmanb26f0122013-06-28 20:48:34 +00002063
2064 // Non-instance-fields can't have a bitfield.
2065 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002066 if (Member->isInvalidDecl()) {
2067 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00002068 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002069 // C++ 9.6p3: A bit-field shall not be a static member.
2070 // "static member 'A' cannot be a bit-field"
2071 Diag(Loc, diag::err_static_not_bitfield)
2072 << Name << BitWidth->getSourceRange();
2073 } else if (isa<TypedefDecl>(Member)) {
2074 // "typedef member 'x' cannot be a bit-field"
2075 Diag(Loc, diag::err_typedef_not_bitfield)
2076 << Name << BitWidth->getSourceRange();
2077 } else {
2078 // A function typedef ("typedef int f(); f a;").
2079 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2080 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00002081 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00002082 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00002083 }
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002085 BitWidth = nullptr;
Chris Lattner8b963ef2009-03-05 23:01:03 +00002086 Member->setInvalidDecl();
2087 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00002088
2089 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Larisse Voufoef4579c2013-08-06 01:03:05 +00002091 // If we have declared a member function template or static data member
2092 // template, set the access of the templated declaration as well.
Douglas Gregor37b372b2009-08-20 22:52:58 +00002093 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2094 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002095 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2096 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002097 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002098
Richard Smitha4b39652012-08-06 03:25:17 +00002099 if (VS.isOverrideSpecified())
Stephen Hines651f13c2014-04-23 16:59:28 -07002100 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smitha4b39652012-08-06 03:25:17 +00002101 if (VS.isFinalSpecified())
David Majnemer7121bdb2013-10-18 00:33:31 +00002102 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2103 VS.isFinalSpelledSealed()));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002104
Douglas Gregorf5251602011-03-08 17:10:18 +00002105 if (VS.getLastLocation().isValid()) {
2106 // Update the end location of a method that has a virt-specifiers.
2107 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2108 MD->setRangeEnd(VS.getLastLocation());
2109 }
Richard Smitha4b39652012-08-06 03:25:17 +00002110
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002111 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002112
Douglas Gregor10bd3682008-11-17 22:58:34 +00002113 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002114
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002115 if (isInstField) {
2116 FieldDecl *FD = cast<FieldDecl>(Member);
2117 FieldCollector->Add(FD);
2118
2119 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2120 FD->getLocation())
2121 != DiagnosticsEngine::Ignored) {
2122 // Remember all explicit private FieldDecls that have a name, no side
2123 // effects and are not part of a dependent type declaration.
2124 if (!FD->isImplicit() && FD->getDeclName() &&
2125 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002126 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002127 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002128 !InitializationHasSideEffects(*FD))
2129 UnusedPrivateFields.insert(FD);
2130 }
2131 }
2132
John McCalld226f652010-08-21 09:40:31 +00002133 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002134}
2135
Hans Wennborg471f9852012-09-18 15:58:06 +00002136namespace {
2137 class UninitializedFieldVisitor
2138 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2139 Sema &S;
Richard Trieu858d2ba2013-10-25 00:56:00 +00002140 // List of Decls to generate a warning on. Also remove Decls that become
2141 // initialized.
Richard Trieuef8f90c2013-09-20 03:03:06 +00002142 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002143 // If non-null, add a note to the warning pointing back to the constructor.
2144 const CXXConstructorDecl *Constructor;
Hans Wennborg471f9852012-09-18 15:58:06 +00002145 public:
2146 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieu858d2ba2013-10-25 00:56:00 +00002147 UninitializedFieldVisitor(Sema &S,
Richard Trieuef8f90c2013-09-20 03:03:06 +00002148 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
Richard Trieuef8f90c2013-09-20 03:03:06 +00002149 const CXXConstructorDecl *Constructor)
Richard Trieu858d2ba2013-10-25 00:56:00 +00002150 : Inherited(S.Context), S(S), Decls(Decls),
2151 Constructor(Constructor) { }
Hans Wennborg471f9852012-09-18 15:58:06 +00002152
Richard Trieu3ddec882013-09-16 20:46:50 +00002153 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieufbb08b52013-09-13 03:20:53 +00002154 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2155 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002156
Richard Trieufbb08b52013-09-13 03:20:53 +00002157 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2158 // or union.
2159 MemberExpr *FieldME = ME;
2160
2161 Expr *Base = ME;
2162 while (isa<MemberExpr>(Base)) {
2163 ME = cast<MemberExpr>(Base);
2164
2165 if (isa<VarDecl>(ME->getMemberDecl()))
2166 return;
2167
2168 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2169 if (!FD->isAnonymousStructOrUnion())
2170 FieldME = ME;
2171
2172 Base = ME->getBase();
2173 }
2174
Richard Trieu3ddec882013-09-16 20:46:50 +00002175 if (!isa<CXXThisExpr>(Base))
2176 return;
2177
Richard Trieuef8f90c2013-09-20 03:03:06 +00002178 ValueDecl* FoundVD = FieldME->getMemberDecl();
2179
Richard Trieu858d2ba2013-10-25 00:56:00 +00002180 if (!Decls.count(FoundVD))
Richard Trieuef8f90c2013-09-20 03:03:06 +00002181 return;
2182
Richard Trieu858d2ba2013-10-25 00:56:00 +00002183 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieuef8f90c2013-09-20 03:03:06 +00002184
Richard Trieu858d2ba2013-10-25 00:56:00 +00002185 // Prevent double warnings on use of unbounded references.
2186 if (IsReference != CheckReferenceOnly)
2187 return;
2188
2189 unsigned diag = IsReference
2190 ? diag::warn_reference_field_is_uninit
2191 : diag::warn_field_is_uninit;
2192 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2193 if (Constructor)
2194 S.Diag(Constructor->getLocation(),
2195 diag::note_uninit_in_this_constructor)
2196 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2197
Hans Wennborg471f9852012-09-18 15:58:06 +00002198 }
2199
2200 void HandleValue(Expr *E) {
2201 E = E->IgnoreParens();
2202
2203 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu3ddec882013-09-16 20:46:50 +00002204 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002205 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002206 }
2207
2208 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2209 HandleValue(CO->getTrueExpr());
2210 HandleValue(CO->getFalseExpr());
2211 return;
2212 }
2213
2214 if (BinaryConditionalOperator *BCO =
2215 dyn_cast<BinaryConditionalOperator>(E)) {
2216 HandleValue(BCO->getCommon());
2217 HandleValue(BCO->getFalseExpr());
2218 return;
2219 }
2220
2221 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2222 switch (BO->getOpcode()) {
2223 default:
2224 return;
2225 case(BO_PtrMemD):
2226 case(BO_PtrMemI):
2227 HandleValue(BO->getLHS());
2228 return;
2229 case(BO_Comma):
2230 HandleValue(BO->getRHS());
2231 return;
2232 }
2233 }
2234 }
2235
Richard Trieufbb08b52013-09-13 03:20:53 +00002236 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieu858d2ba2013-10-25 00:56:00 +00002237 // All uses of unbounded reference fields will warn.
Richard Trieu3ddec882013-09-16 20:46:50 +00002238 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002239
2240 Inherited::VisitMemberExpr(ME);
2241 }
2242
Hans Wennborg471f9852012-09-18 15:58:06 +00002243 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2244 if (E->getCastKind() == CK_LValueToRValue)
2245 HandleValue(E->getSubExpr());
2246
2247 Inherited::VisitImplicitCastExpr(E);
2248 }
2249
Richard Trieufbb08b52013-09-13 03:20:53 +00002250 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieuef8f90c2013-09-20 03:03:06 +00002251 if (E->getConstructor()->isCopyConstructor())
Richard Trieufbb08b52013-09-13 03:20:53 +00002252 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2253 if (ICE->getCastKind() == CK_NoOp)
2254 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieu3ddec882013-09-16 20:46:50 +00002255 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002256
2257 Inherited::VisitCXXConstructExpr(E);
2258 }
2259
Hans Wennborg471f9852012-09-18 15:58:06 +00002260 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2261 Expr *Callee = E->getCallee();
2262 if (isa<MemberExpr>(Callee))
2263 HandleValue(Callee);
2264
2265 Inherited::VisitCXXMemberCallExpr(E);
2266 }
Richard Trieuef8f90c2013-09-20 03:03:06 +00002267
2268 void VisitBinaryOperator(BinaryOperator *E) {
2269 // If a field assignment is detected, remove the field from the
2270 // uninitiailized field set.
2271 if (E->getOpcode() == BO_Assign)
2272 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2273 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieu858d2ba2013-10-25 00:56:00 +00002274 if (!FD->getType()->isReferenceType())
2275 Decls.erase(FD);
Richard Trieuef8f90c2013-09-20 03:03:06 +00002276
2277 Inherited::VisitBinaryOperator(E);
2278 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002279 };
Richard Trieuef8f90c2013-09-20 03:03:06 +00002280 static void CheckInitExprContainsUninitializedFields(
Richard Trieu858d2ba2013-10-25 00:56:00 +00002281 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2282 const CXXConstructorDecl *Constructor) {
2283 if (Decls.size() == 0)
Richard Trieuef8f90c2013-09-20 03:03:06 +00002284 return;
2285
Richard Trieu858d2ba2013-10-25 00:56:00 +00002286 if (!E)
2287 return;
2288
2289 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2290 E = Default->getExpr();
2291 if (!E)
2292 return;
2293 // In class initializers will point to the constructor.
2294 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2295 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002296 UninitializedFieldVisitor(S, Decls, nullptr).Visit(E);
Richard Trieu858d2ba2013-10-25 00:56:00 +00002297 }
2298 }
2299
2300 // Diagnose value-uses of fields to initialize themselves, e.g.
2301 // foo(foo)
2302 // where foo is not also a parameter to the constructor.
2303 // Also diagnose across field uninitialized use such as
2304 // x(y), y(x)
2305 // TODO: implement -Wuninitialized and fold this into that framework.
2306 static void DiagnoseUninitializedFields(
2307 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2308
2309 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2310 Constructor->getLocation())
2311 == DiagnosticsEngine::Ignored) {
2312 return;
2313 }
2314
2315 if (Constructor->isInvalidDecl())
2316 return;
2317
2318 const CXXRecordDecl *RD = Constructor->getParent();
2319
2320 // Holds fields that are uninitialized.
2321 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2322
2323 // At the beginning, all fields are uninitialized.
Stephen Hines651f13c2014-04-23 16:59:28 -07002324 for (auto *I : RD->decls()) {
2325 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieu858d2ba2013-10-25 00:56:00 +00002326 UninitializedFields.insert(FD);
Stephen Hines651f13c2014-04-23 16:59:28 -07002327 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieu858d2ba2013-10-25 00:56:00 +00002328 UninitializedFields.insert(IFD->getAnonField());
2329 }
2330 }
2331
Stephen Hines651f13c2014-04-23 16:59:28 -07002332 for (const auto *FieldInit : Constructor->inits()) {
2333 Expr *InitExpr = FieldInit->getInit();
Richard Trieu858d2ba2013-10-25 00:56:00 +00002334
2335 CheckInitExprContainsUninitializedFields(
2336 SemaRef, InitExpr, UninitializedFields, Constructor);
2337
Stephen Hines651f13c2014-04-23 16:59:28 -07002338 if (FieldDecl *Field = FieldInit->getAnyMember())
Richard Trieu858d2ba2013-10-25 00:56:00 +00002339 UninitializedFields.erase(Field);
2340 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002341 }
2342} // namespace
2343
Stephen Hines651f13c2014-04-23 16:59:28 -07002344/// \brief Enter a new C++ default initializer scope. After calling this, the
2345/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2346/// parsing or instantiating the initializer failed.
2347void Sema::ActOnStartCXXInClassMemberInitializer() {
2348 // Create a synthetic function scope to represent the call to the constructor
2349 // that notionally surrounds a use of this initializer.
2350 PushFunctionScope();
2351}
2352
2353/// \brief This is invoked after parsing an in-class initializer for a
2354/// non-static C++ class member, and after instantiating an in-class initializer
2355/// in a class template. Such actions are deferred until the class is complete.
2356void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2357 SourceLocation InitLoc,
2358 Expr *InitExpr) {
2359 // Pop the notional constructor scope we created earlier.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002360 PopFunctionScopeInfo(nullptr, D);
Stephen Hines651f13c2014-04-23 16:59:28 -07002361
Richard Smith7a614d82011-06-11 17:19:42 +00002362 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002363 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2364 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002365
2366 if (!InitExpr) {
2367 FD->setInvalidDecl();
2368 FD->removeInClassInitializer();
2369 return;
2370 }
2371
Peter Collingbournefef21892011-10-23 18:59:44 +00002372 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2373 FD->setInvalidDecl();
2374 FD->removeInClassInitializer();
2375 return;
2376 }
2377
Richard Smith7a614d82011-06-11 17:19:42 +00002378 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002379 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002380 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002381 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002382 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002383 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002384 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2385 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002386 if (Init.isInvalid()) {
2387 FD->setInvalidDecl();
2388 return;
2389 }
Richard Smith7a614d82011-06-11 17:19:42 +00002390 }
2391
Richard Smith41956372013-01-14 22:39:08 +00002392 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002393 // The initialization of each base and member constitutes a
2394 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002395 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002396 if (Init.isInvalid()) {
2397 FD->setInvalidDecl();
2398 return;
2399 }
2400
2401 InitExpr = Init.release();
2402
2403 FD->setInClassInitializer(InitExpr);
2404}
2405
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002406/// \brief Find the direct and/or virtual base specifiers that
2407/// correspond to the given base type, for use in base initialization
2408/// within a constructor.
2409static bool FindBaseInitializer(Sema &SemaRef,
2410 CXXRecordDecl *ClassDecl,
2411 QualType BaseType,
2412 const CXXBaseSpecifier *&DirectBaseSpec,
2413 const CXXBaseSpecifier *&VirtualBaseSpec) {
2414 // First, check for a direct base class.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002415 DirectBaseSpec = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07002416 for (const auto &Base : ClassDecl->bases()) {
2417 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002418 // We found a direct base of this type. That's what we're
2419 // initializing.
Stephen Hines651f13c2014-04-23 16:59:28 -07002420 DirectBaseSpec = &Base;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002421 break;
2422 }
2423 }
2424
2425 // Check for a virtual base class.
2426 // FIXME: We might be able to short-circuit this if we know in advance that
2427 // there are no virtual bases.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002428 VirtualBaseSpec = nullptr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002429 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2430 // We haven't found a base yet; search the class hierarchy for a
2431 // virtual base class.
2432 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2433 /*DetectVirtual=*/false);
2434 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2435 BaseType, Paths)) {
2436 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2437 Path != Paths.end(); ++Path) {
2438 if (Path->back().Base->isVirtual()) {
2439 VirtualBaseSpec = Path->back().Base;
2440 break;
2441 }
2442 }
2443 }
2444 }
2445
2446 return DirectBaseSpec || VirtualBaseSpec;
2447}
2448
Sebastian Redl6df65482011-09-24 17:48:25 +00002449/// \brief Handle a C++ member initializer using braced-init-list syntax.
2450MemInitResult
2451Sema::ActOnMemInitializer(Decl *ConstructorD,
2452 Scope *S,
2453 CXXScopeSpec &SS,
2454 IdentifierInfo *MemberOrBase,
2455 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002456 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002457 SourceLocation IdLoc,
2458 Expr *InitList,
2459 SourceLocation EllipsisLoc) {
2460 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002461 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002462 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002463}
2464
2465/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002466MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002467Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002468 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002469 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002470 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002471 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002472 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002473 SourceLocation IdLoc,
2474 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002475 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002476 SourceLocation RParenLoc,
2477 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002478 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002479 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002480 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002481 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002482}
2483
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002484namespace {
2485
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002486// Callback to only accept typo corrections that can be a valid C++ member
2487// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002488class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002489public:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002490 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2491 : ClassDecl(ClassDecl) {}
2492
Stephen Hines651f13c2014-04-23 16:59:28 -07002493 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002494 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2495 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2496 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002497 return isa<TypeDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002498 }
2499 return false;
2500 }
2501
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002502private:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002503 CXXRecordDecl *ClassDecl;
2504};
2505
2506}
2507
Sebastian Redl6df65482011-09-24 17:48:25 +00002508/// \brief Handle a C++ member initializer.
2509MemInitResult
2510Sema::BuildMemInitializer(Decl *ConstructorD,
2511 Scope *S,
2512 CXXScopeSpec &SS,
2513 IdentifierInfo *MemberOrBase,
2514 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002515 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002516 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002517 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002518 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002519 if (!ConstructorD)
2520 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002521
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002522 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002523
2524 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002525 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002526 if (!Constructor) {
2527 // The user wrote a constructor initializer on a function that is
2528 // not a C++ constructor. Ignore the error for now, because we may
2529 // have more member initializers coming; we'll diagnose it just
2530 // once in ActOnMemInitializers.
2531 return true;
2532 }
2533
2534 CXXRecordDecl *ClassDecl = Constructor->getParent();
2535
2536 // C++ [class.base.init]p2:
2537 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002538 // constructor's class and, if not found in that scope, are looked
2539 // up in the scope containing the constructor's definition.
2540 // [Note: if the constructor's class contains a member with the
2541 // same name as a direct or virtual base class of the class, a
2542 // mem-initializer-id naming the member or base class and composed
2543 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002544 // mem-initializer-id for the hidden base class may be specified
2545 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002546 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002547 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002548 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002549 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002550 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002551 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002552 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2553 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002554 if (EllipsisLoc.isValid())
2555 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002556 << MemberOrBase
2557 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002558
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002559 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002560 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002561 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002562 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002563 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002564 QualType BaseType;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002565 TypeSourceInfo *TInfo = nullptr;
John McCall2b194412009-12-21 10:41:20 +00002566
2567 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002568 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002569 } else if (DS.getTypeSpecType() == TST_decltype) {
2570 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002571 } else {
2572 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2573 LookupParsedName(R, S, &SS);
2574
2575 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2576 if (!TyD) {
2577 if (R.isAmbiguous()) return true;
2578
John McCallfd225442010-04-09 19:01:14 +00002579 // We don't want access-control diagnostics here.
2580 R.suppressDiagnostics();
2581
Douglas Gregor7a886e12010-01-19 06:46:48 +00002582 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2583 bool NotUnknownSpecialization = false;
2584 DeclContext *DC = computeDeclContext(SS, false);
2585 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2586 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2587
2588 if (!NotUnknownSpecialization) {
2589 // When the scope specifier can refer to a member of an unknown
2590 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002591 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2592 SS.getWithLocInContext(Context),
2593 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002594 if (BaseType.isNull())
2595 return true;
2596
Douglas Gregor7a886e12010-01-19 06:46:48 +00002597 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002598 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002599 }
2600 }
2601
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002602 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002603 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002604 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002605 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002606 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002607 Validator, CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002608 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002609 // We have found a non-static data member with a similar
2610 // name to what was typed; complain and initialize that
2611 // member.
Richard Smith2d670972013-08-17 00:46:16 +00002612 diagnoseTypo(Corr,
2613 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2614 << MemberOrBase << true);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002615 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002616 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002617 const CXXBaseSpecifier *DirectBaseSpec;
2618 const CXXBaseSpecifier *VirtualBaseSpec;
2619 if (FindBaseInitializer(*this, ClassDecl,
2620 Context.getTypeDeclType(Type),
2621 DirectBaseSpec, VirtualBaseSpec)) {
2622 // We have found a direct or virtual base class with a
2623 // similar name to what was typed; complain and initialize
2624 // that base class.
Richard Smith2d670972013-08-17 00:46:16 +00002625 diagnoseTypo(Corr,
2626 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2627 << MemberOrBase << false,
2628 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002629
Richard Smith2d670972013-08-17 00:46:16 +00002630 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2631 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002632 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002633 diag::note_base_class_specified_here)
2634 << BaseSpec->getType()
2635 << BaseSpec->getSourceRange();
2636
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002637 TyD = Type;
2638 }
2639 }
2640 }
2641
Douglas Gregor7a886e12010-01-19 06:46:48 +00002642 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002643 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002644 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002645 return true;
2646 }
John McCall2b194412009-12-21 10:41:20 +00002647 }
2648
Douglas Gregor7a886e12010-01-19 06:46:48 +00002649 if (BaseType.isNull()) {
2650 BaseType = Context.getTypeDeclType(TyD);
Stephen Hines651f13c2014-04-23 16:59:28 -07002651 if (SS.isSet())
Douglas Gregor7a886e12010-01-19 06:46:48 +00002652 // FIXME: preserve source range information
Stephen Hines651f13c2014-04-23 16:59:28 -07002653 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2654 BaseType);
John McCall2b194412009-12-21 10:41:20 +00002655 }
2656 }
Mike Stump1eb44332009-09-09 15:08:12 +00002657
John McCalla93c9342009-12-07 02:54:59 +00002658 if (!TInfo)
2659 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002660
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002661 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002662}
2663
Chandler Carruth81c64772011-09-03 01:14:15 +00002664/// Checks a member initializer expression for cases where reference (or
2665/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002666static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2667 Expr *Init,
2668 SourceLocation IdLoc) {
2669 QualType MemberTy = Member->getType();
2670
2671 // We only handle pointers and references currently.
2672 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2673 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2674 return;
2675
2676 const bool IsPointer = MemberTy->isPointerType();
2677 if (IsPointer) {
2678 if (const UnaryOperator *Op
2679 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2680 // The only case we're worried about with pointers requires taking the
2681 // address.
2682 if (Op->getOpcode() != UO_AddrOf)
2683 return;
2684
2685 Init = Op->getSubExpr();
2686 } else {
2687 // We only handle address-of expression initializers for pointers.
2688 return;
2689 }
2690 }
2691
Richard Smitha4bb99c2013-06-12 21:51:50 +00002692 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002693 // We only warn when referring to a non-reference parameter declaration.
2694 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2695 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002696 return;
2697
2698 S.Diag(Init->getExprLoc(),
2699 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2700 : diag::warn_bind_ref_member_to_parameter)
2701 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002702 } else {
2703 // Other initializers are fine.
2704 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002705 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002706
2707 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2708 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002709}
2710
John McCallf312b1e2010-08-26 23:41:50 +00002711MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002712Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002713 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002714 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2715 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2716 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002717 "Member must be a FieldDecl or IndirectFieldDecl");
2718
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002719 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002720 return true;
2721
Douglas Gregor464b2f02010-11-05 22:21:31 +00002722 if (Member->isInvalidDecl())
2723 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002724
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002725 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002726 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002727 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002728 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002729 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002730 } else {
2731 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002732 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002733 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002734
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002735 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002736
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002737 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002738 // Can't check initialization for a member of dependent type or when
2739 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002740 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002741 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002742 bool InitList = false;
2743 if (isa<InitListExpr>(Init)) {
2744 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002745 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002746 }
2747
Chandler Carruth894aed92010-12-06 09:23:57 +00002748 // Initialize the member.
2749 InitializedEntity MemberEntity =
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002750 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
2751 : InitializedEntity::InitializeMember(IndirectMember,
2752 nullptr);
Chandler Carruth894aed92010-12-06 09:23:57 +00002753 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002754 InitList ? InitializationKind::CreateDirectList(IdLoc)
2755 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2756 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002757
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002758 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002759 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
2760 nullptr);
Chandler Carruth894aed92010-12-06 09:23:57 +00002761 if (MemberInit.isInvalid())
2762 return true;
2763
Richard Smith8a07cd32013-06-12 20:42:33 +00002764 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2765
Richard Smith41956372013-01-14 22:39:08 +00002766 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002767 // The initialization of each base and member constitutes a
2768 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002769 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002770 if (MemberInit.isInvalid())
2771 return true;
2772
Richard Smithc83c2302012-12-19 01:39:02 +00002773 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002774 }
2775
Chandler Carruth894aed92010-12-06 09:23:57 +00002776 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002777 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2778 InitRange.getBegin(), Init,
2779 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002780 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002781 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2782 InitRange.getBegin(), Init,
2783 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002784 }
Eli Friedman59c04372009-07-29 19:44:27 +00002785}
2786
John McCallf312b1e2010-08-26 23:41:50 +00002787MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002788Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002789 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002790 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002791 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002792 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002793 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002794 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002795
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002796 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002797 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002798 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2799 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002800 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002801 }
2802
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002803 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002804 // Initialize the object.
2805 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2806 QualType(ClassDecl->getTypeForDecl(), 0));
2807 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002808 InitList ? InitializationKind::CreateDirectList(NameLoc)
2809 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2810 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002811 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002812 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002813 Args, nullptr);
Sean Hunt41717662011-02-26 19:13:13 +00002814 if (DelegationInit.isInvalid())
2815 return true;
2816
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002817 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2818 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002819
Richard Smith41956372013-01-14 22:39:08 +00002820 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002821 // The initialization of each base and member constitutes a
2822 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002823 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2824 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002825 if (DelegationInit.isInvalid())
2826 return true;
2827
Eli Friedmand21016f2012-05-19 23:35:23 +00002828 // If we are in a dependent context, template instantiation will
2829 // perform this type-checking again. Just save the arguments that we
2830 // received in a ParenListExpr.
2831 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2832 // of the information that we have about the base
2833 // initializer. However, deconstructing the ASTs is a dicey process,
2834 // and this approach is far more likely to get the corner cases right.
2835 if (CurContext->isDependentContext())
2836 DelegationInit = Owned(Init);
2837
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002838 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002839 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002840 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002841}
2842
2843MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002844Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002845 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002846 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002847 SourceLocation BaseLoc
2848 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002849
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002850 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2851 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2852 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2853
2854 // C++ [class.base.init]p2:
2855 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002856 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002857 // of that class, the mem-initializer is ill-formed. A
2858 // mem-initializer-list can initialize a base class using any
2859 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002860 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002861
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002862 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002863 if (EllipsisLoc.isValid()) {
2864 // This is a pack expansion.
2865 if (!BaseType->containsUnexpandedParameterPack()) {
2866 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002867 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002868
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002869 EllipsisLoc = SourceLocation();
2870 }
2871 } else {
2872 // Check for any unexpanded parameter packs.
2873 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2874 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002875
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002876 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002877 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002878 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002879
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002880 // Check for direct and virtual base classes.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002881 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
2882 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002883 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002884 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2885 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002886 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002887
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002888 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2889 VirtualBaseSpec);
2890
2891 // C++ [base.class.init]p2:
2892 // Unless the mem-initializer-id names a nonstatic data member of the
2893 // constructor's class or a direct or virtual base of that class, the
2894 // mem-initializer is ill-formed.
2895 if (!DirectBaseSpec && !VirtualBaseSpec) {
2896 // If the class has any dependent bases, then it's possible that
2897 // one of those types will resolve to the same type as
2898 // BaseType. Therefore, just treat this as a dependent base
2899 // class initialization. FIXME: Should we try to check the
2900 // initialization anyway? It seems odd.
2901 if (ClassDecl->hasAnyDependentBases())
2902 Dependent = true;
2903 else
2904 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2905 << BaseType << Context.getTypeDeclType(ClassDecl)
2906 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2907 }
2908 }
2909
2910 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002911 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002912
Sebastian Redl6df65482011-09-24 17:48:25 +00002913 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2914 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002915 InitRange.getBegin(), Init,
2916 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002917 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002918
2919 // C++ [base.class.init]p2:
2920 // If a mem-initializer-id is ambiguous because it designates both
2921 // a direct non-virtual base class and an inherited virtual base
2922 // class, the mem-initializer is ill-formed.
2923 if (DirectBaseSpec && VirtualBaseSpec)
2924 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002925 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002926
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002927 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002928 if (!BaseSpec)
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002929 BaseSpec = VirtualBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002930
2931 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002932 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002933 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002934 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002935 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002936 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002937 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002938
2939 InitializedEntity BaseEntity =
2940 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2941 InitializationKind Kind =
2942 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2943 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2944 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002945 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002946 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002947 if (BaseInit.isInvalid())
2948 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002949
Richard Smith41956372013-01-14 22:39:08 +00002950 // C++11 [class.base.init]p7:
2951 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002952 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002953 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002954 if (BaseInit.isInvalid())
2955 return true;
2956
2957 // If we are in a dependent context, template instantiation will
2958 // perform this type-checking again. Just save the arguments that we
2959 // received in a ParenListExpr.
2960 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2961 // of the information that we have about the base
2962 // initializer. However, deconstructing the ASTs is a dicey process,
2963 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002964 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002965 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002966
Sean Huntcbb67482011-01-08 20:30:50 +00002967 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002968 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002969 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002970 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002971 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002972}
2973
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002974// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002975static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2976 if (T.isNull()) T = E->getType();
2977 QualType TargetType = SemaRef.BuildReferenceType(
2978 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002979 SourceLocation ExprLoc = E->getLocStart();
2980 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2981 TargetType, ExprLoc);
2982
2983 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2984 SourceRange(ExprLoc, ExprLoc),
2985 E->getSourceRange()).take();
2986}
2987
Anders Carlssone5ef7402010-04-23 03:10:23 +00002988/// ImplicitInitializerKind - How an implicit base or member initializer should
2989/// initialize its base or member.
2990enum ImplicitInitializerKind {
2991 IIK_Default,
2992 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002993 IIK_Move,
2994 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002995};
2996
Anders Carlssondefefd22010-04-23 02:00:02 +00002997static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002998BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002999 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00003000 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00003001 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00003002 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00003003 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00003004 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3005 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00003006
John McCall60d7b3a2010-08-24 06:29:42 +00003007 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00003008
3009 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00003010 case IIK_Inherit: {
3011 const CXXRecordDecl *Inherited =
3012 Constructor->getInheritedConstructor()->getParent();
3013 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3014 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3015 // C++11 [class.inhctor]p8:
3016 // Each expression in the expression-list is of the form
3017 // static_cast<T&&>(p), where p is the name of the corresponding
3018 // constructor parameter and T is the declared type of p.
3019 SmallVector<Expr*, 16> Args;
3020 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3021 ParmVarDecl *PD = Constructor->getParamDecl(I);
3022 ExprResult ArgExpr =
3023 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3024 VK_LValue, SourceLocation());
3025 if (ArgExpr.isInvalid())
3026 return true;
3027 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3028 }
3029
3030 InitializationKind InitKind = InitializationKind::CreateDirect(
3031 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003032 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00003033 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3034 break;
3035 }
3036 }
3037 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00003038 case IIK_Default: {
3039 InitializationKind InitKind
3040 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003041 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3042 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003043 break;
3044 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003045
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003046 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00003047 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003048 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00003049 ParmVarDecl *Param = Constructor->getParamDecl(0);
3050 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00003051
Anders Carlssone5ef7402010-04-23 03:10:23 +00003052 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003053 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00003054 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00003055 Constructor->getLocation(), ParamType,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003056 VK_LValue, nullptr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003057
Eli Friedman5f2987c2012-02-02 03:46:19 +00003058 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3059
Anders Carlssonc7957502010-04-24 22:02:54 +00003060 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00003061 QualType ArgTy =
3062 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3063 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00003064
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003065 if (Moving) {
3066 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3067 }
3068
John McCallf871d0c2010-08-07 06:22:56 +00003069 CXXCastPath BasePath;
3070 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00003071 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3072 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003073 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003074 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00003075
Anders Carlssone5ef7402010-04-23 03:10:23 +00003076 InitializationKind InitKind
3077 = InitializationKind::CreateDirect(Constructor->getLocation(),
3078 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003079 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3080 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003081 break;
3082 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00003083 }
John McCall9ae2f072010-08-23 23:25:46 +00003084
Douglas Gregor53c374f2010-12-07 00:41:46 +00003085 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00003086 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00003087 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00003088
Anders Carlssondefefd22010-04-23 02:00:02 +00003089 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00003090 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00003091 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3092 SourceLocation()),
3093 BaseSpec->isVirtual(),
3094 SourceLocation(),
3095 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003096 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00003097 SourceLocation());
3098
Anders Carlssondefefd22010-04-23 02:00:02 +00003099 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00003100}
3101
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003102static bool RefersToRValueRef(Expr *MemRef) {
3103 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3104 return Referenced->getType()->isRValueReferenceType();
3105}
3106
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003107static bool
3108BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003109 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003110 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00003111 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003112 if (Field->isInvalidDecl())
3113 return true;
3114
Chandler Carruthf186b542010-06-29 23:50:44 +00003115 SourceLocation Loc = Constructor->getLocation();
3116
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003117 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3118 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003119 ParmVarDecl *Param = Constructor->getParamDecl(0);
3120 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00003121
3122 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003123 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3124 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00003125
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003126 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003127 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00003128 SourceLocation(), Param, false,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003129 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003130
Eli Friedman5f2987c2012-02-02 03:46:19 +00003131 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3132
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003133 if (Moving) {
3134 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3135 }
3136
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003137 // Build a reference to this field within the parameter.
3138 CXXScopeSpec SS;
3139 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3140 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003141 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3142 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003143 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00003144 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00003145 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003146 ParamType, Loc,
3147 /*IsArrow=*/false,
3148 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003149 /*TemplateKWLoc=*/SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003150 /*FirstQualifierInScope=*/nullptr,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003151 MemberLookup,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003152 /*TemplateArgs=*/nullptr);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003153 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003154 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003155
3156 // C++11 [class.copy]p15:
3157 // - if a member m has rvalue reference type T&&, it is direct-initialized
3158 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003159 if (RefersToRValueRef(CtorArg.get())) {
3160 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003161 }
3162
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003163 // When the field we are copying is an array, create index variables for
3164 // each dimension of the array. We use these index variables to subscript
3165 // the source array, and other clients (e.g., CodeGen) will perform the
3166 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003167 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003168 QualType BaseType = Field->getType();
3169 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003170 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003171 while (const ConstantArrayType *Array
3172 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003173 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003174 // Create the iteration variable for this array index.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003175 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003176 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003177 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003178 llvm::raw_svector_ostream OS(Str);
3179 OS << "__i" << IndexVariables.size();
3180 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3181 }
3182 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003183 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003184 IterationVarName, SizeType,
3185 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003186 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003187 IndexVariables.push_back(IterationVar);
3188
3189 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003190 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003191 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003192 assert(!IterationVarRef.isInvalid() &&
3193 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003194 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3195 assert(!IterationVarRef.isInvalid() &&
3196 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003197
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003198 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003199 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003200 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003201 Loc);
3202 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003203 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003204
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003205 BaseType = Array->getElementType();
3206 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003207
3208 // The array subscript expression is an lvalue, which is wrong for moving.
3209 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003210 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003211
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003212 // Construct the entity that we will be initializing. For an array, this
3213 // will be first element in the array, which may require several levels
3214 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003215 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003216 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003217 if (Indirect)
3218 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3219 else
3220 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003221 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3222 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3223 0,
3224 Entities.back()));
3225
3226 // Direct-initialize to use the copy constructor.
3227 InitializationKind InitKind =
3228 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3229
Sebastian Redl74e611a2011-09-04 18:14:28 +00003230 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003231 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003232
John McCall60d7b3a2010-08-24 06:29:42 +00003233 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003234 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003235 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003236 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003237 if (MemberInit.isInvalid())
3238 return true;
3239
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003240 if (Indirect) {
3241 assert(IndexVariables.size() == 0 &&
3242 "Indirect field improperly initialized");
3243 CXXMemberInit
3244 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3245 Loc, Loc,
3246 MemberInit.takeAs<Expr>(),
3247 Loc);
3248 } else
3249 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3250 Loc, MemberInit.takeAs<Expr>(),
3251 Loc,
3252 IndexVariables.data(),
3253 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003254 return false;
3255 }
3256
Richard Smith07b0fdc2013-03-18 21:12:30 +00003257 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3258 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003259
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003260 QualType FieldBaseElementType =
3261 SemaRef.Context.getBaseElementType(Field->getType());
3262
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003263 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003264 InitializedEntity InitEntity
3265 = Indirect? InitializedEntity::InitializeMember(Indirect)
3266 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003267 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003268 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003269
3270 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3271 ExprResult MemberInit =
3272 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003273
Douglas Gregor53c374f2010-12-07 00:41:46 +00003274 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003275 if (MemberInit.isInvalid())
3276 return true;
3277
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003278 if (Indirect)
3279 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3280 Indirect, Loc,
3281 Loc,
3282 MemberInit.get(),
3283 Loc);
3284 else
3285 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3286 Field, Loc, Loc,
3287 MemberInit.get(),
3288 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003289 return false;
3290 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003291
Sean Hunt1f2f3842011-05-17 00:19:05 +00003292 if (!Field->getParent()->isUnion()) {
3293 if (FieldBaseElementType->isReferenceType()) {
3294 SemaRef.Diag(Constructor->getLocation(),
3295 diag::err_uninitialized_member_in_ctor)
3296 << (int)Constructor->isImplicit()
3297 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3298 << 0 << Field->getDeclName();
3299 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3300 return true;
3301 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003302
Sean Hunt1f2f3842011-05-17 00:19:05 +00003303 if (FieldBaseElementType.isConstQualified()) {
3304 SemaRef.Diag(Constructor->getLocation(),
3305 diag::err_uninitialized_member_in_ctor)
3306 << (int)Constructor->isImplicit()
3307 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3308 << 1 << Field->getDeclName();
3309 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3310 return true;
3311 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003312 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003313
David Blaikie4e4d0842012-03-11 07:00:24 +00003314 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003315 FieldBaseElementType->isObjCRetainableType() &&
3316 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3317 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003318 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003319 // Default-initialize Objective-C pointers to NULL.
3320 CXXMemberInit
3321 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3322 Loc, Loc,
3323 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3324 Loc);
3325 return false;
3326 }
3327
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003328 // Nothing to initialize.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003329 CXXMemberInit = nullptr;
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003330 return false;
3331}
John McCallf1860e52010-05-20 23:23:51 +00003332
3333namespace {
3334struct BaseAndFieldInfo {
3335 Sema &S;
3336 CXXConstructorDecl *Ctor;
3337 bool AnyErrorsInInits;
3338 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003339 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003340 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Stephen Hines651f13c2014-04-23 16:59:28 -07003341 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallf1860e52010-05-20 23:23:51 +00003342
3343 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3344 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003345 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3346 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003347 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003348 else if (Generated && Ctor->isMoveConstructor())
3349 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003350 else if (Ctor->getInheritedConstructor())
3351 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003352 else
3353 IIK = IIK_Default;
3354 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003355
3356 bool isImplicitCopyOrMove() const {
3357 switch (IIK) {
3358 case IIK_Copy:
3359 case IIK_Move:
3360 return true;
3361
3362 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003363 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003364 return false;
3365 }
David Blaikie30263482012-01-20 21:50:17 +00003366
3367 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003368 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003369
3370 bool addFieldInitializer(CXXCtorInitializer *Init) {
3371 AllToInit.push_back(Init);
3372
3373 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003374 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003375 S.UnusedPrivateFields.remove(Init->getAnyMember());
3376
3377 return false;
3378 }
John McCallf1860e52010-05-20 23:23:51 +00003379
Stephen Hines651f13c2014-04-23 16:59:28 -07003380 bool isInactiveUnionMember(FieldDecl *Field) {
3381 RecordDecl *Record = Field->getParent();
3382 if (!Record->isUnion())
3383 return false;
3384
3385 if (FieldDecl *Active =
3386 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3387 return Active != Field->getCanonicalDecl();
3388
3389 // In an implicit copy or move constructor, ignore any in-class initializer.
3390 if (isImplicitCopyOrMove())
3391 return true;
3392
3393 // If there's no explicit initialization, the field is active only if it
3394 // has an in-class initializer...
3395 if (Field->hasInClassInitializer())
3396 return false;
3397 // ... or it's an anonymous struct or union whose class has an in-class
3398 // initializer.
3399 if (!Field->isAnonymousStructOrUnion())
3400 return true;
3401 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3402 return !FieldRD->hasInClassInitializer();
3403 }
3404
3405 /// \brief Determine whether the given field is, or is within, a union member
3406 /// that is inactive (because there was an initializer given for a different
3407 /// member of the union, or because the union was not initialized at all).
3408 bool isWithinInactiveUnionMember(FieldDecl *Field,
3409 IndirectFieldDecl *Indirect) {
3410 if (!Indirect)
3411 return isInactiveUnionMember(Field);
3412
3413 for (auto *C : Indirect->chain()) {
3414 FieldDecl *Field = dyn_cast<FieldDecl>(C);
3415 if (Field && isInactiveUnionMember(Field))
Richard Smitha4950662011-09-19 13:34:43 +00003416 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07003417 }
3418 return false;
3419 }
3420};
Richard Smitha4950662011-09-19 13:34:43 +00003421}
3422
Douglas Gregorddb21472011-11-02 23:04:16 +00003423/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3424/// array type.
3425static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3426 if (T->isIncompleteArrayType())
3427 return true;
3428
3429 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3430 if (!ArrayT->getSize())
3431 return true;
3432
3433 T = ArrayT->getElementType();
3434 }
3435
3436 return false;
3437}
3438
Richard Smith7a614d82011-06-11 17:19:42 +00003439static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003440 FieldDecl *Field,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003441 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003442 if (Field->isInvalidDecl())
3443 return false;
John McCallf1860e52010-05-20 23:23:51 +00003444
Chandler Carruthe861c602010-06-30 02:59:29 +00003445 // Overwhelmingly common case: we have a direct initializer for this field.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003446 if (CXXCtorInitializer *Init =
3447 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0b8220a2012-08-07 21:30:42 +00003448 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003449
Stephen Hines651f13c2014-04-23 16:59:28 -07003450 // C++11 [class.base.init]p8:
3451 // if the entity is a non-static data member that has a
3452 // brace-or-equal-initializer and either
3453 // -- the constructor's class is a union and no other variant member of that
3454 // union is designated by a mem-initializer-id or
3455 // -- the constructor's class is not a union, and, if the entity is a member
3456 // of an anonymous union, no other member of that union is designated by
3457 // a mem-initializer-id,
3458 // the entity is initialized as specified in [dcl.init].
3459 //
3460 // We also apply the same rules to handle anonymous structs within anonymous
3461 // unions.
3462 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3463 return false;
3464
Douglas Gregorf4853882011-11-28 20:03:15 +00003465 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003466 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3467 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003468 CXXCtorInitializer *Init;
3469 if (Indirect)
3470 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3471 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003472 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003473 SourceLocation());
3474 else
3475 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3476 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003477 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003478 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003479 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003480 }
3481
Douglas Gregorddb21472011-11-02 23:04:16 +00003482 // Don't initialize incomplete or zero-length arrays.
3483 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3484 return false;
3485
John McCallf1860e52010-05-20 23:23:51 +00003486 // Don't try to build an implicit initializer if there were semantic
3487 // errors in any of the initializers (and therefore we might be
3488 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003489 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003490 return false;
3491
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003492 CXXCtorInitializer *Init = nullptr;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003493 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3494 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003495 return true;
John McCallf1860e52010-05-20 23:23:51 +00003496
Richard Smith0b8220a2012-08-07 21:30:42 +00003497 if (!Init)
3498 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003499
Richard Smith0b8220a2012-08-07 21:30:42 +00003500 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003501}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003502
3503bool
3504Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3505 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003506 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003507 Constructor->setNumCtorInitializers(1);
3508 CXXCtorInitializer **initializer =
3509 new (Context) CXXCtorInitializer*[1];
3510 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3511 Constructor->setCtorInitializers(initializer);
3512
Sean Huntb76af9c2011-05-03 23:05:34 +00003513 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003514 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003515 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3516 }
3517
Sean Huntc1598702011-05-05 00:05:47 +00003518 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003519
Sean Hunt059ce0d2011-05-01 07:04:31 +00003520 return false;
3521}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003522
David Blaikie93c86172013-01-17 05:26:25 +00003523bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3524 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003525 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003526 // Just store the initializers as written, they will be checked during
3527 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003528 if (!Initializers.empty()) {
3529 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003530 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003531 new (Context) CXXCtorInitializer*[Initializers.size()];
3532 memcpy(baseOrMemberInitializers, Initializers.data(),
3533 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003534 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003535 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003536
3537 // Let template instantiation know whether we had errors.
3538 if (AnyErrors)
3539 Constructor->setInvalidDecl();
3540
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003541 return false;
3542 }
3543
John McCallf1860e52010-05-20 23:23:51 +00003544 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003545
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003546 // We need to build the initializer AST according to order of construction
3547 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003548 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003549 if (!ClassDecl)
3550 return true;
3551
Eli Friedman80c30da2009-11-09 19:20:36 +00003552 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003553
David Blaikie93c86172013-01-17 05:26:25 +00003554 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003555 CXXCtorInitializer *Member = Initializers[i];
Richard Smithcbc820a2013-07-22 02:56:56 +00003556
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003557 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003558 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Stephen Hines651f13c2014-04-23 16:59:28 -07003559 else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003560 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Stephen Hines651f13c2014-04-23 16:59:28 -07003561
3562 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3563 for (auto *C : F->chain()) {
3564 FieldDecl *FD = dyn_cast<FieldDecl>(C);
3565 if (FD && FD->getParent()->isUnion())
3566 Info.ActiveUnionMember.insert(std::make_pair(
3567 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3568 }
3569 } else if (FieldDecl *FD = Member->getMember()) {
3570 if (FD->getParent()->isUnion())
3571 Info.ActiveUnionMember.insert(std::make_pair(
3572 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3573 }
3574 }
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003575 }
3576
Anders Carlsson711f34a2010-04-21 19:52:01 +00003577 // Keep track of the direct virtual bases.
3578 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Stephen Hines651f13c2014-04-23 16:59:28 -07003579 for (auto &I : ClassDecl->bases()) {
3580 if (I.isVirtual())
3581 DirectVBases.insert(&I);
Anders Carlsson711f34a2010-04-21 19:52:01 +00003582 }
3583
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003584 // Push virtual bases before others.
Stephen Hines651f13c2014-04-23 16:59:28 -07003585 for (auto &VBase : ClassDecl->vbases()) {
Sean Huntcbb67482011-01-08 20:30:50 +00003586 if (CXXCtorInitializer *Value
Stephen Hines651f13c2014-04-23 16:59:28 -07003587 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithcbc820a2013-07-22 02:56:56 +00003588 // [class.base.init]p7, per DR257:
3589 // A mem-initializer where the mem-initializer-id names a virtual base
3590 // class is ignored during execution of a constructor of any class that
3591 // is not the most derived class.
3592 if (ClassDecl->isAbstract()) {
3593 // FIXME: Provide a fixit to remove the base specifier. This requires
3594 // tracking the location of the associated comma for a base specifier.
3595 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Stephen Hines651f13c2014-04-23 16:59:28 -07003596 << VBase.getType() << ClassDecl;
Richard Smithcbc820a2013-07-22 02:56:56 +00003597 DiagnoseAbstractType(ClassDecl);
3598 }
3599
John McCallf1860e52010-05-20 23:23:51 +00003600 Info.AllToInit.push_back(Value);
Richard Smithcbc820a2013-07-22 02:56:56 +00003601 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3602 // [class.base.init]p8, per DR257:
3603 // If a given [...] base class is not named by a mem-initializer-id
3604 // [...] and the entity is not a virtual base class of an abstract
3605 // class, then [...] the entity is default-initialized.
Stephen Hines651f13c2014-04-23 16:59:28 -07003606 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003607 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003608 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Stephen Hines651f13c2014-04-23 16:59:28 -07003609 &VBase, IsInheritedVirtualBase,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003610 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003611 HadError = true;
3612 continue;
3613 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003614
John McCallf1860e52010-05-20 23:23:51 +00003615 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003616 }
3617 }
Mike Stump1eb44332009-09-09 15:08:12 +00003618
John McCallf1860e52010-05-20 23:23:51 +00003619 // Non-virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07003620 for (auto &Base : ClassDecl->bases()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003621 // Virtuals are in the virtual base list and already constructed.
Stephen Hines651f13c2014-04-23 16:59:28 -07003622 if (Base.isVirtual())
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003623 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003624
Sean Huntcbb67482011-01-08 20:30:50 +00003625 if (CXXCtorInitializer *Value
Stephen Hines651f13c2014-04-23 16:59:28 -07003626 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallf1860e52010-05-20 23:23:51 +00003627 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003628 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003629 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003630 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Stephen Hines651f13c2014-04-23 16:59:28 -07003631 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003632 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003633 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003634 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003635 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003636
John McCallf1860e52010-05-20 23:23:51 +00003637 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003638 }
3639 }
Mike Stump1eb44332009-09-09 15:08:12 +00003640
John McCallf1860e52010-05-20 23:23:51 +00003641 // Fields.
Stephen Hines651f13c2014-04-23 16:59:28 -07003642 for (auto *Mem : ClassDecl->decls()) {
3643 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003644 // C++ [class.bit]p2:
3645 // A declaration for a bit-field that omits the identifier declares an
3646 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3647 // initialized.
3648 if (F->isUnnamedBitfield())
3649 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003650
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003651 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003652 // handle anonymous struct/union fields based on their individual
3653 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003654 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003655 continue;
3656
3657 if (CollectFieldInitializer(*this, Info, F))
3658 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003659 continue;
3660 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003661
3662 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003663 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003664 continue;
3665
Stephen Hines651f13c2014-04-23 16:59:28 -07003666 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003667 if (F->getType()->isIncompleteArrayType()) {
3668 assert(ClassDecl->hasFlexibleArrayMember() &&
3669 "Incomplete array type is not valid");
3670 continue;
3671 }
3672
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003673 // Initialize each field of an anonymous struct individually.
3674 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3675 HadError = true;
3676
3677 continue;
3678 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003679 }
Mike Stump1eb44332009-09-09 15:08:12 +00003680
David Blaikie93c86172013-01-17 05:26:25 +00003681 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003682 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003683 Constructor->setNumCtorInitializers(NumInitializers);
3684 CXXCtorInitializer **baseOrMemberInitializers =
3685 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003686 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003687 NumInitializers * sizeof(CXXCtorInitializer*));
3688 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003689
John McCallef027fe2010-03-16 21:39:52 +00003690 // Constructors implicitly reference the base and member
3691 // destructors.
3692 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3693 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003694 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003695
3696 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003697}
3698
David Blaikieee000bb2013-01-17 08:49:22 +00003699static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003700 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003701 const RecordDecl *RD = RT->getDecl();
3702 if (RD->isAnonymousStructOrUnion()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003703 for (auto *Field : RD->fields())
3704 PopulateKeysForFields(Field, IdealInits);
David Blaikieee000bb2013-01-17 08:49:22 +00003705 return;
3706 }
Eli Friedman6347f422009-07-21 19:28:10 +00003707 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003708 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman6347f422009-07-21 19:28:10 +00003709}
3710
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003711static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3712 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003713}
3714
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003715static const void *GetKeyForMember(ASTContext &Context,
3716 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003717 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003718 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003719
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003720 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman6347f422009-07-21 19:28:10 +00003721}
3722
David Blaikie93c86172013-01-17 05:26:25 +00003723static void DiagnoseBaseOrMemInitializerOrder(
3724 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3725 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003726 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003727 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003728
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003729 // Don't check initializers order unless the warning is enabled at the
3730 // location of at least one initializer.
3731 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003732 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003733 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003734 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3735 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003736 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003737 ShouldCheckOrder = true;
3738 break;
3739 }
3740 }
3741 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003742 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003743
John McCalld6ca8da2010-04-10 07:37:23 +00003744 // Build the list of bases and members in the order that they'll
3745 // actually be initialized. The explicit initializers should be in
3746 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003747 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003748
Anders Carlsson071d6102010-04-02 03:38:04 +00003749 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3750
John McCalld6ca8da2010-04-10 07:37:23 +00003751 // 1. Virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07003752 for (const auto &VBase : ClassDecl->vbases())
3753 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003754
John McCalld6ca8da2010-04-10 07:37:23 +00003755 // 2. Non-virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07003756 for (const auto &Base : ClassDecl->bases()) {
3757 if (Base.isVirtual())
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003758 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07003759 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003760 }
Mike Stump1eb44332009-09-09 15:08:12 +00003761
John McCalld6ca8da2010-04-10 07:37:23 +00003762 // 3. Direct fields.
Stephen Hines651f13c2014-04-23 16:59:28 -07003763 for (auto *Field : ClassDecl->fields()) {
Douglas Gregord61db332011-10-10 17:22:13 +00003764 if (Field->isUnnamedBitfield())
3765 continue;
3766
Stephen Hines651f13c2014-04-23 16:59:28 -07003767 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003768 }
3769
John McCalld6ca8da2010-04-10 07:37:23 +00003770 unsigned NumIdealInits = IdealInitKeys.size();
3771 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003772
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003773 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie93c86172013-01-17 05:26:25 +00003774 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003775 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003776 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003777
3778 // Scan forward to try to find this initializer in the idealized
3779 // initializers list.
3780 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3781 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003782 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003783
3784 // If we didn't find this initializer, it must be because we
3785 // scanned past it on a previous iteration. That can only
3786 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003787 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003788 Sema::SemaDiagnosticBuilder D =
3789 SemaRef.Diag(PrevInit->getSourceLocation(),
3790 diag::warn_initializer_out_of_order);
3791
Francois Pichet00eb3f92010-12-04 09:14:42 +00003792 if (PrevInit->isAnyMemberInitializer())
3793 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003794 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003795 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003796
Francois Pichet00eb3f92010-12-04 09:14:42 +00003797 if (Init->isAnyMemberInitializer())
3798 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003799 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003800 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003801
3802 // Move back to the initializer's location in the ideal list.
3803 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3804 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003805 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003806
3807 assert(IdealIndex != NumIdealInits &&
3808 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003809 }
John McCalld6ca8da2010-04-10 07:37:23 +00003810
3811 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003812 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003813}
3814
John McCall3c3ccdb2010-04-10 09:28:51 +00003815namespace {
3816bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003817 CXXCtorInitializer *Init,
3818 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003819 if (!PrevInit) {
3820 PrevInit = Init;
3821 return false;
3822 }
3823
Douglas Gregordc392c12013-03-25 23:28:23 +00003824 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003825 S.Diag(Init->getSourceLocation(),
3826 diag::err_multiple_mem_initialization)
3827 << Field->getDeclName()
3828 << Init->getSourceRange();
3829 else {
John McCallf4c73712011-01-19 06:33:43 +00003830 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003831 assert(BaseClass && "neither field nor base");
3832 S.Diag(Init->getSourceLocation(),
3833 diag::err_multiple_base_initialization)
3834 << QualType(BaseClass, 0)
3835 << Init->getSourceRange();
3836 }
3837 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3838 << 0 << PrevInit->getSourceRange();
3839
3840 return true;
3841}
3842
Sean Huntcbb67482011-01-08 20:30:50 +00003843typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003844typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3845
3846bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003847 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003848 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003849 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003850 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003851 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003852
3853 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003854 if (Parent->isUnion()) {
3855 UnionEntry &En = Unions[Parent];
3856 if (En.first && En.first != Child) {
3857 S.Diag(Init->getSourceLocation(),
3858 diag::err_multiple_mem_union_initialization)
3859 << Field->getDeclName()
3860 << Init->getSourceRange();
3861 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3862 << 0 << En.second->getSourceRange();
3863 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003864 }
3865 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003866 En.first = Child;
3867 En.second = Init;
3868 }
David Blaikie6fe29652011-11-17 06:01:57 +00003869 if (!Parent->isAnonymousStructOrUnion())
3870 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003871 }
3872
3873 Child = Parent;
3874 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003875 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003876
3877 return false;
3878}
3879}
3880
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003881/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003882void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003883 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003884 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003885 bool AnyErrors) {
3886 if (!ConstructorDecl)
3887 return;
3888
3889 AdjustDeclIfTemplate(ConstructorDecl);
3890
3891 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003892 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003893
3894 if (!Constructor) {
3895 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3896 return;
3897 }
3898
John McCall3c3ccdb2010-04-10 09:28:51 +00003899 // Mapping for the duplicate initializers check.
3900 // For member initializers, this is keyed with a FieldDecl*.
3901 // For base initializers, this is keyed with a Type*.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003902 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003903
3904 // Mapping for the inconsistent anonymous-union initializers check.
3905 RedundantUnionMap MemberUnions;
3906
Anders Carlssonea356fb2010-04-02 05:42:15 +00003907 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003908 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003909 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003910
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003911 // Set the source order index.
3912 Init->setSourceOrder(i);
3913
Francois Pichet00eb3f92010-12-04 09:14:42 +00003914 if (Init->isAnyMemberInitializer()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003915 const void *Key = GetKeyForMember(Context, Init);
3916 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall3c3ccdb2010-04-10 09:28:51 +00003917 CheckRedundantUnionInit(*this, Init, MemberUnions))
3918 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003919 } else if (Init->isBaseInitializer()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003920 const void *Key = GetKeyForMember(Context, Init);
John McCall3c3ccdb2010-04-10 09:28:51 +00003921 if (CheckRedundantInit(*this, Init, Members[Key]))
3922 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003923 } else {
3924 assert(Init->isDelegatingInitializer());
3925 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003926 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003927 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003928 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003929 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003930 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003931 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003932 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003933 // Return immediately as the initializer is set.
3934 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003935 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003936 }
3937
Anders Carlssonea356fb2010-04-02 05:42:15 +00003938 if (HadError)
3939 return;
3940
David Blaikie93c86172013-01-17 05:26:25 +00003941 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003942
David Blaikie93c86172013-01-17 05:26:25 +00003943 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu225e9822013-09-16 21:54:53 +00003944
Richard Trieu858d2ba2013-10-25 00:56:00 +00003945 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003946}
3947
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003948void
John McCallef027fe2010-03-16 21:39:52 +00003949Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3950 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003951 // Ignore dependent contexts. Also ignore unions, since their members never
3952 // have destructors implicitly called.
3953 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003954 return;
John McCall58e6f342010-03-16 05:22:47 +00003955
3956 // FIXME: all the access-control diagnostics are positioned on the
3957 // field/base declaration. That's probably good; that said, the
3958 // user might reasonably want to know why the destructor is being
3959 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003960
Anders Carlsson9f853df2009-11-17 04:44:12 +00003961 // Non-static data members.
Stephen Hines651f13c2014-04-23 16:59:28 -07003962 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003963 if (Field->isInvalidDecl())
3964 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003965
3966 // Don't destroy incomplete or zero-length arrays.
3967 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3968 continue;
3969
Anders Carlsson9f853df2009-11-17 04:44:12 +00003970 QualType FieldType = Context.getBaseElementType(Field->getType());
3971
3972 const RecordType* RT = FieldType->getAs<RecordType>();
3973 if (!RT)
3974 continue;
3975
3976 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003977 if (FieldClassDecl->isInvalidDecl())
3978 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003979 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003980 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003981 // The destructor for an implicit anonymous union member is never invoked.
3982 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3983 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003984
Douglas Gregordb89f282010-07-01 22:47:18 +00003985 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003986 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003987 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003988 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003989 << Field->getDeclName()
3990 << FieldType);
3991
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003992 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003993 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003994 }
3995
John McCall58e6f342010-03-16 05:22:47 +00003996 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3997
Anders Carlsson9f853df2009-11-17 04:44:12 +00003998 // Bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07003999 for (const auto &Base : ClassDecl->bases()) {
John McCall58e6f342010-03-16 05:22:47 +00004000 // Bases are always records in a well-formed non-dependent class.
Stephen Hines651f13c2014-04-23 16:59:28 -07004001 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00004002
4003 // Remember direct virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07004004 if (Base.isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00004005 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00004006
John McCall58e6f342010-03-16 05:22:47 +00004007 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004008 // If our base class is invalid, we probably can't get its dtor anyway.
4009 if (BaseClassDecl->isInvalidDecl())
4010 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00004011 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00004012 continue;
John McCall58e6f342010-03-16 05:22:47 +00004013
Douglas Gregordb89f282010-07-01 22:47:18 +00004014 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004015 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00004016
4017 // FIXME: caret should be on the start of the class name
Stephen Hines651f13c2014-04-23 16:59:28 -07004018 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004019 PDiag(diag::err_access_dtor_base)
Stephen Hines651f13c2014-04-23 16:59:28 -07004020 << Base.getType()
4021 << Base.getSourceRange(),
John McCallb9abd8722012-04-07 03:04:20 +00004022 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00004023
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004024 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00004025 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00004026 }
4027
4028 // Virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07004029 for (const auto &VBase : ClassDecl->vbases()) {
John McCall58e6f342010-03-16 05:22:47 +00004030 // Bases are always records in a well-formed non-dependent class.
Stephen Hines651f13c2014-04-23 16:59:28 -07004031 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00004032
4033 // Ignore direct virtual bases.
4034 if (DirectVirtualBases.count(RT))
4035 continue;
4036
John McCall58e6f342010-03-16 05:22:47 +00004037 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004038 // If our base class is invalid, we probably can't get its dtor anyway.
4039 if (BaseClassDecl->isInvalidDecl())
4040 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00004041 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004042 continue;
John McCall58e6f342010-03-16 05:22:47 +00004043
Douglas Gregordb89f282010-07-01 22:47:18 +00004044 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004045 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00004046 if (CheckDestructorAccess(
4047 ClassDecl->getLocation(), Dtor,
4048 PDiag(diag::err_access_dtor_vbase)
Stephen Hines651f13c2014-04-23 16:59:28 -07004049 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer2f686692013-06-22 06:43:58 +00004050 Context.getTypeDeclType(ClassDecl)) ==
4051 AR_accessible) {
4052 CheckDerivedToBaseConversion(
Stephen Hines651f13c2014-04-23 16:59:28 -07004053 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer2f686692013-06-22 06:43:58 +00004054 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004055 SourceRange(), DeclarationName(), nullptr);
David Majnemer2f686692013-06-22 06:43:58 +00004056 }
John McCall58e6f342010-03-16 05:22:47 +00004057
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004058 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00004059 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004060 }
4061}
4062
John McCalld226f652010-08-21 09:40:31 +00004063void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00004064 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004065 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004066
Mike Stump1eb44332009-09-09 15:08:12 +00004067 if (CXXConstructorDecl *Constructor
Richard Trieu858d2ba2013-10-25 00:56:00 +00004068 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie93c86172013-01-17 05:26:25 +00004069 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieu858d2ba2013-10-25 00:56:00 +00004070 DiagnoseUninitializedFields(*this, Constructor);
4071 }
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004072}
4073
Mike Stump1eb44332009-09-09 15:08:12 +00004074bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00004075 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004076 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4077 unsigned DiagID;
4078 AbstractDiagSelID SelID;
4079
4080 public:
4081 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4082 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004083
Stephen Hines651f13c2014-04-23 16:59:28 -07004084 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman2217f852012-08-14 02:06:07 +00004085 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004086 if (SelID == -1)
4087 S.Diag(Loc, DiagID) << T;
4088 else
4089 S.Diag(Loc, DiagID) << SelID << T;
4090 }
4091 } Diagnoser(DiagID, SelID);
4092
4093 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004094}
4095
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00004096bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004097 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004098 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004099 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004100
Anders Carlsson11f21a02009-03-23 19:10:31 +00004101 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004102 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004103
Ted Kremenek6217b802009-07-29 21:53:49 +00004104 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004105 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004106 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004107 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00004108
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004109 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004110 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004111 }
Mike Stump1eb44332009-09-09 15:08:12 +00004112
Ted Kremenek6217b802009-07-29 21:53:49 +00004113 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004114 if (!RT)
4115 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004116
John McCall86ff3082010-02-04 22:26:26 +00004117 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004118
John McCall94c3b562010-08-18 09:41:07 +00004119 // We can't answer whether something is abstract until it has a
4120 // definition. If it's currently being defined, we'll walk back
4121 // over all the declarations when we have a full definition.
4122 const CXXRecordDecl *Def = RD->getDefinition();
4123 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00004124 return false;
4125
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004126 if (!RD->isAbstract())
4127 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004128
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004129 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00004130 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00004131
John McCall94c3b562010-08-18 09:41:07 +00004132 return true;
4133}
4134
4135void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4136 // Check if we've already emitted the list of pure virtual functions
4137 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004138 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00004139 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004140
Richard Smithcbc820a2013-07-22 02:56:56 +00004141 // If the diagnostic is suppressed, don't emit the notes. We're only
4142 // going to emit them once, so try to attach them to a diagnostic we're
4143 // actually going to show.
4144 if (Diags.isLastDiagnosticIgnored())
4145 return;
4146
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004147 CXXFinalOverriderMap FinalOverriders;
4148 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00004149
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004150 // Keep a set of seen pure methods so we won't diagnose the same method
4151 // more than once.
4152 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4153
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004154 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4155 MEnd = FinalOverriders.end();
4156 M != MEnd;
4157 ++M) {
4158 for (OverridingMethods::iterator SO = M->second.begin(),
4159 SOEnd = M->second.end();
4160 SO != SOEnd; ++SO) {
4161 // C++ [class.abstract]p4:
4162 // A class is abstract if it contains or inherits at least one
4163 // pure virtual function for which the final overrider is pure
4164 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00004165
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004166 //
4167 if (SO->second.size() != 1)
4168 continue;
4169
4170 if (!SO->second.front().Method->isPure())
4171 continue;
4172
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004173 if (!SeenPureMethods.insert(SO->second.front().Method))
4174 continue;
4175
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004176 Diag(SO->second.front().Method->getLocation(),
4177 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00004178 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004179 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004180 }
4181
4182 if (!PureVirtualClassDiagSet)
4183 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4184 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004185}
4186
Anders Carlsson8211eff2009-03-24 01:19:16 +00004187namespace {
John McCall94c3b562010-08-18 09:41:07 +00004188struct AbstractUsageInfo {
4189 Sema &S;
4190 CXXRecordDecl *Record;
4191 CanQualType AbstractType;
4192 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00004193
John McCall94c3b562010-08-18 09:41:07 +00004194 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4195 : S(S), Record(Record),
4196 AbstractType(S.Context.getCanonicalType(
4197 S.Context.getTypeDeclType(Record))),
4198 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00004199
John McCall94c3b562010-08-18 09:41:07 +00004200 void DiagnoseAbstractType() {
4201 if (Invalid) return;
4202 S.DiagnoseAbstractType(Record);
4203 Invalid = true;
4204 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00004205
John McCall94c3b562010-08-18 09:41:07 +00004206 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4207};
4208
4209struct CheckAbstractUsage {
4210 AbstractUsageInfo &Info;
4211 const NamedDecl *Ctx;
4212
4213 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4214 : Info(Info), Ctx(Ctx) {}
4215
4216 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4217 switch (TL.getTypeLocClass()) {
4218#define ABSTRACT_TYPELOC(CLASS, PARENT)
4219#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00004220 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00004221#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00004222 }
John McCall94c3b562010-08-18 09:41:07 +00004223 }
Mike Stump1eb44332009-09-09 15:08:12 +00004224
John McCall94c3b562010-08-18 09:41:07 +00004225 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004226 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4227 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4228 if (!TL.getParam(I))
Douglas Gregor70191862011-02-22 23:21:06 +00004229 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07004230
4231 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall94c3b562010-08-18 09:41:07 +00004232 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004233 }
John McCall94c3b562010-08-18 09:41:07 +00004234 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004235
John McCall94c3b562010-08-18 09:41:07 +00004236 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4237 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4238 }
Mike Stump1eb44332009-09-09 15:08:12 +00004239
John McCall94c3b562010-08-18 09:41:07 +00004240 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4241 // Visit the type parameters from a permissive context.
4242 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4243 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4244 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4245 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4246 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4247 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004248 }
John McCall94c3b562010-08-18 09:41:07 +00004249 }
Mike Stump1eb44332009-09-09 15:08:12 +00004250
John McCall94c3b562010-08-18 09:41:07 +00004251 // Visit pointee types from a permissive context.
4252#define CheckPolymorphic(Type) \
4253 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4254 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4255 }
4256 CheckPolymorphic(PointerTypeLoc)
4257 CheckPolymorphic(ReferenceTypeLoc)
4258 CheckPolymorphic(MemberPointerTypeLoc)
4259 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004260 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004261
John McCall94c3b562010-08-18 09:41:07 +00004262 /// Handle all the types we haven't given a more specific
4263 /// implementation for above.
4264 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4265 // Every other kind of type that we haven't called out already
4266 // that has an inner type is either (1) sugar or (2) contains that
4267 // inner type in some way as a subobject.
4268 if (TypeLoc Next = TL.getNextTypeLoc())
4269 return Visit(Next, Sel);
4270
4271 // If there's no inner type and we're in a permissive context,
4272 // don't diagnose.
4273 if (Sel == Sema::AbstractNone) return;
4274
4275 // Check whether the type matches the abstract type.
4276 QualType T = TL.getType();
4277 if (T->isArrayType()) {
4278 Sel = Sema::AbstractArrayType;
4279 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004280 }
John McCall94c3b562010-08-18 09:41:07 +00004281 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4282 if (CT != Info.AbstractType) return;
4283
4284 // It matched; do some magic.
4285 if (Sel == Sema::AbstractArrayType) {
4286 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4287 << T << TL.getSourceRange();
4288 } else {
4289 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4290 << Sel << T << TL.getSourceRange();
4291 }
4292 Info.DiagnoseAbstractType();
4293 }
4294};
4295
4296void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4297 Sema::AbstractDiagSelID Sel) {
4298 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4299}
4300
4301}
4302
4303/// Check for invalid uses of an abstract type in a method declaration.
4304static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4305 CXXMethodDecl *MD) {
4306 // No need to do the check on definitions, which require that
4307 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004308 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004309 return;
4310
4311 // For safety's sake, just ignore it if we don't have type source
4312 // information. This should never happen for non-implicit methods,
4313 // but...
4314 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4315 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4316}
4317
4318/// Check for invalid uses of an abstract type within a class definition.
4319static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4320 CXXRecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004321 for (auto *D : RD->decls()) {
John McCall94c3b562010-08-18 09:41:07 +00004322 if (D->isImplicit()) continue;
4323
4324 // Methods and method templates.
4325 if (isa<CXXMethodDecl>(D)) {
4326 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4327 } else if (isa<FunctionTemplateDecl>(D)) {
4328 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4329 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4330
4331 // Fields and static variables.
4332 } else if (isa<FieldDecl>(D)) {
4333 FieldDecl *FD = cast<FieldDecl>(D);
4334 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4335 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4336 } else if (isa<VarDecl>(D)) {
4337 VarDecl *VD = cast<VarDecl>(D);
4338 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4339 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4340
4341 // Nested classes and class templates.
4342 } else if (isa<CXXRecordDecl>(D)) {
4343 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4344 } else if (isa<ClassTemplateDecl>(D)) {
4345 CheckAbstractClassUsage(Info,
4346 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4347 }
4348 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004349}
4350
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004351/// \brief Perform semantic checks on a class definition that has been
4352/// completing, introducing implicitly-declared members, checking for
4353/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004354void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004355 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004356 return;
4357
John McCall94c3b562010-08-18 09:41:07 +00004358 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4359 AbstractUsageInfo Info(*this, Record);
4360 CheckAbstractClassUsage(Info, Record);
4361 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004362
4363 // If this is not an aggregate type and has no user-declared constructor,
4364 // complain about any non-static data members of reference or const scalar
4365 // type, since they will never get initializers.
4366 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004367 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4368 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004369 bool Complained = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07004370 for (const auto *F : Record->fields()) {
Douglas Gregord61db332011-10-10 17:22:13 +00004371 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004372 continue;
4373
Douglas Gregor325e5932010-04-15 00:00:53 +00004374 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004375 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004376 if (!Complained) {
4377 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4378 << Record->getTagKind() << Record;
4379 Complained = true;
4380 }
4381
4382 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4383 << F->getType()->isReferenceType()
4384 << F->getDeclName();
4385 }
4386 }
4387 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004388
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004389 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004390 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004391
4392 if (Record->getIdentifier()) {
4393 // C++ [class.mem]p13:
4394 // If T is the name of a class, then each of the following shall have a
4395 // name different from T:
4396 // - every member of every anonymous union that is a member of class T.
4397 //
4398 // C++ [class.mem]p14:
4399 // In addition, if class T has a user-declared constructor (12.1), every
4400 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004401 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4402 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4403 ++I) {
4404 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004405 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4406 isa<IndirectFieldDecl>(D)) {
4407 Diag(D->getLocation(), diag::err_member_name_of_class)
4408 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004409 break;
4410 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004411 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004412 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004413
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004414 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004415 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004416 CXXDestructorDecl *dtor = Record->getDestructor();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004417 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4418 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004419 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4420 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4421 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004422
David Majnemer7121bdb2013-10-18 00:33:31 +00004423 if (Record->isAbstract()) {
4424 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4425 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4426 << FA->isSpelledAsSealed();
4427 DiagnoseAbstractType(Record);
4428 }
David Blaikieb6b5b972012-09-21 03:21:07 +00004429 }
4430
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004431 if (!Record->isDependentType()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004432 for (auto *M : Record->methods()) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004433 // See if a method overloads virtual methods in a base
4434 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004435 if (!M->isStatic())
Stephen Hines651f13c2014-04-23 16:59:28 -07004436 DiagnoseHiddenVirtualMethods(M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004437
4438 // Check whether the explicitly-defaulted special members are valid.
4439 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Stephen Hines651f13c2014-04-23 16:59:28 -07004440 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004441
4442 // For an explicitly defaulted or deleted special member, we defer
4443 // determining triviality until the class is complete. That time is now!
4444 if (!M->isImplicit() && !M->isUserProvided()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004445 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004446 if (CSM != CXXInvalid) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004447 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smith1d28caf2012-12-11 01:14:52 +00004448
4449 // Inform the class that we've finished declaring this member.
Stephen Hines651f13c2014-04-23 16:59:28 -07004450 Record->finishedDefaultedOrDeletedMember(M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004451 }
4452 }
4453 }
4454 }
4455
4456 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4457 // function that is not a constructor declares that member function to be
4458 // const. [...] The class of which that function is a member shall be
4459 // a literal type.
4460 //
4461 // If the class has virtual bases, any constexpr members will already have
4462 // been diagnosed by the checks performed on the member declaration, so
4463 // suppress this (less useful) diagnostic.
4464 //
4465 // We delay this until we know whether an explicitly-defaulted (or deleted)
4466 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004467 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004468 !Record->isLiteral() && !Record->getNumVBases()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004469 for (const auto *M : Record->methods()) {
4470 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004471 switch (Record->getTemplateSpecializationKind()) {
4472 case TSK_ImplicitInstantiation:
4473 case TSK_ExplicitInstantiationDeclaration:
4474 case TSK_ExplicitInstantiationDefinition:
4475 // If a template instantiates to a non-literal type, but its members
4476 // instantiate to constexpr functions, the template is technically
4477 // ill-formed, but we allow it for sanity.
4478 continue;
4479
4480 case TSK_Undeclared:
4481 case TSK_ExplicitSpecialization:
4482 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4483 diag::err_constexpr_method_non_literal);
4484 break;
4485 }
4486
4487 // Only produce one error per class.
4488 break;
4489 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004490 }
4491 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004492
Stephen Hines651f13c2014-04-23 16:59:28 -07004493 // ms_struct is a request to use the same ABI rules as MSVC. Check
4494 // whether this class uses any C++ features that are implemented
4495 // completely differently in MSVC, and if so, emit a diagnostic.
4496 // That diagnostic defaults to an error, but we allow projects to
4497 // map it down to a warning (or ignore it). It's a fairly common
4498 // practice among users of the ms_struct pragma to mass-annotate
4499 // headers, sweeping up a bunch of types that the project doesn't
4500 // really rely on MSVC-compatible layout for. We must therefore
4501 // support "ms_struct except for C++ stuff" as a secondary ABI.
4502 if (Record->isMsStruct(Context) &&
4503 (Record->isPolymorphic() || Record->getNumBases())) {
4504 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Huntb2969b12013-10-11 20:19:00 +00004505 }
4506
Richard Smith07b0fdc2013-03-18 21:12:30 +00004507 // Declare inheriting constructors. We do this eagerly here because:
4508 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004509 // constructors from different classes.
4510 // - The lazy declaration of the other implicit constructors is so as to not
4511 // waste space and performance on classes that are not meant to be
4512 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004513 // have inheriting constructors.
4514 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004515}
4516
Stephen Hines651f13c2014-04-23 16:59:28 -07004517/// Look up the special member function that would be called by a special
4518/// member function for a subobject of class type.
4519///
4520/// \param Class The class type of the subobject.
4521/// \param CSM The kind of special member function.
4522/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4523/// \param ConstRHS True if this is a copy operation with a const object
4524/// on its RHS, that is, if the argument to the outer special member
4525/// function is 'const' and this is not a field marked 'mutable'.
4526static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4527 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4528 unsigned FieldQuals, bool ConstRHS) {
4529 unsigned LHSQuals = 0;
4530 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4531 LHSQuals = FieldQuals;
4532
4533 unsigned RHSQuals = FieldQuals;
4534 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4535 RHSQuals = 0;
4536 else if (ConstRHS)
4537 RHSQuals |= Qualifiers::Const;
4538
4539 return S.LookupSpecialMember(Class, CSM,
4540 RHSQuals & Qualifiers::Const,
4541 RHSQuals & Qualifiers::Volatile,
4542 false,
4543 LHSQuals & Qualifiers::Const,
4544 LHSQuals & Qualifiers::Volatile);
4545}
4546
Richard Smith7756afa2012-06-10 05:43:50 +00004547/// Is the special member function which would be selected to perform the
4548/// specified operation on the specified class type a constexpr constructor?
4549static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4550 Sema::CXXSpecialMember CSM,
Stephen Hines651f13c2014-04-23 16:59:28 -07004551 unsigned Quals, bool ConstRHS) {
Richard Smith7756afa2012-06-10 05:43:50 +00004552 Sema::SpecialMemberOverloadResult *SMOR =
Stephen Hines651f13c2014-04-23 16:59:28 -07004553 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smith7756afa2012-06-10 05:43:50 +00004554 if (!SMOR || !SMOR->getMethod())
4555 // A constructor we wouldn't select can't be "involved in initializing"
4556 // anything.
4557 return true;
4558 return SMOR->getMethod()->isConstexpr();
4559}
4560
4561/// Determine whether the specified special member function would be constexpr
4562/// if it were implicitly defined.
4563static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4564 Sema::CXXSpecialMember CSM,
4565 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004566 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004567 return false;
4568
4569 // C++11 [dcl.constexpr]p4:
4570 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004571 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004572 switch (CSM) {
4573 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004574 // Since default constructor lookup is essentially trivial (and cannot
4575 // involve, for instance, template instantiation), we compute whether a
4576 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4577 //
4578 // This is important for performance; we need to know whether the default
4579 // constructor is constexpr to determine whether the type is a literal type.
4580 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4581
Richard Smith7756afa2012-06-10 05:43:50 +00004582 case Sema::CXXCopyConstructor:
4583 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004584 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004585 break;
4586
4587 case Sema::CXXCopyAssignment:
4588 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004589 if (!S.getLangOpts().CPlusPlus1y)
4590 return false;
4591 // In C++1y, we need to perform overload resolution.
4592 Ctor = false;
4593 break;
4594
Richard Smith7756afa2012-06-10 05:43:50 +00004595 case Sema::CXXDestructor:
4596 case Sema::CXXInvalid:
4597 return false;
4598 }
4599
4600 // -- if the class is a non-empty union, or for each non-empty anonymous
4601 // union member of a non-union class, exactly one non-static data member
4602 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004603 //
4604 // If we squint, this is guaranteed, since exactly one non-static data member
4605 // will be initialized (if the constructor isn't deleted), we just don't know
4606 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004607 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004608 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004609
4610 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004611 if (Ctor && ClassDecl->getNumVBases())
4612 return false;
4613
4614 // C++1y [class.copy]p26:
4615 // -- [the class] is a literal type, and
4616 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004617 return false;
4618
4619 // -- every constructor involved in initializing [...] base class
4620 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004621 // -- the assignment operator selected to copy/move each direct base
4622 // class is a constexpr function, and
Stephen Hines651f13c2014-04-23 16:59:28 -07004623 for (const auto &B : ClassDecl->bases()) {
4624 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smith7756afa2012-06-10 05:43:50 +00004625 if (!BaseType) continue;
4626
4627 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -07004628 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smith7756afa2012-06-10 05:43:50 +00004629 return false;
4630 }
4631
4632 // -- every constructor involved in initializing non-static data members
4633 // [...] shall be a constexpr constructor;
4634 // -- every non-static data member and base class sub-object shall be
4635 // initialized
Stephen Hines651f13c2014-04-23 16:59:28 -07004636 // -- for each non-static data member of X that is of class type (or array
Richard Smitha8942d72013-05-07 03:19:20 +00004637 // thereof), the assignment operator selected to copy/move that member is
4638 // a constexpr function
Stephen Hines651f13c2014-04-23 16:59:28 -07004639 for (const auto *F : ClassDecl->fields()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004640 if (F->isInvalidDecl())
4641 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07004642 QualType BaseType = S.Context.getBaseElementType(F->getType());
4643 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004644 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -07004645 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4646 BaseType.getCVRQualifiers(),
4647 ConstArg && !F->isMutable()))
Richard Smith7756afa2012-06-10 05:43:50 +00004648 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004649 }
4650 }
4651
4652 // All OK, it's constexpr!
4653 return true;
4654}
4655
Richard Smithb9d0b762012-07-27 04:22:15 +00004656static Sema::ImplicitExceptionSpecification
4657computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4658 switch (S.getSpecialMember(MD)) {
4659 case Sema::CXXDefaultConstructor:
4660 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4661 case Sema::CXXCopyConstructor:
4662 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4663 case Sema::CXXCopyAssignment:
4664 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4665 case Sema::CXXMoveConstructor:
4666 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4667 case Sema::CXXMoveAssignment:
4668 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4669 case Sema::CXXDestructor:
4670 return S.ComputeDefaultedDtorExceptionSpec(MD);
4671 case Sema::CXXInvalid:
4672 break;
4673 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004674 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4675 "only special members have implicit exception specs");
4676 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004677}
4678
Reid Kleckneref072032013-08-27 23:08:25 +00004679static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4680 CXXMethodDecl *MD) {
4681 FunctionProtoType::ExtProtoInfo EPI;
4682
4683 // Build an exception specification pointing back at this member.
4684 EPI.ExceptionSpecType = EST_Unevaluated;
4685 EPI.ExceptionSpecDecl = MD;
4686
4687 // Set the calling convention to the default for C++ instance methods.
4688 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4689 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4690 /*IsCXXMethod=*/true));
4691 return EPI;
4692}
4693
Richard Smithb9d0b762012-07-27 04:22:15 +00004694void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4695 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4696 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4697 return;
4698
Richard Smithdd25e802012-07-30 23:48:14 +00004699 // Evaluate the exception specification.
4700 ImplicitExceptionSpecification ExceptSpec =
4701 computeImplicitExceptionSpec(*this, Loc, MD);
4702
Stephen Hines651f13c2014-04-23 16:59:28 -07004703 FunctionProtoType::ExtProtoInfo EPI;
4704 ExceptSpec.getEPI(EPI);
4705
Richard Smithdd25e802012-07-30 23:48:14 +00004706 // Update the type of the special member to use it.
Stephen Hines651f13c2014-04-23 16:59:28 -07004707 UpdateExceptionSpec(MD, EPI);
Richard Smithdd25e802012-07-30 23:48:14 +00004708
4709 // A user-provided destructor can be defined outside the class. When that
4710 // happens, be sure to update the exception specification on both
4711 // declarations.
4712 const FunctionProtoType *CanonicalFPT =
4713 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4714 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Stephen Hines651f13c2014-04-23 16:59:28 -07004715 UpdateExceptionSpec(MD->getCanonicalDecl(), EPI);
Richard Smithb9d0b762012-07-27 04:22:15 +00004716}
4717
Richard Smith3003e1d2012-05-15 04:39:51 +00004718void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4719 CXXRecordDecl *RD = MD->getParent();
4720 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004721
Richard Smith3003e1d2012-05-15 04:39:51 +00004722 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4723 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004724
4725 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004726 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004727 bool First = MD == MD->getCanonicalDecl();
4728
4729 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004730
4731 // C++11 [dcl.fct.def.default]p1:
4732 // A function that is explicitly defaulted shall
4733 // -- be a special member function (checked elsewhere),
4734 // -- have the same type (except for ref-qualifiers, and except that a
4735 // copy operation can take a non-const reference) as an implicit
4736 // declaration, and
4737 // -- not have default arguments.
4738 unsigned ExpectedParams = 1;
4739 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4740 ExpectedParams = 0;
4741 if (MD->getNumParams() != ExpectedParams) {
4742 // This also checks for default arguments: a copy or move constructor with a
4743 // default argument is classified as a default constructor, and assignment
4744 // operations and destructors can't have default arguments.
4745 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4746 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004747 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004748 } else if (MD->isVariadic()) {
4749 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4750 << CSM << MD->getSourceRange();
4751 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004752 }
4753
Richard Smith3003e1d2012-05-15 04:39:51 +00004754 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004755
Richard Smith7756afa2012-06-10 05:43:50 +00004756 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004757 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004758 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004759 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004760 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004761
Richard Smith3003e1d2012-05-15 04:39:51 +00004762 QualType ReturnType = Context.VoidTy;
4763 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4764 // Check for return type matching.
Stephen Hines651f13c2014-04-23 16:59:28 -07004765 ReturnType = Type->getReturnType();
Richard Smith3003e1d2012-05-15 04:39:51 +00004766 QualType ExpectedReturnType =
4767 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4768 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4769 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4770 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4771 HadError = true;
4772 }
4773
4774 // A defaulted special member cannot have cv-qualifiers.
4775 if (Type->getTypeQuals()) {
4776 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004777 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004778 HadError = true;
4779 }
4780 }
4781
4782 // Check for parameter type matching.
Stephen Hines651f13c2014-04-23 16:59:28 -07004783 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004784 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004785 if (ExpectedParams && ArgType->isReferenceType()) {
4786 // Argument must be reference to possibly-const T.
4787 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004788 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004789
4790 if (ReferentType.isVolatileQualified()) {
4791 Diag(MD->getLocation(),
4792 diag::err_defaulted_special_member_volatile_param) << CSM;
4793 HadError = true;
4794 }
4795
Richard Smith7756afa2012-06-10 05:43:50 +00004796 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004797 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4798 Diag(MD->getLocation(),
4799 diag::err_defaulted_special_member_copy_const_param)
4800 << (CSM == CXXCopyAssignment);
4801 // FIXME: Explain why this special member can't be const.
4802 } else {
4803 Diag(MD->getLocation(),
4804 diag::err_defaulted_special_member_move_const_param)
4805 << (CSM == CXXMoveAssignment);
4806 }
4807 HadError = true;
4808 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004809 } else if (ExpectedParams) {
4810 // A copy assignment operator can take its argument by value, but a
4811 // defaulted one cannot.
4812 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004813 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004814 HadError = true;
4815 }
Sean Huntbe631222011-05-17 20:44:43 +00004816
Richard Smith61802452011-12-22 02:22:31 +00004817 // C++11 [dcl.fct.def.default]p2:
4818 // An explicitly-defaulted function may be declared constexpr only if it
4819 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004820 // Do not apply this rule to members of class templates, since core issue 1358
4821 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004822 // functions which cannot be constexpr (for non-constructors in C++11 and for
4823 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004824 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4825 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004826 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4827 : isa<CXXConstructorDecl>(MD)) &&
4828 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004829 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4830 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004831 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004832 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004833 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004834
Richard Smith61802452011-12-22 02:22:31 +00004835 // and may have an explicit exception-specification only if it is compatible
4836 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004837 if (Type->hasExceptionSpec()) {
4838 // Delay the check if this is the first declaration of the special member,
4839 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004840 if (First) {
4841 // If the exception specification needs to be instantiated, do so now,
4842 // before we clobber it with an EST_Unevaluated specification below.
4843 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4844 InstantiateExceptionSpec(MD->getLocStart(), MD);
4845 Type = MD->getType()->getAs<FunctionProtoType>();
4846 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004847 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004848 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004849 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4850 }
Richard Smith61802452011-12-22 02:22:31 +00004851
4852 // If a function is explicitly defaulted on its first declaration,
4853 if (First) {
4854 // -- it is implicitly considered to be constexpr if the implicit
4855 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004856 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004857
Richard Smith3003e1d2012-05-15 04:39:51 +00004858 // -- it is implicitly considered to have the same exception-specification
4859 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004860 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4861 EPI.ExceptionSpecType = EST_Unevaluated;
4862 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004863 MD->setType(Context.getFunctionType(ReturnType,
4864 ArrayRef<QualType>(&ArgType,
4865 ExpectedParams),
4866 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004867 }
4868
Richard Smith3003e1d2012-05-15 04:39:51 +00004869 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004870 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004871 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004872 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004873 // C++11 [dcl.fct.def.default]p4:
4874 // [For a] user-provided explicitly-defaulted function [...] if such a
4875 // function is implicitly defined as deleted, the program is ill-formed.
4876 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Stephen Hines651f13c2014-04-23 16:59:28 -07004877 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smith3003e1d2012-05-15 04:39:51 +00004878 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004879 }
4880 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004881
Richard Smith3003e1d2012-05-15 04:39:51 +00004882 if (HadError)
4883 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004884}
4885
Richard Smith1d28caf2012-12-11 01:14:52 +00004886/// Check whether the exception specification provided for an
4887/// explicitly-defaulted special member matches the exception specification
4888/// that would have been generated for an implicit special member, per
4889/// C++11 [dcl.fct.def.default]p2.
4890void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4891 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4892 // Compute the implicit exception specification.
Reid Kleckneref072032013-08-27 23:08:25 +00004893 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4894 /*IsCXXMethod=*/true);
4895 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith1d28caf2012-12-11 01:14:52 +00004896 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4897 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004898 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004899
4900 // Ensure that it matches.
4901 CheckEquivalentExceptionSpec(
4902 PDiag(diag::err_incorrect_defaulted_exception_spec)
4903 << getSpecialMember(MD), PDiag(),
4904 ImplicitType, SourceLocation(),
4905 SpecifiedType, MD->getLocation());
4906}
4907
Alp Toker08235662013-10-18 05:54:19 +00004908void Sema::CheckDelayedMemberExceptionSpecs() {
4909 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4910 2> Checks;
4911 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smith1d28caf2012-12-11 01:14:52 +00004912
Alp Toker08235662013-10-18 05:54:19 +00004913 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4914 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4915
4916 // Perform any deferred checking of exception specifications for virtual
4917 // destructors.
4918 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4919 const CXXDestructorDecl *Dtor = Checks[i].first;
4920 assert(!Dtor->getParent()->isDependentType() &&
4921 "Should not ever add destructors of templates into the list.");
4922 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4923 }
4924
4925 // Check that any explicitly-defaulted methods have exception specifications
4926 // compatible with their implicit exception specifications.
4927 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4928 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4929 Specs[I].second);
Richard Smith1d28caf2012-12-11 01:14:52 +00004930}
4931
Richard Smith7d5088a2012-02-18 02:02:13 +00004932namespace {
4933struct SpecialMemberDeletionInfo {
4934 Sema &S;
4935 CXXMethodDecl *MD;
4936 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004937 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004938
4939 // Properties of the special member, computed for convenience.
Stephen Hines651f13c2014-04-23 16:59:28 -07004940 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smith7d5088a2012-02-18 02:02:13 +00004941 SourceLocation Loc;
4942
4943 bool AllFieldsAreConst;
4944
4945 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004946 Sema::CXXSpecialMember CSM, bool Diagnose)
4947 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004948 IsConstructor(false), IsAssignment(false), IsMove(false),
Stephen Hines651f13c2014-04-23 16:59:28 -07004949 ConstArg(false), Loc(MD->getLocation()),
Richard Smith7d5088a2012-02-18 02:02:13 +00004950 AllFieldsAreConst(true) {
4951 switch (CSM) {
4952 case Sema::CXXDefaultConstructor:
4953 case Sema::CXXCopyConstructor:
4954 IsConstructor = true;
4955 break;
4956 case Sema::CXXMoveConstructor:
4957 IsConstructor = true;
4958 IsMove = true;
4959 break;
4960 case Sema::CXXCopyAssignment:
4961 IsAssignment = true;
4962 break;
4963 case Sema::CXXMoveAssignment:
4964 IsAssignment = true;
4965 IsMove = true;
4966 break;
4967 case Sema::CXXDestructor:
4968 break;
4969 case Sema::CXXInvalid:
4970 llvm_unreachable("invalid special member kind");
4971 }
4972
4973 if (MD->getNumParams()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004974 if (const ReferenceType *RT =
4975 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
4976 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smith7d5088a2012-02-18 02:02:13 +00004977 }
4978 }
4979
4980 bool inUnion() const { return MD->getParent()->isUnion(); }
4981
4982 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004983 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Stephen Hines651f13c2014-04-23 16:59:28 -07004984 unsigned Quals, bool IsMutable) {
4985 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
4986 ConstArg && !IsMutable);
Richard Smith7d5088a2012-02-18 02:02:13 +00004987 }
4988
Richard Smith6c4c36c2012-03-30 20:53:28 +00004989 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004990
Richard Smith6c4c36c2012-03-30 20:53:28 +00004991 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004992 bool shouldDeleteForField(FieldDecl *FD);
4993 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004994
Richard Smith517bb842012-07-18 03:51:16 +00004995 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4996 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004997 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4998 Sema::SpecialMemberOverloadResult *SMOR,
4999 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00005000
5001 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00005002};
5003}
5004
John McCall12d8d802012-04-09 20:53:23 +00005005/// Is the given special member inaccessible when used on the given
5006/// sub-object.
5007bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5008 CXXMethodDecl *target) {
5009 /// If we're operating on a base class, the object type is the
5010 /// type of this special member.
5011 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00005012 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00005013 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5014 objectTy = S.Context.getTypeDeclType(MD->getParent());
5015 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5016
5017 // If we're operating on a field, the object type is the type of the field.
5018 } else {
5019 objectTy = S.Context.getTypeDeclType(target->getParent());
5020 }
5021
5022 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5023}
5024
Richard Smith6c4c36c2012-03-30 20:53:28 +00005025/// Check whether we should delete a special member due to the implicit
5026/// definition containing a call to a special member of a subobject.
5027bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5028 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5029 bool IsDtorCallInCtor) {
5030 CXXMethodDecl *Decl = SMOR->getMethod();
5031 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5032
5033 int DiagKind = -1;
5034
5035 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5036 DiagKind = !Decl ? 0 : 1;
5037 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5038 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00005039 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00005040 DiagKind = 3;
5041 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5042 !Decl->isTrivial()) {
5043 // A member of a union must have a trivial corresponding special member.
5044 // As a weird special case, a destructor call from a union's constructor
5045 // must be accessible and non-deleted, but need not be trivial. Such a
5046 // destructor is never actually called, but is semantically checked as
5047 // if it were.
5048 DiagKind = 4;
5049 }
5050
5051 if (DiagKind == -1)
5052 return false;
5053
5054 if (Diagnose) {
5055 if (Field) {
5056 S.Diag(Field->getLocation(),
5057 diag::note_deleted_special_member_class_subobject)
5058 << CSM << MD->getParent() << /*IsField*/true
5059 << Field << DiagKind << IsDtorCallInCtor;
5060 } else {
5061 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5062 S.Diag(Base->getLocStart(),
5063 diag::note_deleted_special_member_class_subobject)
5064 << CSM << MD->getParent() << /*IsField*/false
5065 << Base->getType() << DiagKind << IsDtorCallInCtor;
5066 }
5067
5068 if (DiagKind == 1)
5069 S.NoteDeletedFunction(Decl);
5070 // FIXME: Explain inaccessibility if DiagKind == 3.
5071 }
5072
5073 return true;
5074}
5075
Richard Smith9a561d52012-02-26 09:11:52 +00005076/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00005077/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00005078bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00005079 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005080 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Stephen Hines651f13c2014-04-23 16:59:28 -07005081 bool IsMutable = Field && Field->isMutable();
Richard Smith7d5088a2012-02-18 02:02:13 +00005082
5083 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00005084 // -- any direct or virtual base class, or non-static data member with no
5085 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00005086 // either M has no default constructor or overload resolution as applied
5087 // to M's default constructor results in an ambiguity or in a function
5088 // that is deleted or inaccessible
5089 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5090 // -- a direct or virtual base class B that cannot be copied/moved because
5091 // overload resolution, as applied to B's corresponding special member,
5092 // results in an ambiguity or a function that is deleted or inaccessible
5093 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00005094 // C++11 [class.dtor]p5:
5095 // -- any direct or virtual base class [...] has a type with a destructor
5096 // that is deleted or inaccessible
5097 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00005098 Field && Field->hasInClassInitializer()) &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005099 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5100 false))
Richard Smith1c931be2012-04-02 18:40:40 +00005101 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005102
Richard Smith6c4c36c2012-03-30 20:53:28 +00005103 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5104 // -- any direct or virtual base class or non-static data member has a
5105 // type with a destructor that is deleted or inaccessible
5106 if (IsConstructor) {
5107 Sema::SpecialMemberOverloadResult *SMOR =
5108 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5109 false, false, false, false, false);
5110 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5111 return true;
5112 }
5113
Richard Smith9a561d52012-02-26 09:11:52 +00005114 return false;
5115}
5116
5117/// Check whether we should delete a special member function due to the class
5118/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005119bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00005120 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00005121 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00005122}
5123
5124/// Check whether we should delete a special member function due to the class
5125/// having a particular non-static data member.
5126bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5127 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5128 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5129
5130 if (CSM == Sema::CXXDefaultConstructor) {
5131 // For a default constructor, all references must be initialized in-class
5132 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005133 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5134 if (Diagnose)
5135 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5136 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005137 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005138 }
Richard Smith79363f52012-02-27 06:07:25 +00005139 // C++11 [class.ctor]p5: any non-variant non-static data member of
5140 // const-qualified type (or array thereof) with no
5141 // brace-or-equal-initializer does not have a user-provided default
5142 // constructor.
5143 if (!inUnion() && FieldType.isConstQualified() &&
5144 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005145 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5146 if (Diagnose)
5147 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005148 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00005149 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005150 }
5151
5152 if (inUnion() && !FieldType.isConstQualified())
5153 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005154 } else if (CSM == Sema::CXXCopyConstructor) {
5155 // For a copy constructor, data members must not be of rvalue reference
5156 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005157 if (FieldType->isRValueReferenceType()) {
5158 if (Diagnose)
5159 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5160 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00005161 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005162 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005163 } else if (IsAssignment) {
5164 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005165 if (FieldType->isReferenceType()) {
5166 if (Diagnose)
5167 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5168 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005169 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005170 }
5171 if (!FieldRecord && FieldType.isConstQualified()) {
5172 // C++11 [class.copy]p23:
5173 // -- a non-static data member of const non-class type (or array thereof)
5174 if (Diagnose)
5175 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005176 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005177 return true;
5178 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005179 }
5180
5181 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00005182 // Some additional restrictions exist on the variant members.
5183 if (!inUnion() && FieldRecord->isUnion() &&
5184 FieldRecord->isAnonymousStructOrUnion()) {
5185 bool AllVariantFieldsAreConst = true;
5186
Richard Smithdf8dc862012-03-29 19:00:10 +00005187 // FIXME: Handle anonymous unions declared within anonymous unions.
Stephen Hines651f13c2014-04-23 16:59:28 -07005188 for (auto *UI : FieldRecord->fields()) {
Richard Smith7d5088a2012-02-18 02:02:13 +00005189 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00005190
5191 if (!UnionFieldType.isConstQualified())
5192 AllVariantFieldsAreConst = false;
5193
Richard Smith9a561d52012-02-26 09:11:52 +00005194 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5195 if (UnionFieldRecord &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005196 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smith517bb842012-07-18 03:51:16 +00005197 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00005198 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005199 }
5200
5201 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00005202 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005203 !FieldRecord->field_empty()) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005204 if (Diagnose)
5205 S.Diag(FieldRecord->getLocation(),
5206 diag::note_deleted_default_ctor_all_const)
5207 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00005208 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005209 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005210
Richard Smithdf8dc862012-03-29 19:00:10 +00005211 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00005212 // This is technically non-conformant, but sanity demands it.
5213 return false;
5214 }
5215
Richard Smith517bb842012-07-18 03:51:16 +00005216 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5217 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00005218 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005219 }
5220
5221 return false;
5222}
5223
5224/// C++11 [class.ctor] p5:
5225/// A defaulted default constructor for a class X is defined as deleted if
5226/// X is a union and all of its variant members are of const-qualified type.
5227bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00005228 // This is a silly definition, because it gives an empty union a deleted
5229 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005230 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005231 !MD->getParent()->field_empty()) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005232 if (Diagnose)
5233 S.Diag(MD->getParent()->getLocation(),
5234 diag::note_deleted_default_ctor_all_const)
5235 << MD->getParent() << /*not anonymous union*/0;
5236 return true;
5237 }
5238 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005239}
5240
5241/// Determine whether a defaulted special member function should be defined as
5242/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5243/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005244bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5245 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00005246 if (MD->isInvalidDecl())
5247 return false;
Sean Hunte16da072011-10-10 06:18:57 +00005248 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00005249 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00005250 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005251 return false;
5252
Richard Smith7d5088a2012-02-18 02:02:13 +00005253 // C++11 [expr.lambda.prim]p19:
5254 // The closure type associated with a lambda-expression has a
5255 // deleted (8.4.3) default constructor and a deleted copy
5256 // assignment operator.
5257 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005258 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5259 if (Diagnose)
5260 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00005261 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005262 }
5263
Richard Smith5bdaac52012-04-02 20:59:25 +00005264 // For an anonymous struct or union, the copy and assignment special members
5265 // will never be used, so skip the check. For an anonymous union declared at
5266 // namespace scope, the constructor and destructor are used.
5267 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5268 RD->isAnonymousStructOrUnion())
5269 return false;
5270
Richard Smith6c4c36c2012-03-30 20:53:28 +00005271 // C++11 [class.copy]p7, p18:
5272 // If the class definition declares a move constructor or move assignment
5273 // operator, an implicitly declared copy constructor or copy assignment
5274 // operator is defined as deleted.
5275 if (MD->isImplicit() &&
5276 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005277 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005278
5279 // In Microsoft mode, a user-declared move only causes the deletion of the
5280 // corresponding copy operation, not both copy operations.
5281 if (RD->hasUserDeclaredMoveConstructor() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005282 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005283 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005284
5285 // Find any user-declared move constructor.
Stephen Hines651f13c2014-04-23 16:59:28 -07005286 for (auto *I : RD->ctors()) {
Richard Smith55798652012-12-08 04:10:18 +00005287 if (I->isMoveConstructor()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005288 UserDeclaredMove = I;
Richard Smith55798652012-12-08 04:10:18 +00005289 break;
5290 }
5291 }
Richard Smith1c931be2012-04-02 18:40:40 +00005292 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005293 } else if (RD->hasUserDeclaredMoveAssignment() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005294 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005295 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005296
5297 // Find any user-declared move assignment operator.
Stephen Hines651f13c2014-04-23 16:59:28 -07005298 for (auto *I : RD->methods()) {
Richard Smith55798652012-12-08 04:10:18 +00005299 if (I->isMoveAssignmentOperator()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005300 UserDeclaredMove = I;
Richard Smith55798652012-12-08 04:10:18 +00005301 break;
5302 }
5303 }
Richard Smith1c931be2012-04-02 18:40:40 +00005304 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005305 }
5306
5307 if (UserDeclaredMove) {
5308 Diag(UserDeclaredMove->getLocation(),
5309 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005310 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005311 << UserDeclaredMove->isMoveAssignmentOperator();
5312 return true;
5313 }
5314 }
Sean Hunte16da072011-10-10 06:18:57 +00005315
Richard Smith5bdaac52012-04-02 20:59:25 +00005316 // Do access control from the special member function
5317 ContextRAII MethodContext(*this, MD);
5318
Richard Smith9a561d52012-02-26 09:11:52 +00005319 // C++11 [class.dtor]p5:
5320 // -- for a virtual destructor, lookup of the non-array deallocation function
5321 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005322 if (CSM == CXXDestructor && MD->isVirtual()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005323 FunctionDecl *OperatorDelete = nullptr;
Richard Smith9a561d52012-02-26 09:11:52 +00005324 DeclarationName Name =
5325 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5326 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005327 OperatorDelete, false)) {
5328 if (Diagnose)
5329 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005330 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005331 }
Richard Smith9a561d52012-02-26 09:11:52 +00005332 }
5333
Richard Smith6c4c36c2012-03-30 20:53:28 +00005334 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005335
Stephen Hines651f13c2014-04-23 16:59:28 -07005336 for (auto &BI : RD->bases())
5337 if (!BI.isVirtual() &&
5338 SMI.shouldDeleteForBase(&BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005339 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005340
Richard Smithe0883602013-07-22 18:06:23 +00005341 // Per DR1611, do not consider virtual bases of constructors of abstract
5342 // classes, since we are not going to construct them.
Richard Smithcbc820a2013-07-22 02:56:56 +00005343 if (!RD->isAbstract() || !SMI.IsConstructor) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005344 for (auto &BI : RD->vbases())
5345 if (SMI.shouldDeleteForBase(&BI))
Richard Smithcbc820a2013-07-22 02:56:56 +00005346 return true;
5347 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00005348
Stephen Hines651f13c2014-04-23 16:59:28 -07005349 for (auto *FI : RD->fields())
Richard Smith7d5088a2012-02-18 02:02:13 +00005350 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005351 SMI.shouldDeleteForField(FI))
Sean Hunte3406822011-05-20 21:43:47 +00005352 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005353
Richard Smith7d5088a2012-02-18 02:02:13 +00005354 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005355 return true;
5356
5357 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005358}
5359
Richard Smithac713512012-12-08 02:53:02 +00005360/// Perform lookup for a special member of the specified kind, and determine
5361/// whether it is trivial. If the triviality can be determined without the
5362/// lookup, skip it. This is intended for use when determining whether a
5363/// special member of a containing object is trivial, and thus does not ever
5364/// perform overload resolution for default constructors.
5365///
5366/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5367/// member that was most likely to be intended to be trivial, if any.
5368static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5369 Sema::CXXSpecialMember CSM, unsigned Quals,
Stephen Hines651f13c2014-04-23 16:59:28 -07005370 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smithac713512012-12-08 02:53:02 +00005371 if (Selected)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005372 *Selected = nullptr;
Richard Smithac713512012-12-08 02:53:02 +00005373
5374 switch (CSM) {
5375 case Sema::CXXInvalid:
5376 llvm_unreachable("not a special member");
5377
5378 case Sema::CXXDefaultConstructor:
5379 // C++11 [class.ctor]p5:
5380 // A default constructor is trivial if:
5381 // - all the [direct subobjects] have trivial default constructors
5382 //
5383 // Note, no overload resolution is performed in this case.
5384 if (RD->hasTrivialDefaultConstructor())
5385 return true;
5386
5387 if (Selected) {
5388 // If there's a default constructor which could have been trivial, dig it
5389 // out. Otherwise, if there's any user-provided default constructor, point
5390 // to that as an example of why there's not a trivial one.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005391 CXXConstructorDecl *DefCtor = nullptr;
Richard Smithac713512012-12-08 02:53:02 +00005392 if (RD->needsImplicitDefaultConstructor())
5393 S.DeclareImplicitDefaultConstructor(RD);
Stephen Hines651f13c2014-04-23 16:59:28 -07005394 for (auto *CI : RD->ctors()) {
Richard Smithac713512012-12-08 02:53:02 +00005395 if (!CI->isDefaultConstructor())
5396 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07005397 DefCtor = CI;
Richard Smithac713512012-12-08 02:53:02 +00005398 if (!DefCtor->isUserProvided())
5399 break;
5400 }
5401
5402 *Selected = DefCtor;
5403 }
5404
5405 return false;
5406
5407 case Sema::CXXDestructor:
5408 // C++11 [class.dtor]p5:
5409 // A destructor is trivial if:
5410 // - all the direct [subobjects] have trivial destructors
5411 if (RD->hasTrivialDestructor())
5412 return true;
5413
5414 if (Selected) {
5415 if (RD->needsImplicitDestructor())
5416 S.DeclareImplicitDestructor(RD);
5417 *Selected = RD->getDestructor();
5418 }
5419
5420 return false;
5421
5422 case Sema::CXXCopyConstructor:
5423 // C++11 [class.copy]p12:
5424 // A copy constructor is trivial if:
5425 // - the constructor selected to copy each direct [subobject] is trivial
5426 if (RD->hasTrivialCopyConstructor()) {
5427 if (Quals == Qualifiers::Const)
5428 // We must either select the trivial copy constructor or reach an
5429 // ambiguity; no need to actually perform overload resolution.
5430 return true;
5431 } else if (!Selected) {
5432 return false;
5433 }
5434 // In C++98, we are not supposed to perform overload resolution here, but we
5435 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5436 // cases like B as having a non-trivial copy constructor:
5437 // struct A { template<typename T> A(T&); };
5438 // struct B { mutable A a; };
5439 goto NeedOverloadResolution;
5440
5441 case Sema::CXXCopyAssignment:
5442 // C++11 [class.copy]p25:
5443 // A copy assignment operator is trivial if:
5444 // - the assignment operator selected to copy each direct [subobject] is
5445 // trivial
5446 if (RD->hasTrivialCopyAssignment()) {
5447 if (Quals == Qualifiers::Const)
5448 return true;
5449 } else if (!Selected) {
5450 return false;
5451 }
5452 // In C++98, we are not supposed to perform overload resolution here, but we
5453 // treat that as a language defect.
5454 goto NeedOverloadResolution;
5455
5456 case Sema::CXXMoveConstructor:
5457 case Sema::CXXMoveAssignment:
5458 NeedOverloadResolution:
5459 Sema::SpecialMemberOverloadResult *SMOR =
Stephen Hines651f13c2014-04-23 16:59:28 -07005460 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smithac713512012-12-08 02:53:02 +00005461
5462 // The standard doesn't describe how to behave if the lookup is ambiguous.
5463 // We treat it as not making the member non-trivial, just like the standard
5464 // mandates for the default constructor. This should rarely matter, because
5465 // the member will also be deleted.
5466 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5467 return true;
5468
5469 if (!SMOR->getMethod()) {
5470 assert(SMOR->getKind() ==
5471 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5472 return false;
5473 }
5474
5475 // We deliberately don't check if we found a deleted special member. We're
5476 // not supposed to!
5477 if (Selected)
5478 *Selected = SMOR->getMethod();
5479 return SMOR->getMethod()->isTrivial();
5480 }
5481
5482 llvm_unreachable("unknown special method kind");
5483}
5484
Benjamin Kramera574c892013-02-15 12:30:38 +00005485static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005486 for (auto *CI : RD->ctors())
Richard Smithac713512012-12-08 02:53:02 +00005487 if (!CI->isImplicit())
Stephen Hines651f13c2014-04-23 16:59:28 -07005488 return CI;
Richard Smithac713512012-12-08 02:53:02 +00005489
5490 // Look for constructor templates.
5491 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5492 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5493 if (CXXConstructorDecl *CD =
5494 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5495 return CD;
5496 }
5497
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005498 return nullptr;
Richard Smithac713512012-12-08 02:53:02 +00005499}
5500
5501/// The kind of subobject we are checking for triviality. The values of this
5502/// enumeration are used in diagnostics.
5503enum TrivialSubobjectKind {
5504 /// The subobject is a base class.
5505 TSK_BaseClass,
5506 /// The subobject is a non-static data member.
5507 TSK_Field,
5508 /// The object is actually the complete object.
5509 TSK_CompleteObject
5510};
5511
5512/// Check whether the special member selected for a given type would be trivial.
5513static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Stephen Hines651f13c2014-04-23 16:59:28 -07005514 QualType SubType, bool ConstRHS,
Richard Smithac713512012-12-08 02:53:02 +00005515 Sema::CXXSpecialMember CSM,
5516 TrivialSubobjectKind Kind,
5517 bool Diagnose) {
5518 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5519 if (!SubRD)
5520 return true;
5521
5522 CXXMethodDecl *Selected;
5523 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005524 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smithac713512012-12-08 02:53:02 +00005525 return true;
5526
5527 if (Diagnose) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005528 if (ConstRHS)
5529 SubType.addConst();
5530
Richard Smithac713512012-12-08 02:53:02 +00005531 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5532 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5533 << Kind << SubType.getUnqualifiedType();
5534 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5535 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5536 } else if (!Selected)
5537 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5538 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5539 else if (Selected->isUserProvided()) {
5540 if (Kind == TSK_CompleteObject)
5541 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5542 << Kind << SubType.getUnqualifiedType() << CSM;
5543 else {
5544 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5545 << Kind << SubType.getUnqualifiedType() << CSM;
5546 S.Diag(Selected->getLocation(), diag::note_declared_at);
5547 }
5548 } else {
5549 if (Kind != TSK_CompleteObject)
5550 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5551 << Kind << SubType.getUnqualifiedType() << CSM;
5552
5553 // Explain why the defaulted or deleted special member isn't trivial.
5554 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5555 }
5556 }
5557
5558 return false;
5559}
5560
5561/// Check whether the members of a class type allow a special member to be
5562/// trivial.
5563static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5564 Sema::CXXSpecialMember CSM,
5565 bool ConstArg, bool Diagnose) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005566 for (const auto *FI : RD->fields()) {
Richard Smithac713512012-12-08 02:53:02 +00005567 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5568 continue;
5569
5570 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5571
5572 // Pretend anonymous struct or union members are members of this class.
5573 if (FI->isAnonymousStructOrUnion()) {
5574 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5575 CSM, ConstArg, Diagnose))
5576 return false;
5577 continue;
5578 }
5579
5580 // C++11 [class.ctor]p5:
5581 // A default constructor is trivial if [...]
5582 // -- no non-static data member of its class has a
5583 // brace-or-equal-initializer
5584 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5585 if (Diagnose)
Stephen Hines651f13c2014-04-23 16:59:28 -07005586 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smithac713512012-12-08 02:53:02 +00005587 return false;
5588 }
5589
5590 // Objective C ARC 4.3.5:
5591 // [...] nontrivally ownership-qualified types are [...] not trivially
5592 // default constructible, copy constructible, move constructible, copy
5593 // assignable, move assignable, or destructible [...]
5594 if (S.getLangOpts().ObjCAutoRefCount &&
5595 FieldType.hasNonTrivialObjCLifetime()) {
5596 if (Diagnose)
5597 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5598 << RD << FieldType.getObjCLifetime();
5599 return false;
5600 }
5601
Stephen Hines651f13c2014-04-23 16:59:28 -07005602 bool ConstRHS = ConstArg && !FI->isMutable();
5603 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5604 CSM, TSK_Field, Diagnose))
Richard Smithac713512012-12-08 02:53:02 +00005605 return false;
5606 }
5607
5608 return true;
5609}
5610
5611/// Diagnose why the specified class does not have a trivial special member of
5612/// the given kind.
5613void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5614 QualType Ty = Context.getRecordType(RD);
Richard Smithac713512012-12-08 02:53:02 +00005615
Stephen Hines651f13c2014-04-23 16:59:28 -07005616 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5617 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smithac713512012-12-08 02:53:02 +00005618 TSK_CompleteObject, /*Diagnose*/true);
5619}
5620
5621/// Determine whether a defaulted or deleted special member function is trivial,
5622/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5623/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5624bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5625 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005626 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5627
5628 CXXRecordDecl *RD = MD->getParent();
5629
5630 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005631
Richard Smitha8d478e2013-11-04 02:02:27 +00005632 // C++11 [class.copy]p12, p25: [DR1593]
5633 // A [special member] is trivial if [...] its parameter-type-list is
5634 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smithac713512012-12-08 02:53:02 +00005635 switch (CSM) {
5636 case CXXDefaultConstructor:
5637 case CXXDestructor:
5638 // Trivial default constructors and destructors cannot have parameters.
5639 break;
5640
5641 case CXXCopyConstructor:
5642 case CXXCopyAssignment: {
5643 // Trivial copy operations always have const, non-volatile parameter types.
5644 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005645 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005646 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5647 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5648 if (Diagnose)
5649 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5650 << Param0->getSourceRange() << Param0->getType()
5651 << Context.getLValueReferenceType(
5652 Context.getRecordType(RD).withConst());
5653 return false;
5654 }
5655 break;
5656 }
5657
5658 case CXXMoveConstructor:
5659 case CXXMoveAssignment: {
5660 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005661 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005662 const RValueReferenceType *RT =
5663 Param0->getType()->getAs<RValueReferenceType>();
5664 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5665 if (Diagnose)
5666 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5667 << Param0->getSourceRange() << Param0->getType()
5668 << Context.getRValueReferenceType(Context.getRecordType(RD));
5669 return false;
5670 }
5671 break;
5672 }
5673
5674 case CXXInvalid:
5675 llvm_unreachable("not a special member");
5676 }
5677
Richard Smithac713512012-12-08 02:53:02 +00005678 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5679 if (Diagnose)
5680 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5681 diag::note_nontrivial_default_arg)
5682 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5683 return false;
5684 }
5685 if (MD->isVariadic()) {
5686 if (Diagnose)
5687 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5688 return false;
5689 }
5690
5691 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5692 // A copy/move [constructor or assignment operator] is trivial if
5693 // -- the [member] selected to copy/move each direct base class subobject
5694 // is trivial
5695 //
5696 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5697 // A [default constructor or destructor] is trivial if
5698 // -- all the direct base classes have trivial [default constructors or
5699 // destructors]
Stephen Hines651f13c2014-04-23 16:59:28 -07005700 for (const auto &BI : RD->bases())
5701 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
5702 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smithac713512012-12-08 02:53:02 +00005703 return false;
5704
5705 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5706 // A copy/move [constructor or assignment operator] for a class X is
5707 // trivial if
5708 // -- for each non-static data member of X that is of class type (or array
5709 // thereof), the constructor selected to copy/move that member is
5710 // trivial
5711 //
5712 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5713 // A [default constructor or destructor] is trivial if
5714 // -- for all of the non-static data members of its class that are of class
5715 // type (or array thereof), each such class has a trivial [default
5716 // constructor or destructor]
5717 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5718 return false;
5719
5720 // C++11 [class.dtor]p5:
5721 // A destructor is trivial if [...]
5722 // -- the destructor is not virtual
5723 if (CSM == CXXDestructor && MD->isVirtual()) {
5724 if (Diagnose)
5725 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5726 return false;
5727 }
5728
5729 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5730 // A [special member] for class X is trivial if [...]
5731 // -- class X has no virtual functions and no virtual base classes
5732 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5733 if (!Diagnose)
5734 return false;
5735
5736 if (RD->getNumVBases()) {
5737 // Check for virtual bases. We already know that the corresponding
5738 // member in all bases is trivial, so vbases must all be direct.
5739 CXXBaseSpecifier &BS = *RD->vbases_begin();
5740 assert(BS.isVirtual());
5741 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5742 return false;
5743 }
5744
5745 // Must have a virtual method.
Stephen Hines651f13c2014-04-23 16:59:28 -07005746 for (const auto *MI : RD->methods()) {
Richard Smithac713512012-12-08 02:53:02 +00005747 if (MI->isVirtual()) {
5748 SourceLocation MLoc = MI->getLocStart();
5749 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5750 return false;
5751 }
5752 }
5753
5754 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5755 }
5756
5757 // Looks like it's trivial!
5758 return true;
5759}
5760
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005761/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005762namespace {
5763 struct FindHiddenVirtualMethodData {
5764 Sema *S;
5765 CXXMethodDecl *Method;
5766 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005767 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005768 };
5769}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005770
David Blaikie5f750682012-10-19 00:53:08 +00005771/// \brief Check whether any most overriden method from MD in Methods
5772static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5773 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5774 if (MD->size_overridden_methods() == 0)
5775 return Methods.count(MD->getCanonicalDecl());
5776 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5777 E = MD->end_overridden_methods();
5778 I != E; ++I)
5779 if (CheckMostOverridenMethods(*I, Methods))
5780 return true;
5781 return false;
5782}
5783
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005784/// \brief Member lookup function that determines whether a given C++
5785/// method overloads virtual methods in a base class without overriding any,
5786/// to be used with CXXRecordDecl::lookupInBases().
5787static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5788 CXXBasePath &Path,
5789 void *UserData) {
5790 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5791
5792 FindHiddenVirtualMethodData &Data
5793 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5794
5795 DeclarationName Name = Data.Method->getDeclName();
5796 assert(Name.getNameKind() == DeclarationName::Identifier);
5797
5798 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005799 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005800 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005801 !Path.Decls.empty();
5802 Path.Decls = Path.Decls.slice(1)) {
5803 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005804 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005805 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005806 foundSameNameMethod = true;
5807 // Interested only in hidden virtual methods.
5808 if (!MD->isVirtual())
5809 continue;
5810 // If the method we are checking overrides a method from its base
5811 // don't warn about the other overloaded methods.
5812 if (!Data.S->IsOverload(Data.Method, MD, false))
5813 return true;
5814 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005815 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005816 overloadedMethods.push_back(MD);
5817 }
5818 }
5819
5820 if (foundSameNameMethod)
5821 Data.OverloadedMethods.append(overloadedMethods.begin(),
5822 overloadedMethods.end());
5823 return foundSameNameMethod;
5824}
5825
David Blaikie5f750682012-10-19 00:53:08 +00005826/// \brief Add the most overriden methods from MD to Methods
5827static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5828 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5829 if (MD->size_overridden_methods() == 0)
5830 Methods.insert(MD->getCanonicalDecl());
5831 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5832 E = MD->end_overridden_methods();
5833 I != E; ++I)
5834 AddMostOverridenMethods(*I, Methods);
5835}
5836
Eli Friedmandae92712013-09-05 23:51:03 +00005837/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005838/// overriding any.
Eli Friedmandae92712013-09-05 23:51:03 +00005839void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5840 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramerc4704422012-05-19 16:03:58 +00005841 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005842 return;
5843
5844 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5845 /*bool RecordPaths=*/false,
5846 /*bool DetectVirtual=*/false);
5847 FindHiddenVirtualMethodData Data;
5848 Data.Method = MD;
5849 Data.S = this;
5850
5851 // Keep the base methods that were overriden or introduced in the subclass
5852 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmandae92712013-09-05 23:51:03 +00005853 CXXRecordDecl *DC = MD->getParent();
David Blaikie3bc93e32012-12-19 00:45:41 +00005854 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5855 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5856 NamedDecl *ND = *I;
5857 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005858 ND = shad->getTargetDecl();
5859 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5860 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005861 }
5862
Eli Friedmandae92712013-09-05 23:51:03 +00005863 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5864 OverloadedMethods = Data.OverloadedMethods;
5865}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005866
Eli Friedmandae92712013-09-05 23:51:03 +00005867void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5868 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5869 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5870 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5871 PartialDiagnostic PD = PDiag(
5872 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5873 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5874 Diag(overloadedMD->getLocation(), PD);
5875 }
5876}
5877
5878/// \brief Diagnose methods which overload virtual methods in a base class
5879/// without overriding any.
5880void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5881 if (MD->isInvalidDecl())
5882 return;
5883
5884 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5885 MD->getLocation()) == DiagnosticsEngine::Ignored)
5886 return;
5887
5888 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5889 FindHiddenVirtualMethods(MD, OverloadedMethods);
5890 if (!OverloadedMethods.empty()) {
5891 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5892 << MD << (OverloadedMethods.size() > 1);
5893
5894 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005895 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005896}
5897
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005898void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005899 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005900 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005901 SourceLocation RBrac,
5902 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005903 if (!TagDecl)
5904 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005905
Douglas Gregor42af25f2009-05-11 19:58:34 +00005906 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005907
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005908 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5909 if (l->getKind() != AttributeList::AT_Visibility)
5910 continue;
5911 l->setInvalid();
5912 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5913 l->getName();
5914 }
5915
David Blaikie77b6de02011-09-22 02:58:26 +00005916 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005917 // strict aliasing violation!
5918 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005919 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005920
Douglas Gregor23c94db2010-07-02 17:43:08 +00005921 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005922 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005923}
5924
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005925/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5926/// special functions, such as the default constructor, copy
5927/// constructor, or destructor, to the given C++ class (C++
5928/// [special]p1). This routine can only be executed just before the
5929/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005930void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005931 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005932 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005933
Richard Smithbc2a35d2012-12-08 08:32:28 +00005934 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005935 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005936
Richard Smithbc2a35d2012-12-08 08:32:28 +00005937 // If the properties or semantics of the copy constructor couldn't be
5938 // determined while the class was being declared, force a declaration
5939 // of it now.
5940 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5941 DeclareImplicitCopyConstructor(ClassDecl);
5942 }
5943
Richard Smith80ad52f2013-01-02 11:42:31 +00005944 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005945 ++ASTContext::NumImplicitMoveConstructors;
5946
Richard Smithbc2a35d2012-12-08 08:32:28 +00005947 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5948 DeclareImplicitMoveConstructor(ClassDecl);
5949 }
5950
Douglas Gregora376d102010-07-02 21:50:04 +00005951 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5952 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005953
5954 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005955 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005956 // it shows up in the right place in the vtable and that we diagnose
5957 // problems with the implicit exception specification.
5958 if (ClassDecl->isDynamicClass() ||
5959 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005960 DeclareImplicitCopyAssignment(ClassDecl);
5961 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005962
Richard Smith80ad52f2013-01-02 11:42:31 +00005963 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005964 ++ASTContext::NumImplicitMoveAssignmentOperators;
5965
5966 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005967 if (ClassDecl->isDynamicClass() ||
5968 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005969 DeclareImplicitMoveAssignment(ClassDecl);
5970 }
5971
Douglas Gregor4923aa22010-07-02 20:37:36 +00005972 if (!ClassDecl->hasUserDeclaredDestructor()) {
5973 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005974
5975 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005976 // have to declare the destructor immediately. This ensures that, e.g., it
5977 // shows up in the right place in the vtable and that we diagnose problems
5978 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005979 if (ClassDecl->isDynamicClass() ||
5980 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005981 DeclareImplicitDestructor(ClassDecl);
5982 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005983}
5984
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005985unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00005986 if (!D)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005987 return 0;
Francois Pichet8387e2a2011-04-22 22:18:13 +00005988
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005989 // The order of template parameters is not important here. All names
5990 // get added to the same scope.
5991 SmallVector<TemplateParameterList *, 4> ParameterLists;
5992
5993 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
5994 D = TD->getTemplatedDecl();
5995
5996 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5997 ParameterLists.push_back(PSD->getTemplateParameters());
5998
5999 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6000 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6001 ParameterLists.push_back(DD->getTemplateParameterList(i));
6002
6003 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6004 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6005 ParameterLists.push_back(FTD->getTemplateParameters());
6006 }
6007 }
6008
6009 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6010 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6011 ParameterLists.push_back(TD->getTemplateParameterList(i));
6012
6013 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6014 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6015 ParameterLists.push_back(CTD->getTemplateParameters());
6016 }
6017 }
6018
6019 unsigned Count = 0;
6020 for (TemplateParameterList *Params : ParameterLists) {
6021 if (Params->size() > 0)
6022 // Ignore explicit specializations; they don't contribute to the template
6023 // depth.
6024 ++Count;
6025 for (NamedDecl *Param : *Params) {
6026 if (Param->getDeclName()) {
6027 S->AddDecl(Param);
6028 IdResolver.AddDecl(Param);
Francois Pichet8387e2a2011-04-22 22:18:13 +00006029 }
6030 }
6031 }
Francois Pichet8387e2a2011-04-22 22:18:13 +00006032
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006033 return Count;
Douglas Gregor6569d682009-05-27 23:11:45 +00006034}
6035
John McCalld226f652010-08-21 09:40:31 +00006036void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00006037 if (!RecordD) return;
6038 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00006039 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00006040 PushDeclContext(S, Record);
6041}
6042
John McCalld226f652010-08-21 09:40:31 +00006043void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00006044 if (!RecordD) return;
6045 PopDeclContext();
6046}
6047
Stephen Hines651f13c2014-04-23 16:59:28 -07006048/// This is used to implement the constant expression evaluation part of the
6049/// attribute enable_if extension. There is nothing in standard C++ which would
6050/// require reentering parameters.
6051void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6052 if (!Param)
6053 return;
6054
6055 S->AddDecl(Param);
6056 if (Param->getDeclName())
6057 IdResolver.AddDecl(Param);
6058}
6059
Douglas Gregor72b505b2008-12-16 21:30:33 +00006060/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6061/// parsing a top-level (non-nested) C++ class, and we are now
6062/// parsing those parts of the given Method declaration that could
6063/// not be parsed earlier (C++ [class.mem]p2), such as default
6064/// arguments. This action should enter the scope of the given
6065/// Method declaration as if we had just parsed the qualified method
6066/// name. However, it should not bring the parameters into scope;
6067/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00006068void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006069}
6070
6071/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6072/// C++ method declaration. We're (re-)introducing the given
6073/// function parameter into scope for use in parsing later parts of
6074/// the method declaration. For example, we could see an
6075/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00006076void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006077 if (!ParamD)
6078 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006079
John McCalld226f652010-08-21 09:40:31 +00006080 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00006081
6082 // If this parameter has an unparsed default argument, clear it out
6083 // to make way for the parsed default argument.
6084 if (Param->hasUnparsedDefaultArg())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006085 Param->setDefaultArg(nullptr);
Douglas Gregor61366e92008-12-24 00:01:03 +00006086
John McCalld226f652010-08-21 09:40:31 +00006087 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006088 if (Param->getDeclName())
6089 IdResolver.AddDecl(Param);
6090}
6091
6092/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6093/// processing the delayed method declaration for Method. The method
6094/// declaration is now considered finished. There may be a separate
6095/// ActOnStartOfFunctionDef action later (not necessarily
6096/// immediately!) for this method, if it was also defined inside the
6097/// class body.
John McCalld226f652010-08-21 09:40:31 +00006098void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006099 if (!MethodD)
6100 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006101
Douglas Gregorefd5bda2009-08-24 11:57:43 +00006102 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00006103
John McCalld226f652010-08-21 09:40:31 +00006104 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006105
6106 // Now that we have our default arguments, check the constructor
6107 // again. It could produce additional diagnostics or affect whether
6108 // the class has implicitly-declared destructors, among other
6109 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00006110 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6111 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006112
6113 // Check the default arguments, which we may have added.
6114 if (!Method->isInvalidDecl())
6115 CheckCXXDefaultArguments(Method);
6116}
6117
Douglas Gregor42a552f2008-11-05 20:51:48 +00006118/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00006119/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00006120/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006121/// emit diagnostics and set the invalid bit to true. In any case, the type
6122/// will be updated to reflect a well-formed type for the constructor and
6123/// returned.
6124QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006125 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006126 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006127
6128 // C++ [class.ctor]p3:
6129 // A constructor shall not be virtual (10.3) or static (9.4). A
6130 // constructor can be invoked for a const, volatile or const
6131 // volatile object. A constructor shall not be declared const,
6132 // volatile, or const volatile (9.3.2).
6133 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00006134 if (!D.isInvalidType())
6135 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6136 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6137 << SourceRange(D.getIdentifierLoc());
6138 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006139 }
John McCalld931b082010-08-26 03:08:43 +00006140 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006141 if (!D.isInvalidType())
6142 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6143 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6144 << SourceRange(D.getIdentifierLoc());
6145 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006146 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006147 }
Mike Stump1eb44332009-09-09 15:08:12 +00006148
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006149 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006150 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00006151 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006152 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6153 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006154 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006155 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6156 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006157 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006158 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6159 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00006160 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006161 }
Mike Stump1eb44332009-09-09 15:08:12 +00006162
Douglas Gregorc938c162011-01-26 05:01:58 +00006163 // C++0x [class.ctor]p4:
6164 // A constructor shall not be declared with a ref-qualifier.
6165 if (FTI.hasRefQualifier()) {
6166 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6167 << FTI.RefQualifierIsLValueRef
6168 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6169 D.setInvalidType();
6170 }
6171
Douglas Gregor42a552f2008-11-05 20:51:48 +00006172 // Rebuild the function type "R" without any type qualifiers (in
6173 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00006174 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00006175 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07006176 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalle23cf432010-12-14 08:05:40 +00006177 return R;
6178
6179 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6180 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006181 EPI.RefQualifier = RQ_None;
Stephen Hines651f13c2014-04-23 16:59:28 -07006182
6183 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006184}
6185
Douglas Gregor72b505b2008-12-16 21:30:33 +00006186/// CheckConstructor - Checks a fully-formed constructor for
6187/// well-formedness, issuing any diagnostics required. Returns true if
6188/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00006189void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00006190 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00006191 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6192 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00006193 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006194
6195 // C++ [class.copy]p3:
6196 // A declaration of a constructor for a class X is ill-formed if
6197 // its first parameter is of type (optionally cv-qualified) X and
6198 // either there are no other parameters or else all other
6199 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00006200 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006201 ((Constructor->getNumParams() == 1) ||
6202 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00006203 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6204 Constructor->getTemplateSpecializationKind()
6205 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006206 QualType ParamType = Constructor->getParamDecl(0)->getType();
6207 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6208 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00006209 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006210 const char *ConstRef
6211 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6212 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00006213 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006214 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00006215
6216 // FIXME: Rather that making the constructor invalid, we should endeavor
6217 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00006218 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006219 }
6220 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00006221}
6222
John McCall15442822010-08-04 01:04:25 +00006223/// CheckDestructor - Checks a fully-formed destructor definition for
6224/// well-formedness, issuing any diagnostics required. Returns true
6225/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006226bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006227 CXXRecordDecl *RD = Destructor->getParent();
6228
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006229 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006230 SourceLocation Loc;
6231
6232 if (!Destructor->isImplicit())
6233 Loc = Destructor->getLocation();
6234 else
6235 Loc = RD->getLocation();
6236
6237 // If we have a virtual destructor, look up the deallocation function
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006238 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson6d701392009-11-15 22:49:34 +00006239 DeclarationName Name =
6240 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006241 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00006242 return true;
Bill Wendlingc12b43a2013-12-07 23:53:50 +00006243 // If there's no class-specific operator delete, look up the global
6244 // non-array delete.
6245 if (!OperatorDelete)
6246 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall5efd91a2010-07-03 18:33:00 +00006247
Eli Friedman5f2987c2012-02-02 03:46:19 +00006248 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00006249
6250 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00006251 }
Anders Carlsson37909802009-11-30 21:24:50 +00006252
6253 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00006254}
6255
Douglas Gregor42a552f2008-11-05 20:51:48 +00006256/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6257/// the well-formednes of the destructor declarator @p D with type @p
6258/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006259/// emit diagnostics and set the declarator to invalid. Even if this happens,
6260/// will be updated to reflect a well-formed type for the destructor and
6261/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00006262QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006263 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006264 // C++ [class.dtor]p1:
6265 // [...] A typedef-name that names a class is a class-name
6266 // (7.1.3); however, a typedef-name that names a class shall not
6267 // be used as the identifier in the declarator for a destructor
6268 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006269 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00006270 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00006271 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00006272 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00006273 else if (const TemplateSpecializationType *TST =
6274 DeclaratorType->getAs<TemplateSpecializationType>())
6275 if (TST->isTypeAlias())
6276 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6277 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006278
6279 // C++ [class.dtor]p2:
6280 // A destructor is used to destroy objects of its class type. A
6281 // destructor takes no parameters, and no return type can be
6282 // specified for it (not even void). The address of a destructor
6283 // shall not be taken. A destructor shall not be static. A
6284 // destructor can be invoked for a const, volatile or const
6285 // volatile object. A destructor shall not be declared const,
6286 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00006287 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006288 if (!D.isInvalidType())
6289 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6290 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00006291 << SourceRange(D.getIdentifierLoc())
6292 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6293
John McCalld931b082010-08-26 03:08:43 +00006294 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006295 }
Chris Lattner65401802009-04-25 08:28:21 +00006296 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006297 // Destructors don't have return types, but the parser will
6298 // happily parse something like:
6299 //
6300 // class X {
6301 // float ~X();
6302 // };
6303 //
6304 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006305 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6306 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6307 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00006308 }
Mike Stump1eb44332009-09-09 15:08:12 +00006309
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006310 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006311 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006312 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006313 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6314 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006315 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006316 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6317 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006318 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006319 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6320 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006321 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006322 }
6323
Douglas Gregorc938c162011-01-26 05:01:58 +00006324 // C++0x [class.dtor]p2:
6325 // A destructor shall not be declared with a ref-qualifier.
6326 if (FTI.hasRefQualifier()) {
6327 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6328 << FTI.RefQualifierIsLValueRef
6329 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6330 D.setInvalidType();
6331 }
6332
Douglas Gregor42a552f2008-11-05 20:51:48 +00006333 // Make sure we don't have any parameters.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006334 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006335 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6336
6337 // Delete the parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -07006338 FTI.freeParams();
Chris Lattner65401802009-04-25 08:28:21 +00006339 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006340 }
6341
Mike Stump1eb44332009-09-09 15:08:12 +00006342 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006343 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006344 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006345 D.setInvalidType();
6346 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006347
6348 // Rebuild the function type "R" without any type qualifiers or
6349 // parameters (in case any of the errors above fired) and with
6350 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006351 // types.
John McCalle23cf432010-12-14 08:05:40 +00006352 if (!D.isInvalidType())
6353 return R;
6354
Douglas Gregord92ec472010-07-01 05:10:53 +00006355 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006356 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6357 EPI.Variadic = false;
6358 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006359 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006360 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006361}
6362
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006363/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6364/// well-formednes of the conversion function declarator @p D with
6365/// type @p R. If there are any errors in the declarator, this routine
6366/// will emit diagnostics and return true. Otherwise, it will return
6367/// false. Either way, the type @p R will be updated to reflect a
6368/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006369void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006370 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006371 // C++ [class.conv.fct]p1:
6372 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006373 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006374 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006375 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006376 if (!D.isInvalidType())
6377 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006378 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6379 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006380 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006381 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006382 }
John McCalla3f81372010-04-13 00:04:31 +00006383
6384 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6385
Chris Lattner6e475012009-04-25 08:35:12 +00006386 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006387 // Conversion functions don't have return types, but the parser will
6388 // happily parse something like:
6389 //
6390 // class X {
6391 // float operator bool();
6392 // };
6393 //
6394 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006395 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6396 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6397 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006398 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006399 }
6400
John McCalla3f81372010-04-13 00:04:31 +00006401 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6402
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006403 // Make sure we don't have any parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -07006404 if (Proto->getNumParams() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006405 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6406
6407 // Delete the parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -07006408 D.getFunctionTypeInfo().freeParams();
Chris Lattner6e475012009-04-25 08:35:12 +00006409 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006410 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006411 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006412 D.setInvalidType();
6413 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006414
John McCalla3f81372010-04-13 00:04:31 +00006415 // Diagnose "&operator bool()" and other such nonsense. This
6416 // is actually a gcc extension which we don't support.
Stephen Hines651f13c2014-04-23 16:59:28 -07006417 if (Proto->getReturnType() != ConvType) {
John McCalla3f81372010-04-13 00:04:31 +00006418 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Stephen Hines651f13c2014-04-23 16:59:28 -07006419 << Proto->getReturnType();
John McCalla3f81372010-04-13 00:04:31 +00006420 D.setInvalidType();
Stephen Hines651f13c2014-04-23 16:59:28 -07006421 ConvType = Proto->getReturnType();
John McCalla3f81372010-04-13 00:04:31 +00006422 }
6423
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006424 // C++ [class.conv.fct]p4:
6425 // The conversion-type-id shall not represent a function type nor
6426 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006427 if (ConvType->isArrayType()) {
6428 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6429 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006430 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006431 } else if (ConvType->isFunctionType()) {
6432 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6433 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006434 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006435 }
6436
6437 // Rebuild the function type "R" without any parameters (in case any
6438 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006439 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006440 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006441 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006442
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006443 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006444 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006445 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006446 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006447 diag::warn_cxx98_compat_explicit_conversion_functions :
6448 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006449 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006450}
6451
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006452/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6453/// the declaration of the given C++ conversion function. This routine
6454/// is responsible for recording the conversion function in the C++
6455/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006456Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006457 assert(Conversion && "Expected to receive a conversion function declaration");
6458
Douglas Gregor9d350972008-12-12 08:25:50 +00006459 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006460
6461 // Make sure we aren't redeclaring the conversion function.
6462 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006463
6464 // C++ [class.conv.fct]p1:
6465 // [...] A conversion function is never used to convert a
6466 // (possibly cv-qualified) object to the (possibly cv-qualified)
6467 // same object type (or a reference to it), to a (possibly
6468 // cv-qualified) base class of that type (or a reference to it),
6469 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006470 // FIXME: Suppress this warning if the conversion function ends up being a
6471 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006472 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006473 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006474 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006475 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006476 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6477 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006478 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006479 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006480 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6481 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006482 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006483 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006484 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006485 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006486 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006487 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006488 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006489 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006490 }
6491
Douglas Gregore80622f2010-09-29 04:25:11 +00006492 if (FunctionTemplateDecl *ConversionTemplate
6493 = Conversion->getDescribedFunctionTemplate())
6494 return ConversionTemplate;
6495
John McCalld226f652010-08-21 09:40:31 +00006496 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006497}
6498
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006499//===----------------------------------------------------------------------===//
6500// Namespace Handling
6501//===----------------------------------------------------------------------===//
6502
Richard Smithd1a55a62012-10-04 22:13:39 +00006503/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6504/// reopened.
6505static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6506 SourceLocation Loc,
6507 IdentifierInfo *II, bool *IsInline,
6508 NamespaceDecl *PrevNS) {
6509 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006510
Richard Smithc969e6a2012-10-05 01:46:25 +00006511 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6512 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6513 // inline namespaces, with the intention of bringing names into namespace std.
6514 //
6515 // We support this just well enough to get that case working; this is not
6516 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006517 if (*IsInline && II && II->getName().startswith("__atomic") &&
6518 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006519 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006520 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6521 NS = NS->getPreviousDecl())
6522 NS->setInline(*IsInline);
6523 // Patch up the lookup table for the containing namespace. This isn't really
6524 // correct, but it's good enough for this particular case.
Stephen Hines651f13c2014-04-23 16:59:28 -07006525 for (auto *I : PrevNS->decls())
6526 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smithd1a55a62012-10-04 22:13:39 +00006527 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6528 return;
6529 }
6530
6531 if (PrevNS->isInline())
6532 // The user probably just forgot the 'inline', so suggest that it
6533 // be added back.
6534 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6535 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6536 else
Stephen Hines651f13c2014-04-23 16:59:28 -07006537 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smithd1a55a62012-10-04 22:13:39 +00006538
6539 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6540 *IsInline = PrevNS->isInline();
6541}
John McCallea318642010-08-26 09:15:37 +00006542
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006543/// ActOnStartNamespaceDef - This is called at the start of a namespace
6544/// definition.
John McCalld226f652010-08-21 09:40:31 +00006545Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006546 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006547 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006548 SourceLocation IdentLoc,
6549 IdentifierInfo *II,
6550 SourceLocation LBrace,
6551 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006552 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6553 // For anonymous namespace, take the location of the left brace.
6554 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006555 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006556 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006557 bool IsStd = false;
6558 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006559 Scope *DeclRegionScope = NamespcScope->getParent();
6560
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006561 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006562 if (II) {
6563 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006564 // The identifier in an original-namespace-definition shall not
6565 // have been previously defined in the declarative region in
6566 // which the original-namespace-definition appears. The
6567 // identifier in an original-namespace-definition is the name of
6568 // the namespace. Subsequently in that declarative region, it is
6569 // treated as an original-namespace-name.
6570 //
6571 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006572 // look through using directives, just look for any ordinary names.
6573
6574 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006575 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6576 Decl::IDNS_Namespace;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006577 NamedDecl *PrevDecl = nullptr;
David Blaikie3bc93e32012-12-19 00:45:41 +00006578 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6579 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6580 ++I) {
6581 if ((*I)->getIdentifierNamespace() & IDNS) {
6582 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006583 break;
6584 }
6585 }
6586
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006587 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6588
6589 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006590 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006591 if (IsInline != PrevNS->isInline())
6592 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6593 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006594 } else if (PrevDecl) {
6595 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006596 Diag(Loc, diag::err_redefinition_different_kind)
6597 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006598 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006599 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006600 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006601 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006602 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006603 // This is the first "real" definition of the namespace "std", so update
6604 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006605 PrevNS = getStdNamespace();
6606 IsStd = true;
6607 AddToKnown = !IsInline;
6608 } else {
6609 // We've seen this namespace for the first time.
6610 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006611 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006612 } else {
John McCall9aeed322009-10-01 00:25:31 +00006613 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006614
6615 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006616 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006617 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006618 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006619 } else {
6620 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006621 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006622 }
6623
Richard Smithd1a55a62012-10-04 22:13:39 +00006624 if (PrevNS && IsInline != PrevNS->isInline())
6625 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6626 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006627 }
6628
6629 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6630 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006631 if (IsInvalid)
6632 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006633
6634 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006635
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006636 // FIXME: Should we be merging attributes?
6637 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006638 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006639
6640 if (IsStd)
6641 StdNamespace = Namespc;
6642 if (AddToKnown)
6643 KnownNamespaces[Namespc] = false;
6644
6645 if (II) {
6646 PushOnScopeChains(Namespc, DeclRegionScope);
6647 } else {
6648 // Link the anonymous namespace into its parent.
6649 DeclContext *Parent = CurContext->getRedeclContext();
6650 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6651 TU->setAnonymousNamespace(Namespc);
6652 } else {
6653 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006654 }
John McCall9aeed322009-10-01 00:25:31 +00006655
Douglas Gregora4181472010-03-24 00:46:35 +00006656 CurContext->addDecl(Namespc);
6657
John McCall9aeed322009-10-01 00:25:31 +00006658 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6659 // behaves as if it were replaced by
6660 // namespace unique { /* empty body */ }
6661 // using namespace unique;
6662 // namespace unique { namespace-body }
6663 // where all occurrences of 'unique' in a translation unit are
6664 // replaced by the same identifier and this identifier differs
6665 // from all other identifiers in the entire program.
6666
6667 // We just create the namespace with an empty name and then add an
6668 // implicit using declaration, just like the standard suggests.
6669 //
6670 // CodeGen enforces the "universally unique" aspect by giving all
6671 // declarations semantically contained within an anonymous
6672 // namespace internal linkage.
6673
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006674 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006675 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006676 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006677 /* 'using' */ LBrace,
6678 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006679 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006680 /* identifier */ SourceLocation(),
6681 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006682 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006683 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006684 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006685 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006686 }
6687
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006688 ActOnDocumentableDecl(Namespc);
6689
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006690 // Although we could have an invalid decl (i.e. the namespace name is a
6691 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006692 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6693 // for the namespace has the declarations that showed up in that particular
6694 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006695 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006696 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006697}
6698
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006699/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6700/// is a namespace alias, returns the namespace it points to.
6701static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6702 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6703 return AD->getNamespace();
6704 return dyn_cast_or_null<NamespaceDecl>(D);
6705}
6706
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006707/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6708/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006709void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006710 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6711 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006712 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006713 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006714 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006715 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006716}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006717
John McCall384aff82010-08-25 07:42:41 +00006718CXXRecordDecl *Sema::getStdBadAlloc() const {
6719 return cast_or_null<CXXRecordDecl>(
6720 StdBadAlloc.get(Context.getExternalSource()));
6721}
6722
6723NamespaceDecl *Sema::getStdNamespace() const {
6724 return cast_or_null<NamespaceDecl>(
6725 StdNamespace.get(Context.getExternalSource()));
6726}
6727
Douglas Gregor66992202010-06-29 17:53:46 +00006728/// \brief Retrieve the special "std" namespace, which may require us to
6729/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006730NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006731 if (!StdNamespace) {
6732 // The "std" namespace has not yet been defined, so build one implicitly.
6733 StdNamespace = NamespaceDecl::Create(Context,
6734 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006735 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006736 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006737 &PP.getIdentifierTable().get("std"),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006738 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006739 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006740 }
6741
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006742 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006743}
6744
Sebastian Redl395e04d2012-01-17 22:49:33 +00006745bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006746 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006747 "Looking for std::initializer_list outside of C++.");
6748
6749 // We're looking for implicit instantiations of
6750 // template <typename E> class std::initializer_list.
6751
6752 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6753 return false;
6754
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006755 ClassTemplateDecl *Template = nullptr;
6756 const TemplateArgument *Arguments = nullptr;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006757
Sebastian Redl84760e32012-01-17 22:49:58 +00006758 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006759
Sebastian Redl84760e32012-01-17 22:49:58 +00006760 ClassTemplateSpecializationDecl *Specialization =
6761 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6762 if (!Specialization)
6763 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006764
Sebastian Redl84760e32012-01-17 22:49:58 +00006765 Template = Specialization->getSpecializedTemplate();
6766 Arguments = Specialization->getTemplateArgs().data();
6767 } else if (const TemplateSpecializationType *TST =
6768 Ty->getAs<TemplateSpecializationType>()) {
6769 Template = dyn_cast_or_null<ClassTemplateDecl>(
6770 TST->getTemplateName().getAsTemplateDecl());
6771 Arguments = TST->getArgs();
6772 }
6773 if (!Template)
6774 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006775
6776 if (!StdInitializerList) {
6777 // Haven't recognized std::initializer_list yet, maybe this is it.
6778 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6779 if (TemplateClass->getIdentifier() !=
6780 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006781 !getStdNamespace()->InEnclosingNamespaceSetOf(
6782 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006783 return false;
6784 // This is a template called std::initializer_list, but is it the right
6785 // template?
6786 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006787 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006788 return false;
6789 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6790 return false;
6791
6792 // It's the right template.
6793 StdInitializerList = Template;
6794 }
6795
6796 if (Template != StdInitializerList)
6797 return false;
6798
6799 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006800 if (Element)
6801 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006802 return true;
6803}
6804
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006805static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6806 NamespaceDecl *Std = S.getStdNamespace();
6807 if (!Std) {
6808 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006809 return nullptr;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006810 }
6811
6812 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6813 Loc, Sema::LookupOrdinaryName);
6814 if (!S.LookupQualifiedName(Result, Std)) {
6815 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006816 return nullptr;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006817 }
6818 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6819 if (!Template) {
6820 Result.suppressDiagnostics();
6821 // We found something weird. Complain about the first thing we found.
6822 NamedDecl *Found = *Result.begin();
6823 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006824 return nullptr;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006825 }
6826
6827 // We found some template called std::initializer_list. Now verify that it's
6828 // correct.
6829 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006830 if (Params->getMinRequiredArguments() != 1 ||
6831 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006832 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006833 return nullptr;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006834 }
6835
6836 return Template;
6837}
6838
6839QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6840 if (!StdInitializerList) {
6841 StdInitializerList = LookupStdInitializerList(*this, Loc);
6842 if (!StdInitializerList)
6843 return QualType();
6844 }
6845
6846 TemplateArgumentListInfo Args(Loc, Loc);
6847 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6848 Context.getTrivialTypeSourceInfo(Element,
6849 Loc)));
6850 return Context.getCanonicalType(
6851 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6852}
6853
Sebastian Redl98d36062012-01-17 22:50:14 +00006854bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6855 // C++ [dcl.init.list]p2:
6856 // A constructor is an initializer-list constructor if its first parameter
6857 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6858 // std::initializer_list<E> for some type E, and either there are no other
6859 // parameters or else all other parameters have default arguments.
6860 if (Ctor->getNumParams() < 1 ||
6861 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6862 return false;
6863
6864 QualType ArgType = Ctor->getParamDecl(0)->getType();
6865 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6866 ArgType = RT->getPointeeType().getUnqualifiedType();
6867
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006868 return isStdInitializerList(ArgType, nullptr);
Sebastian Redl98d36062012-01-17 22:50:14 +00006869}
6870
Douglas Gregor9172aa62011-03-26 22:25:30 +00006871/// \brief Determine whether a using statement is in a context where it will be
6872/// apply in all contexts.
6873static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6874 switch (CurContext->getDeclKind()) {
6875 case Decl::TranslationUnit:
6876 return true;
6877 case Decl::LinkageSpec:
6878 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6879 default:
6880 return false;
6881 }
6882}
6883
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006884namespace {
6885
6886// Callback to only accept typo corrections that are namespaces.
6887class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00006888public:
Stephen Hines651f13c2014-04-23 16:59:28 -07006889 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00006890 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006891 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006892 return false;
6893 }
6894};
6895
6896}
6897
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006898static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6899 CXXScopeSpec &SS,
6900 SourceLocation IdentLoc,
6901 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006902 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006903 R.clear();
6904 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006905 R.getLookupKind(), Sc, &SS,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006906 Validator,
6907 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006908 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +00006909 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6910 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006911 Ident->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +00006912 S.diagnoseTypo(Corrected,
6913 S.PDiag(diag::err_using_directive_member_suggest)
6914 << Ident << DC << DroppedSpecifier << SS.getRange(),
6915 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006916 } else {
Richard Smith2d670972013-08-17 00:46:16 +00006917 S.diagnoseTypo(Corrected,
6918 S.PDiag(diag::err_using_directive_suggest) << Ident,
6919 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006920 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006921 R.addDecl(Corrected.getCorrectionDecl());
6922 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006923 }
6924 return false;
6925}
6926
John McCalld226f652010-08-21 09:40:31 +00006927Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006928 SourceLocation UsingLoc,
6929 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006930 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006931 SourceLocation IdentLoc,
6932 IdentifierInfo *NamespcName,
6933 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006934 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6935 assert(NamespcName && "Invalid NamespcName.");
6936 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006937
6938 // This can only happen along a recovery path.
6939 while (S->getFlags() & Scope::TemplateParamScope)
6940 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006941 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006942
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006943 UsingDirectiveDecl *UDir = nullptr;
6944 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregor66992202010-06-29 17:53:46 +00006945 if (SS.isSet())
Stephen Hines651f13c2014-04-23 16:59:28 -07006946 Qualifier = SS.getScopeRep();
Douglas Gregor66992202010-06-29 17:53:46 +00006947
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006948 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006949 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6950 LookupParsedName(R, S, &SS);
6951 if (R.isAmbiguous())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006952 return nullptr;
John McCalla24dc2e2009-11-17 02:14:36 +00006953
Douglas Gregor66992202010-06-29 17:53:46 +00006954 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006955 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006956 // Allow "using namespace std;" or "using namespace ::std;" even if
6957 // "std" hasn't been defined yet, for GCC compatibility.
6958 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6959 NamespcName->isStr("std")) {
6960 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006961 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006962 R.resolveKind();
6963 }
6964 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006965 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006966 }
6967
John McCallf36e02d2009-10-09 21:13:30 +00006968 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006969 NamedDecl *Named = R.getFoundDecl();
6970 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6971 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006972 // C++ [namespace.udir]p1:
6973 // A using-directive specifies that the names in the nominated
6974 // namespace can be used in the scope in which the
6975 // using-directive appears after the using-directive. During
6976 // unqualified name lookup (3.4.1), the names appear as if they
6977 // were declared in the nearest enclosing namespace which
6978 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006979 // namespace. [Note: in this context, "contains" means "contains
6980 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006981
6982 // Find enclosing context containing both using-directive and
6983 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006984 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006985 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6986 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6987 CommonAncestor = CommonAncestor->getParent();
6988
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006989 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006990 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006991 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006992
Douglas Gregor9172aa62011-03-26 22:25:30 +00006993 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman24146972013-08-22 00:27:10 +00006994 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006995 Diag(IdentLoc, diag::warn_using_directive_in_header);
6996 }
6997
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006998 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006999 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00007000 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00007001 }
7002
Richard Smith6b3d3e52013-02-20 19:22:51 +00007003 if (UDir)
7004 ProcessDeclAttributeList(S, UDir, AttrList);
7005
John McCalld226f652010-08-21 09:40:31 +00007006 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00007007}
7008
7009void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00007010 // If the scope has an associated entity and the using directive is at
7011 // namespace or translation unit scope, add the UsingDirectiveDecl into
7012 // its lookup structure so qualified name lookup can find it.
Ted Kremenekf0d58612013-10-08 17:08:03 +00007013 DeclContext *Ctx = S->getEntity();
Richard Smith1b7f9cb2012-03-13 03:12:56 +00007014 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007015 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00007016 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007017 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith1b7f9cb2012-03-13 03:12:56 +00007018 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00007019 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00007020}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007021
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007022
John McCalld226f652010-08-21 09:40:31 +00007023Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00007024 AccessSpecifier AS,
7025 bool HasUsingKeyword,
7026 SourceLocation UsingLoc,
7027 CXXScopeSpec &SS,
7028 UnqualifiedId &Name,
7029 AttributeList *AttrList,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007030 bool HasTypenameKeyword,
John McCall78b81052010-11-10 02:40:36 +00007031 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007032 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00007033
Douglas Gregor12c118a2009-11-04 16:30:06 +00007034 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00007035 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00007036 case UnqualifiedId::IK_Identifier:
7037 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00007038 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00007039 case UnqualifiedId::IK_ConversionFunctionId:
7040 break;
7041
7042 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00007043 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00007044 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00007045 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00007046 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00007047 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00007048 diag::err_using_decl_constructor)
7049 << SS.getRange();
7050
Richard Smith80ad52f2013-01-02 11:42:31 +00007051 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00007052
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007053 return nullptr;
7054
Douglas Gregor12c118a2009-11-04 16:30:06 +00007055 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00007056 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00007057 << SS.getRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007058 return nullptr;
7059
Douglas Gregor12c118a2009-11-04 16:30:06 +00007060 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00007061 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00007062 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007063 return nullptr;
Douglas Gregor12c118a2009-11-04 16:30:06 +00007064 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007065
7066 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7067 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00007068 if (!TargetName)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007069 return nullptr;
John McCall604e7f12009-12-08 07:46:18 +00007070
Richard Smith07b0fdc2013-03-18 21:12:30 +00007071 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00007072 if (!HasUsingKeyword) {
Enea Zaffanellad4de59d2013-07-17 17:28:56 +00007073 Diag(Name.getLocStart(),
Richard Smith1b2209f2013-06-13 02:12:17 +00007074 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7075 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00007076 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00007077 }
7078
Douglas Gregor56c04582010-12-16 00:46:58 +00007079 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7080 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007081 return nullptr;
Douglas Gregor56c04582010-12-16 00:46:58 +00007082
John McCall9488ea12009-11-17 05:59:44 +00007083 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007084 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007085 /* IsInstantiation */ false,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007086 HasTypenameKeyword, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00007087 if (UD)
7088 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00007089
John McCalld226f652010-08-21 09:40:31 +00007090 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00007091}
7092
Douglas Gregor09acc982010-07-07 23:08:52 +00007093/// \brief Determine whether a using declaration considers the given
7094/// declarations as "equivalent", e.g., if they are redeclarations of
7095/// the same entity or are both typedefs of the same type.
Richard Smithf06a28932013-10-23 02:17:46 +00007096static bool
7097IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7098 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor09acc982010-07-07 23:08:52 +00007099 return true;
Douglas Gregor09acc982010-07-07 23:08:52 +00007100
Richard Smith162e1c12011-04-15 14:24:37 +00007101 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithf06a28932013-10-23 02:17:46 +00007102 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor09acc982010-07-07 23:08:52 +00007103 return Context.hasSameType(TD1->getUnderlyingType(),
7104 TD2->getUnderlyingType());
Douglas Gregor09acc982010-07-07 23:08:52 +00007105
7106 return false;
7107}
7108
7109
John McCall9f54ad42009-12-10 09:41:52 +00007110/// Determines whether to create a using shadow decl for a particular
7111/// decl, given the set of decls existing prior to this using lookup.
7112bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithf06a28932013-10-23 02:17:46 +00007113 const LookupResult &Previous,
7114 UsingShadowDecl *&PrevShadow) {
John McCall9f54ad42009-12-10 09:41:52 +00007115 // Diagnose finding a decl which is not from a base class of the
7116 // current class. We do this now because there are cases where this
7117 // function will silently decide not to build a shadow decl, which
7118 // will pre-empt further diagnostics.
7119 //
7120 // We don't need to do this in C++0x because we do the check once on
7121 // the qualifier.
7122 //
7123 // FIXME: diagnose the following if we care enough:
7124 // struct A { int foo; };
7125 // struct B : A { using A::foo; };
7126 // template <class T> struct C : A {};
7127 // template <class T> struct D : C<T> { using B::foo; } // <---
7128 // This is invalid (during instantiation) in C++03 because B::foo
7129 // resolves to the using decl in B, which is not a base class of D<T>.
7130 // We can't diagnose it immediately because C<T> is an unknown
7131 // specialization. The UsingShadowDecl in D<T> then points directly
7132 // to A::foo, which will look well-formed when we instantiate.
7133 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00007134 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00007135 DeclContext *OrigDC = Orig->getDeclContext();
7136
7137 // Handle enums and anonymous structs.
7138 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7139 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7140 while (OrigRec->isAnonymousStructOrUnion())
7141 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7142
7143 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7144 if (OrigDC == CurContext) {
7145 Diag(Using->getLocation(),
7146 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007147 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007148 Diag(Orig->getLocation(), diag::note_using_decl_target);
7149 return true;
7150 }
7151
Douglas Gregordc355712011-02-25 00:36:19 +00007152 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00007153 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007154 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00007155 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00007156 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007157 Diag(Orig->getLocation(), diag::note_using_decl_target);
7158 return true;
7159 }
7160 }
7161
7162 if (Previous.empty()) return false;
7163
7164 NamedDecl *Target = Orig;
7165 if (isa<UsingShadowDecl>(Target))
7166 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7167
John McCalld7533ec2009-12-11 02:33:26 +00007168 // If the target happens to be one of the previous declarations, we
7169 // don't have a conflict.
7170 //
7171 // FIXME: but we might be increasing its access, in which case we
7172 // should redeclare it.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007173 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithf06a28932013-10-23 02:17:46 +00007174 bool FoundEquivalentDecl = false;
John McCalld7533ec2009-12-11 02:33:26 +00007175 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7176 I != E; ++I) {
7177 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithf06a28932013-10-23 02:17:46 +00007178 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7179 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7180 PrevShadow = Shadow;
7181 FoundEquivalentDecl = true;
7182 }
John McCalld7533ec2009-12-11 02:33:26 +00007183
7184 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7185 }
7186
Richard Smithf06a28932013-10-23 02:17:46 +00007187 if (FoundEquivalentDecl)
7188 return false;
7189
Stephen Hines651f13c2014-04-23 16:59:28 -07007190 if (FunctionDecl *FD = Target->getAsFunction()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007191 NamedDecl *OldDecl = nullptr;
7192 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7193 /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00007194 case Ovl_Overload:
7195 return false;
7196
7197 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00007198 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007199 break;
Stephen Hines651f13c2014-04-23 16:59:28 -07007200
John McCall9f54ad42009-12-10 09:41:52 +00007201 // We found a decl with the exact signature.
7202 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007203 // If we're in a record, we want to hide the target, so we
7204 // return true (without a diagnostic) to tell the caller not to
7205 // build a shadow decl.
7206 if (CurContext->isRecord())
7207 return true;
7208
7209 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00007210 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007211 break;
7212 }
7213
7214 Diag(Target->getLocation(), diag::note_using_decl_target);
7215 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7216 return true;
7217 }
7218
7219 // Target is not a function.
7220
John McCall9f54ad42009-12-10 09:41:52 +00007221 if (isa<TagDecl>(Target)) {
7222 // No conflict between a tag and a non-tag.
7223 if (!Tag) return false;
7224
John McCall41ce66f2009-12-10 19:51:03 +00007225 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007226 Diag(Target->getLocation(), diag::note_using_decl_target);
7227 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7228 return true;
7229 }
7230
7231 // No conflict between a tag and a non-tag.
7232 if (!NonTag) return false;
7233
John McCall41ce66f2009-12-10 19:51:03 +00007234 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007235 Diag(Target->getLocation(), diag::note_using_decl_target);
7236 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7237 return true;
7238}
7239
John McCall9488ea12009-11-17 05:59:44 +00007240/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00007241UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00007242 UsingDecl *UD,
Richard Smithf06a28932013-10-23 02:17:46 +00007243 NamedDecl *Orig,
7244 UsingShadowDecl *PrevDecl) {
John McCall9488ea12009-11-17 05:59:44 +00007245
7246 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00007247 NamedDecl *Target = Orig;
7248 if (isa<UsingShadowDecl>(Target)) {
7249 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7250 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00007251 }
Richard Smithf06a28932013-10-23 02:17:46 +00007252
John McCall9488ea12009-11-17 05:59:44 +00007253 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00007254 = UsingShadowDecl::Create(Context, CurContext,
7255 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00007256 UD->addShadowDecl(Shadow);
Richard Smithf06a28932013-10-23 02:17:46 +00007257
Douglas Gregore80622f2010-09-29 04:25:11 +00007258 Shadow->setAccess(UD->getAccess());
7259 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7260 Shadow->setInvalidDecl();
Richard Smithf06a28932013-10-23 02:17:46 +00007261
7262 Shadow->setPreviousDecl(PrevDecl);
7263
John McCall9488ea12009-11-17 05:59:44 +00007264 if (S)
John McCall604e7f12009-12-08 07:46:18 +00007265 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00007266 else
John McCall604e7f12009-12-08 07:46:18 +00007267 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00007268
John McCall604e7f12009-12-08 07:46:18 +00007269
John McCall9f54ad42009-12-10 09:41:52 +00007270 return Shadow;
7271}
John McCall604e7f12009-12-08 07:46:18 +00007272
John McCall9f54ad42009-12-10 09:41:52 +00007273/// Hides a using shadow declaration. This is required by the current
7274/// using-decl implementation when a resolvable using declaration in a
7275/// class is followed by a declaration which would hide or override
7276/// one or more of the using decl's targets; for example:
7277///
7278/// struct Base { void foo(int); };
7279/// struct Derived : Base {
7280/// using Base::foo;
7281/// void foo(int);
7282/// };
7283///
7284/// The governing language is C++03 [namespace.udecl]p12:
7285///
7286/// When a using-declaration brings names from a base class into a
7287/// derived class scope, member functions in the derived class
7288/// override and/or hide member functions with the same name and
7289/// parameter types in a base class (rather than conflicting).
7290///
7291/// There are two ways to implement this:
7292/// (1) optimistically create shadow decls when they're not hidden
7293/// by existing declarations, or
7294/// (2) don't create any shadow decls (or at least don't make them
7295/// visible) until we've fully parsed/instantiated the class.
7296/// The problem with (1) is that we might have to retroactively remove
7297/// a shadow decl, which requires several O(n) operations because the
7298/// decl structures are (very reasonably) not designed for removal.
7299/// (2) avoids this but is very fiddly and phase-dependent.
7300void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007301 if (Shadow->getDeclName().getNameKind() ==
7302 DeclarationName::CXXConversionFunctionName)
7303 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7304
John McCall9f54ad42009-12-10 09:41:52 +00007305 // Remove it from the DeclContext...
7306 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007307
John McCall9f54ad42009-12-10 09:41:52 +00007308 // ...and the scope, if applicable...
7309 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007310 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007311 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007312 }
7313
John McCall9f54ad42009-12-10 09:41:52 +00007314 // ...and the using decl.
7315 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7316
7317 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007318 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007319}
7320
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007321/// Find the base specifier for a base class with the given type.
7322static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7323 QualType DesiredBase,
7324 bool &AnyDependentBases) {
7325 // Check whether the named type is a direct base class.
7326 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7327 for (auto &Base : Derived->bases()) {
7328 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7329 if (CanonicalDesiredBase == BaseType)
7330 return &Base;
7331 if (BaseType->isDependentType())
7332 AnyDependentBases = true;
7333 }
7334 return nullptr;
7335}
7336
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007337namespace {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007338class UsingValidatorCCC : public CorrectionCandidateCallback {
7339public:
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007340 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007341 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007342 : HasTypenameKeyword(HasTypenameKeyword),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007343 IsInstantiation(IsInstantiation), OldNNS(NNS),
7344 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007345
Stephen Hines651f13c2014-04-23 16:59:28 -07007346 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007347 NamedDecl *ND = Candidate.getCorrectionDecl();
7348
7349 // Keywords are not valid here.
7350 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007351 return false;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007352
7353 // Completely unqualified names are invalid for a 'using' declaration.
7354 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7355 return false;
7356
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007357 if (RequireMemberOf) {
7358 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7359 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7360 // No-one ever wants a using-declaration to name an injected-class-name
7361 // of a base class, unless they're declaring an inheriting constructor.
7362 ASTContext &Ctx = ND->getASTContext();
7363 if (!Ctx.getLangOpts().CPlusPlus11)
7364 return false;
7365 QualType FoundType = Ctx.getRecordType(FoundRecord);
7366
7367 // Check that the injected-class-name is named as a member of its own
7368 // type; we don't want to suggest 'using Derived::Base;', since that
7369 // means something else.
7370 NestedNameSpecifier *Specifier =
7371 Candidate.WillReplaceSpecifier()
7372 ? Candidate.getCorrectionSpecifier()
7373 : OldNNS;
7374 if (!Specifier->getAsType() ||
7375 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7376 return false;
7377
7378 // Check that this inheriting constructor declaration actually names a
7379 // direct base class of the current class.
7380 bool AnyDependentBases = false;
7381 if (!findDirectBaseWithType(RequireMemberOf,
7382 Ctx.getRecordType(FoundRecord),
7383 AnyDependentBases) &&
7384 !AnyDependentBases)
7385 return false;
7386 } else {
7387 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7388 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7389 return false;
7390
7391 // FIXME: Check that the base class member is accessible?
7392 }
7393 }
7394
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007395 if (isa<TypeDecl>(ND))
7396 return HasTypenameKeyword || !IsInstantiation;
7397
7398 return !HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007399 }
7400
7401private:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007402 bool HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007403 bool IsInstantiation;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007404 NestedNameSpecifier *OldNNS;
7405 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007406};
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007407} // end anonymous namespace
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007408
John McCall7ba107a2009-11-18 02:36:19 +00007409/// Builds a using declaration.
7410///
7411/// \param IsInstantiation - Whether this call arises from an
7412/// instantiation of an unresolved using declaration. We treat
7413/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007414NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7415 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007416 CXXScopeSpec &SS,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007417 DeclarationNameInfo NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007418 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007419 bool IsInstantiation,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007420 bool HasTypenameKeyword,
John McCall7ba107a2009-11-18 02:36:19 +00007421 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007422 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007423 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007424 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007425
Anders Carlsson550b14b2009-08-28 05:49:21 +00007426 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007427
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007428 if (SS.isEmpty()) {
7429 Diag(IdentLoc, diag::err_using_requires_qualname);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007430 return nullptr;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007431 }
Mike Stump1eb44332009-09-09 15:08:12 +00007432
John McCall9f54ad42009-12-10 09:41:52 +00007433 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007434 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007435 ForRedeclaration);
7436 Previous.setHideTags(false);
7437 if (S) {
7438 LookupName(Previous, S);
7439
7440 // It is really dumb that we have to do this.
7441 LookupResult::Filter F = Previous.makeFilter();
7442 while (F.hasNext()) {
7443 NamedDecl *D = F.next();
7444 if (!isDeclInScope(D, CurContext, S))
7445 F.erase();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007446 // If we found a local extern declaration that's not ordinarily visible,
7447 // and this declaration is being added to a non-block scope, ignore it.
7448 // We're only checking for scope conflicts here, not also for violations
7449 // of the linkage rules.
7450 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7451 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7452 F.erase();
John McCall9f54ad42009-12-10 09:41:52 +00007453 }
7454 F.done();
7455 } else {
7456 assert(IsInstantiation && "no scope in non-instantiation");
7457 assert(CurContext->isRecord() && "scope not record in instantiation");
7458 LookupQualifiedName(Previous, CurContext);
7459 }
7460
John McCall9f54ad42009-12-10 09:41:52 +00007461 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007462 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7463 SS, IdentLoc, Previous))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007464 return nullptr;
John McCall9f54ad42009-12-10 09:41:52 +00007465
7466 // Check for bad qualifiers.
Stephen Hines651f13c2014-04-23 16:59:28 -07007467 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007468 return nullptr;
John McCalled976492009-12-04 22:46:56 +00007469
John McCallaf8e6ed2009-11-12 03:15:40 +00007470 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007471 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007472 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007473 if (!LookupContext) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007474 if (HasTypenameKeyword) {
John McCalled976492009-12-04 22:46:56 +00007475 // FIXME: not all declaration name kinds are legal here
7476 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7477 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007478 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007479 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007480 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007481 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7482 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007483 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007484 D->setAccess(AS);
7485 CurContext->addDecl(D);
7486 return D;
Anders Carlsson550b14b2009-08-28 05:49:21 +00007487 }
John McCalled976492009-12-04 22:46:56 +00007488
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007489 auto Build = [&](bool Invalid) {
7490 UsingDecl *UD =
7491 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7492 HasTypenameKeyword);
7493 UD->setAccess(AS);
7494 CurContext->addDecl(UD);
7495 UD->setInvalidDecl(Invalid);
John McCall604e7f12009-12-08 07:46:18 +00007496 return UD;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007497 };
7498 auto BuildInvalid = [&]{ return Build(true); };
7499 auto BuildValid = [&]{ return Build(false); };
7500
7501 if (RequireCompleteDeclContext(SS, LookupContext))
7502 return BuildInvalid();
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007503
Richard Smithc5a89a12012-04-02 01:30:27 +00007504 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007505 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007506 UsingDecl *UD = BuildValid();
7507 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007508 return UD;
7509 }
7510
7511 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007512
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007513 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007514
John McCall604e7f12009-12-08 07:46:18 +00007515 // Unlike most lookups, we don't always want to hide tag
7516 // declarations: tag names are visible through the using declaration
7517 // even if hidden by ordinary names, *except* in a dependent context
7518 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007519 if (!IsInstantiation)
7520 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007521
John McCallb9abd8722012-04-07 03:04:20 +00007522 // For the purposes of this lookup, we have a base object type
7523 // equal to that of the current context.
7524 if (CurContext->isRecord()) {
7525 R.setBaseObjectType(
7526 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7527 }
7528
John McCalla24dc2e2009-11-17 02:14:36 +00007529 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007530
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007531 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00007532 if (R.empty()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007533 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
7534 dyn_cast<CXXRecordDecl>(CurContext));
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007535 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007536 R.getLookupKind(), S, &SS, CCC,
7537 CTK_ErrorRecovery)){
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007538 // We reject any correction for which ND would be NULL.
7539 NamedDecl *ND = Corrected.getCorrectionDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007540
Richard Smith2d670972013-08-17 00:46:16 +00007541 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007542 // literal '0' below.
Richard Smith2d670972013-08-17 00:46:16 +00007543 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7544 << NameInfo.getName() << LookupContext << 0
7545 << SS.getRange());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007546
7547 // If we corrected to an inheriting constructor, handle it as one.
7548 auto *RD = dyn_cast<CXXRecordDecl>(ND);
7549 if (RD && RD->isInjectedClassName()) {
7550 // Fix up the information we'll use to build the using declaration.
7551 if (Corrected.WillReplaceSpecifier()) {
7552 NestedNameSpecifierLocBuilder Builder;
7553 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7554 QualifierLoc.getSourceRange());
7555 QualifierLoc = Builder.getWithLocInContext(Context);
7556 }
7557
7558 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7559 Context.getCanonicalType(Context.getRecordType(RD))));
7560 NameInfo.setNamedTypeInfo(nullptr);
7561
7562 // Build it and process it as an inheriting constructor.
7563 UsingDecl *UD = BuildValid();
7564 CheckInheritingConstructorUsingDecl(UD);
7565 return UD;
7566 }
7567
7568 // FIXME: Pick up all the declarations if we found an overloaded function.
7569 R.setLookupName(Corrected.getCorrection());
7570 R.addDecl(ND);
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007571 } else {
Richard Smith2d670972013-08-17 00:46:16 +00007572 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007573 << NameInfo.getName() << LookupContext << SS.getRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007574 return BuildInvalid();
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007575 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007576 }
7577
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007578 if (R.isAmbiguous())
7579 return BuildInvalid();
Mike Stump1eb44332009-09-09 15:08:12 +00007580
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007581 if (HasTypenameKeyword) {
John McCall7ba107a2009-11-18 02:36:19 +00007582 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007583 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007584 Diag(IdentLoc, diag::err_using_typename_non_type);
7585 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7586 Diag((*I)->getUnderlyingDecl()->getLocation(),
7587 diag::note_using_decl_target);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007588 return BuildInvalid();
John McCall7ba107a2009-11-18 02:36:19 +00007589 }
7590 } else {
7591 // If we asked for a non-typename and we got a type, error out,
7592 // but only if this is an instantiation of an unresolved using
7593 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007594 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007595 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7596 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007597 return BuildInvalid();
John McCall7ba107a2009-11-18 02:36:19 +00007598 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007599 }
7600
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007601 // C++0x N2914 [namespace.udecl]p6:
7602 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007603 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007604 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7605 << SS.getRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007606 return BuildInvalid();
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007607 }
Mike Stump1eb44332009-09-09 15:08:12 +00007608
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007609 UsingDecl *UD = BuildValid();
John McCall9f54ad42009-12-10 09:41:52 +00007610 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007611 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithf06a28932013-10-23 02:17:46 +00007612 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7613 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall9f54ad42009-12-10 09:41:52 +00007614 }
John McCall9488ea12009-11-17 05:59:44 +00007615
7616 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007617}
7618
Sebastian Redlf677ea32011-02-05 19:23:19 +00007619/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007620bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007621 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007622
Douglas Gregordc355712011-02-25 00:36:19 +00007623 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007624 assert(SourceType &&
7625 "Using decl naming constructor doesn't have type in scope spec.");
7626 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7627
7628 // Check whether the named type is a direct base class.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007629 bool AnyDependentBases = false;
7630 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
7631 AnyDependentBases);
7632 if (!Base && !AnyDependentBases) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007633 Diag(UD->getUsingLoc(),
Sebastian Redlf677ea32011-02-05 19:23:19 +00007634 diag::err_using_decl_constructor_not_in_direct_base)
7635 << UD->getNameInfo().getSourceRange()
7636 << QualType(SourceType, 0) << TargetClass;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007637 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007638 return true;
7639 }
7640
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007641 if (Base)
7642 Base->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007643
7644 return false;
7645}
7646
John McCall9f54ad42009-12-10 09:41:52 +00007647/// Checks that the given using declaration is not an invalid
7648/// redeclaration. Note that this is checking only for the using decl
7649/// itself, not for any ill-formedness among the UsingShadowDecls.
7650bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007651 bool HasTypenameKeyword,
John McCall9f54ad42009-12-10 09:41:52 +00007652 const CXXScopeSpec &SS,
7653 SourceLocation NameLoc,
7654 const LookupResult &Prev) {
7655 // C++03 [namespace.udecl]p8:
7656 // C++0x [namespace.udecl]p10:
7657 // A using-declaration is a declaration and can therefore be used
7658 // repeatedly where (and only where) multiple declarations are
7659 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007660 //
John McCall8a726212010-11-29 18:01:58 +00007661 // That's in non-member contexts.
7662 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007663 return false;
7664
Stephen Hines651f13c2014-04-23 16:59:28 -07007665 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall9f54ad42009-12-10 09:41:52 +00007666
7667 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7668 NamedDecl *D = *I;
7669
7670 bool DTypename;
7671 NestedNameSpecifier *DQual;
7672 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007673 DTypename = UD->hasTypename();
Douglas Gregordc355712011-02-25 00:36:19 +00007674 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007675 } else if (UnresolvedUsingValueDecl *UD
7676 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7677 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007678 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007679 } else if (UnresolvedUsingTypenameDecl *UD
7680 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7681 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007682 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007683 } else continue;
7684
7685 // using decls differ if one says 'typename' and the other doesn't.
7686 // FIXME: non-dependent using decls?
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007687 if (HasTypenameKeyword != DTypename) continue;
John McCall9f54ad42009-12-10 09:41:52 +00007688
7689 // using decls differ if they name different scopes (but note that
7690 // template instantiation can cause this check to trigger when it
7691 // didn't before instantiation).
7692 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7693 Context.getCanonicalNestedNameSpecifier(DQual))
7694 continue;
7695
7696 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007697 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007698 return true;
7699 }
7700
7701 return false;
7702}
7703
John McCall604e7f12009-12-08 07:46:18 +00007704
John McCalled976492009-12-04 22:46:56 +00007705/// Checks that the given nested-name qualifier used in a using decl
7706/// in the current context is appropriately related to the current
7707/// scope. If an error is found, diagnoses it and returns true.
7708bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7709 const CXXScopeSpec &SS,
Stephen Hines651f13c2014-04-23 16:59:28 -07007710 const DeclarationNameInfo &NameInfo,
John McCalled976492009-12-04 22:46:56 +00007711 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007712 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007713
John McCall604e7f12009-12-08 07:46:18 +00007714 if (!CurContext->isRecord()) {
7715 // C++03 [namespace.udecl]p3:
7716 // C++0x [namespace.udecl]p8:
7717 // A using-declaration for a class member shall be a member-declaration.
7718
7719 // If we weren't able to compute a valid scope, it must be a
7720 // dependent class scope.
7721 if (!NamedContext || NamedContext->isRecord()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07007722 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7723 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007724 RD = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07007725
John McCall604e7f12009-12-08 07:46:18 +00007726 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7727 << SS.getRange();
Stephen Hines651f13c2014-04-23 16:59:28 -07007728
7729 // If we have a complete, non-dependent source type, try to suggest a
7730 // way to get the same effect.
7731 if (!RD)
7732 return true;
7733
7734 // Find what this using-declaration was referring to.
7735 LookupResult R(*this, NameInfo, LookupOrdinaryName);
7736 R.setHideTags(false);
7737 R.suppressDiagnostics();
7738 LookupQualifiedName(R, RD);
7739
7740 if (R.getAsSingle<TypeDecl>()) {
7741 if (getLangOpts().CPlusPlus11) {
7742 // Convert 'using X::Y;' to 'using Y = X::Y;'.
7743 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7744 << 0 // alias declaration
7745 << FixItHint::CreateInsertion(SS.getBeginLoc(),
7746 NameInfo.getName().getAsString() +
7747 " = ");
7748 } else {
7749 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7750 SourceLocation InsertLoc =
7751 PP.getLocForEndOfToken(NameInfo.getLocEnd());
7752 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7753 << 1 // typedef declaration
7754 << FixItHint::CreateReplacement(UsingLoc, "typedef")
7755 << FixItHint::CreateInsertion(
7756 InsertLoc, " " + NameInfo.getName().getAsString());
7757 }
7758 } else if (R.getAsSingle<VarDecl>()) {
7759 // Don't provide a fixit outside C++11 mode; we don't want to suggest
7760 // repeating the type of the static data member here.
7761 FixItHint FixIt;
7762 if (getLangOpts().CPlusPlus11) {
7763 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7764 FixIt = FixItHint::CreateReplacement(
7765 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7766 }
7767
7768 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
7769 << 2 // reference declaration
7770 << FixIt;
7771 }
John McCall604e7f12009-12-08 07:46:18 +00007772 return true;
7773 }
7774
7775 // Otherwise, everything is known to be fine.
7776 return false;
7777 }
7778
7779 // The current scope is a record.
7780
7781 // If the named context is dependent, we can't decide much.
7782 if (!NamedContext) {
7783 // FIXME: in C++0x, we can diagnose if we can prove that the
7784 // nested-name-specifier does not refer to a base class, which is
7785 // still possible in some cases.
7786
7787 // Otherwise we have to conservatively report that things might be
7788 // okay.
7789 return false;
7790 }
7791
7792 if (!NamedContext->isRecord()) {
7793 // Ideally this would point at the last name in the specifier,
7794 // but we don't have that level of source info.
7795 Diag(SS.getRange().getBegin(),
7796 diag::err_using_decl_nested_name_specifier_is_not_class)
Stephen Hines651f13c2014-04-23 16:59:28 -07007797 << SS.getScopeRep() << SS.getRange();
John McCall604e7f12009-12-08 07:46:18 +00007798 return true;
7799 }
7800
Douglas Gregor6fb07292010-12-21 07:41:49 +00007801 if (!NamedContext->isDependentContext() &&
7802 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7803 return true;
7804
Richard Smith80ad52f2013-01-02 11:42:31 +00007805 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007806 // C++0x [namespace.udecl]p3:
7807 // In a using-declaration used as a member-declaration, the
7808 // nested-name-specifier shall name a base class of the class
7809 // being defined.
7810
7811 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7812 cast<CXXRecordDecl>(NamedContext))) {
7813 if (CurContext == NamedContext) {
7814 Diag(NameLoc,
7815 diag::err_using_decl_nested_name_specifier_is_current_class)
7816 << SS.getRange();
7817 return true;
7818 }
7819
7820 Diag(SS.getRange().getBegin(),
7821 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Stephen Hines651f13c2014-04-23 16:59:28 -07007822 << SS.getScopeRep()
John McCall604e7f12009-12-08 07:46:18 +00007823 << cast<CXXRecordDecl>(CurContext)
7824 << SS.getRange();
7825 return true;
7826 }
7827
7828 return false;
7829 }
7830
7831 // C++03 [namespace.udecl]p4:
7832 // A using-declaration used as a member-declaration shall refer
7833 // to a member of a base class of the class being defined [etc.].
7834
7835 // Salient point: SS doesn't have to name a base class as long as
7836 // lookup only finds members from base classes. Therefore we can
7837 // diagnose here only if we can prove that that can't happen,
7838 // i.e. if the class hierarchies provably don't intersect.
7839
7840 // TODO: it would be nice if "definitely valid" results were cached
7841 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7842 // need to be repeated.
7843
7844 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007845 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007846
7847 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7848 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7849 Data->Bases.insert(Base);
7850 return true;
7851 }
7852
7853 bool hasDependentBases(const CXXRecordDecl *Class) {
7854 return !Class->forallBases(collect, this);
7855 }
7856
7857 /// Returns true if the base is dependent or is one of the
7858 /// accumulated base classes.
7859 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7860 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7861 return !Data->Bases.count(Base);
7862 }
7863
7864 bool mightShareBases(const CXXRecordDecl *Class) {
7865 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7866 }
7867 };
7868
7869 UserData Data;
7870
7871 // Returns false if we find a dependent base.
7872 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7873 return false;
7874
7875 // Returns false if the class has a dependent base or if it or one
7876 // of its bases is present in the base set of the current context.
7877 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7878 return false;
7879
7880 Diag(SS.getRange().getBegin(),
7881 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Stephen Hines651f13c2014-04-23 16:59:28 -07007882 << SS.getScopeRep()
John McCall604e7f12009-12-08 07:46:18 +00007883 << cast<CXXRecordDecl>(CurContext)
7884 << SS.getRange();
7885
7886 return true;
John McCalled976492009-12-04 22:46:56 +00007887}
7888
Richard Smith162e1c12011-04-15 14:24:37 +00007889Decl *Sema::ActOnAliasDeclaration(Scope *S,
7890 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007891 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007892 SourceLocation UsingLoc,
7893 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007894 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007895 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007896 // Skip up to the relevant declaration scope.
7897 while (S->getFlags() & Scope::TemplateParamScope)
7898 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007899 assert((S->getFlags() & Scope::DeclScope) &&
7900 "got alias-declaration outside of declaration scope");
7901
7902 if (Type.isInvalid())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007903 return nullptr;
Richard Smith162e1c12011-04-15 14:24:37 +00007904
7905 bool Invalid = false;
7906 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007907 TypeSourceInfo *TInfo = nullptr;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007908 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007909
7910 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007911 return nullptr;
Richard Smith162e1c12011-04-15 14:24:37 +00007912
7913 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007914 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007915 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007916 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7917 TInfo->getTypeLoc().getBeginLoc());
7918 }
Richard Smith162e1c12011-04-15 14:24:37 +00007919
7920 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7921 LookupName(Previous, S);
7922
7923 // Warn about shadowing the name of a template parameter.
7924 if (Previous.isSingleResult() &&
7925 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007926 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007927 Previous.clear();
7928 }
7929
7930 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7931 "name in alias declaration must be an identifier");
7932 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7933 Name.StartLocation,
7934 Name.Identifier, TInfo);
7935
7936 NewTD->setAccess(AS);
7937
7938 if (Invalid)
7939 NewTD->setInvalidDecl();
7940
Richard Smith6b3d3e52013-02-20 19:22:51 +00007941 ProcessDeclAttributeList(S, NewTD, AttrList);
7942
Richard Smith3e4c6c42011-05-05 21:57:07 +00007943 CheckTypedefForVariablyModifiedType(S, NewTD);
7944 Invalid |= NewTD->isInvalidDecl();
7945
Richard Smith162e1c12011-04-15 14:24:37 +00007946 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007947
7948 NamedDecl *NewND;
7949 if (TemplateParamLists.size()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007950 TypeAliasTemplateDecl *OldDecl = nullptr;
7951 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007952
7953 if (TemplateParamLists.size() != 1) {
7954 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007955 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7956 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007957 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007958 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007959
7960 // Only consider previous declarations in the same scope.
7961 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7962 /*ExplicitInstantiationOrSpecialization*/false);
7963 if (!Previous.empty()) {
7964 Redeclaration = true;
7965
7966 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7967 if (!OldDecl && !Invalid) {
7968 Diag(UsingLoc, diag::err_redefinition_different_kind)
7969 << Name.Identifier;
7970
7971 NamedDecl *OldD = Previous.getRepresentativeDecl();
7972 if (OldD->getLocation().isValid())
7973 Diag(OldD->getLocation(), diag::note_previous_definition);
7974
7975 Invalid = true;
7976 }
7977
7978 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7979 if (TemplateParameterListsAreEqual(TemplateParams,
7980 OldDecl->getTemplateParameters(),
7981 /*Complain=*/true,
7982 TPL_TemplateMatch))
7983 OldTemplateParams = OldDecl->getTemplateParameters();
7984 else
7985 Invalid = true;
7986
7987 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7988 if (!Invalid &&
7989 !Context.hasSameType(OldTD->getUnderlyingType(),
7990 NewTD->getUnderlyingType())) {
7991 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7992 // but we can't reasonably accept it.
7993 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7994 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7995 if (OldTD->getLocation().isValid())
7996 Diag(OldTD->getLocation(), diag::note_previous_definition);
7997 Invalid = true;
7998 }
7999 }
8000 }
8001
8002 // Merge any previous default template arguments into our parameters,
8003 // and check the parameter list.
8004 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8005 TPC_TypeAliasTemplate))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008006 return nullptr;
Richard Smith3e4c6c42011-05-05 21:57:07 +00008007
8008 TypeAliasTemplateDecl *NewDecl =
8009 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8010 Name.Identifier, TemplateParams,
8011 NewTD);
8012
8013 NewDecl->setAccess(AS);
8014
8015 if (Invalid)
8016 NewDecl->setInvalidDecl();
8017 else if (OldDecl)
Rafael Espindolabc650912013-10-17 15:37:26 +00008018 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3e4c6c42011-05-05 21:57:07 +00008019
8020 NewND = NewDecl;
8021 } else {
8022 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8023 NewND = NewTD;
8024 }
Richard Smith162e1c12011-04-15 14:24:37 +00008025
8026 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00008027 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00008028
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00008029 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00008030 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00008031}
8032
John McCalld226f652010-08-21 09:40:31 +00008033Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00008034 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00008035 SourceLocation AliasLoc,
8036 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00008037 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00008038 SourceLocation IdentLoc,
8039 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00008040
Anders Carlsson81c85c42009-03-28 23:53:49 +00008041 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00008042 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8043 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00008044
Anders Carlsson8d7ba402009-03-28 06:23:46 +00008045 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00008046 NamedDecl *PrevDecl
8047 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8048 ForRedeclaration);
8049 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008050 PrevDecl = nullptr;
Douglas Gregorae374752010-05-03 15:37:31 +00008051
8052 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00008053 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00008054 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00008055 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00008056 // FIXME: At some point, we'll want to create the (redundant)
8057 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00008058 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00008059 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008060 return nullptr;
Anders Carlsson81c85c42009-03-28 23:53:49 +00008061 }
Mike Stump1eb44332009-09-09 15:08:12 +00008062
Anders Carlsson8d7ba402009-03-28 06:23:46 +00008063 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
8064 diag::err_redefinition_different_kind;
8065 Diag(AliasLoc, DiagID) << Alias;
8066 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008067 return nullptr;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00008068 }
8069
John McCalla24dc2e2009-11-17 02:14:36 +00008070 if (R.isAmbiguous())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008071 return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +00008072
John McCallf36e02d2009-10-09 21:13:30 +00008073 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00008074 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00008075 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008076 return nullptr;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00008077 }
Anders Carlsson5721c682009-03-28 06:42:02 +00008078 }
Mike Stump1eb44332009-09-09 15:08:12 +00008079
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008080 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00008081 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00008082 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00008083 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00008084
John McCall3dbd3d52010-02-16 06:53:13 +00008085 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00008086 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00008087}
8088
Sean Hunt001cad92011-05-10 00:49:42 +00008089Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008090Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8091 CXXMethodDecl *MD) {
8092 CXXRecordDecl *ClassDecl = MD->getParent();
8093
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008094 // C++ [except.spec]p14:
8095 // An implicitly declared special member function (Clause 12) shall have an
8096 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00008097 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008098 if (ClassDecl->isInvalidDecl())
8099 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008100
Sebastian Redl60618fa2011-03-12 11:50:43 +00008101 // Direct base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008102 for (const auto &B : ClassDecl->bases()) {
8103 if (B.isVirtual()) // Handled below.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008104 continue;
8105
Stephen Hines651f13c2014-04-23 16:59:28 -07008106 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor18274032010-07-03 00:47:00 +00008107 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00008108 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8109 // If this is a deleted function, add it anyway. This might be conformant
8110 // with the standard. This might not. I'm not sure. It might not matter.
8111 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -07008112 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00008113 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008114 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008115
8116 // Virtual base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008117 for (const auto &B : ClassDecl->vbases()) {
8118 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor18274032010-07-03 00:47:00 +00008119 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00008120 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8121 // If this is a deleted function, add it anyway. This might be conformant
8122 // with the standard. This might not. I'm not sure. It might not matter.
8123 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -07008124 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00008125 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008126 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008127
8128 // Field constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008129 for (const auto *F : ClassDecl->fields()) {
Richard Smith7a614d82011-06-11 17:19:42 +00008130 if (F->hasInClassInitializer()) {
8131 if (Expr *E = F->getInClassInitializer())
8132 ExceptSpec.CalledExpr(E);
8133 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00008134 // DR1351:
8135 // If the brace-or-equal-initializer of a non-static data member
8136 // invokes a defaulted default constructor of its class or of an
8137 // enclosing class in a potentially evaluated subexpression, the
8138 // program is ill-formed.
8139 //
8140 // This resolution is unworkable: the exception specification of the
8141 // default constructor can be needed in an unevaluated context, in
8142 // particular, in the operand of a noexcept-expression, and we can be
8143 // unable to compute an exception specification for an enclosed class.
8144 //
8145 // We do not allow an in-class initializer to require the evaluation
8146 // of the exception specification for any in-class initializer whose
8147 // definition is not lexically complete.
8148 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00008149 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00008150 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00008151 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8152 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8153 // If this is a deleted function, add it anyway. This might be conformant
8154 // with the standard. This might not. I'm not sure. It might not matter.
8155 // In particular, the problem is that this function never gets called. It
8156 // might just be ill-formed because this function attempts to refer to
8157 // a deleted function here.
8158 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008159 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00008160 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008161 }
John McCalle23cf432010-12-14 08:05:40 +00008162
Sean Hunt001cad92011-05-10 00:49:42 +00008163 return ExceptSpec;
8164}
8165
Richard Smith07b0fdc2013-03-18 21:12:30 +00008166Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00008167Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8168 CXXRecordDecl *ClassDecl = CD->getParent();
8169
8170 // C++ [except.spec]p14:
8171 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00008172 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00008173 if (ClassDecl->isInvalidDecl())
8174 return ExceptSpec;
8175
8176 // Inherited constructor.
8177 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8178 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8179 // FIXME: Copying or moving the parameters could add extra exceptions to the
8180 // set, as could the default arguments for the inherited constructor. This
8181 // will be addressed when we implement the resolution of core issue 1351.
8182 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8183
8184 // Direct base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008185 for (const auto &B : ClassDecl->bases()) {
8186 if (B.isVirtual()) // Handled below.
Richard Smith0b0ca472013-04-10 06:11:48 +00008187 continue;
8188
Stephen Hines651f13c2014-04-23 16:59:28 -07008189 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smith0b0ca472013-04-10 06:11:48 +00008190 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8191 if (BaseClassDecl == InheritedDecl)
8192 continue;
8193 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8194 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -07008195 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smith0b0ca472013-04-10 06:11:48 +00008196 }
8197 }
8198
8199 // Virtual base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008200 for (const auto &B : ClassDecl->vbases()) {
8201 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smith0b0ca472013-04-10 06:11:48 +00008202 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8203 if (BaseClassDecl == InheritedDecl)
8204 continue;
8205 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8206 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -07008207 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smith0b0ca472013-04-10 06:11:48 +00008208 }
8209 }
8210
8211 // Field constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008212 for (const auto *F : ClassDecl->fields()) {
Richard Smith0b0ca472013-04-10 06:11:48 +00008213 if (F->hasInClassInitializer()) {
8214 if (Expr *E = F->getInClassInitializer())
8215 ExceptSpec.CalledExpr(E);
8216 else if (!F->isInvalidDecl())
8217 Diag(CD->getLocation(),
8218 diag::err_in_class_initializer_references_def_ctor) << CD;
8219 } else if (const RecordType *RecordTy
8220 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8221 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8222 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8223 if (Constructor)
8224 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8225 }
8226 }
8227
Richard Smith07b0fdc2013-03-18 21:12:30 +00008228 return ExceptSpec;
8229}
8230
Richard Smithafb49182012-11-29 01:34:07 +00008231namespace {
8232/// RAII object to register a special member as being currently declared.
8233struct DeclaringSpecialMember {
8234 Sema &S;
8235 Sema::SpecialMemberDecl D;
8236 bool WasAlreadyBeingDeclared;
8237
8238 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8239 : S(S), D(RD, CSM) {
8240 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8241 if (WasAlreadyBeingDeclared)
8242 // This almost never happens, but if it does, ensure that our cache
8243 // doesn't contain a stale result.
8244 S.SpecialMemberCache.clear();
8245
8246 // FIXME: Register a note to be produced if we encounter an error while
8247 // declaring the special member.
8248 }
8249 ~DeclaringSpecialMember() {
8250 if (!WasAlreadyBeingDeclared)
8251 S.SpecialMembersBeingDeclared.erase(D);
8252 }
8253
8254 /// \brief Are we already trying to declare this special member?
8255 bool isAlreadyBeingDeclared() const {
8256 return WasAlreadyBeingDeclared;
8257 }
8258};
8259}
8260
Sean Hunt001cad92011-05-10 00:49:42 +00008261CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8262 CXXRecordDecl *ClassDecl) {
8263 // C++ [class.ctor]p5:
8264 // A default constructor for a class X is a constructor of class X
8265 // that can be called without an argument. If there is no
8266 // user-declared constructor for class X, a default constructor is
8267 // implicitly declared. An implicitly-declared default constructor
8268 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00008269 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00008270 "Should not build implicit default constructor!");
8271
Richard Smithafb49182012-11-29 01:34:07 +00008272 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8273 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008274 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +00008275
Richard Smith7756afa2012-06-10 05:43:50 +00008276 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8277 CXXDefaultConstructor,
8278 false);
8279
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008280 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00008281 CanQualType ClassType
8282 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008283 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00008284 DeclarationName Name
8285 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008286 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00008287 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008288 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8289 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8290 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00008291 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00008292 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00008293 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008294
8295 // Build an exception specification pointing back at this constructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008296 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008297 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008298
Richard Smithbc2a35d2012-12-08 08:32:28 +00008299 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8300 // constructors is easy to compute.
8301 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8302
8303 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008304 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008305
Douglas Gregor18274032010-07-03 00:47:00 +00008306 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00008307 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00008308
Douglas Gregor23c94db2010-07-02 17:43:08 +00008309 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00008310 PushOnScopeChains(DefaultCon, S, false);
8311 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00008312
Douglas Gregor32df23e2010-07-01 22:02:46 +00008313 return DefaultCon;
8314}
8315
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008316void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8317 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00008318 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008319 !Constructor->doesThisDeclarationHaveABody() &&
8320 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00008321 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008322
Anders Carlssonf6513ed2010-04-23 16:04:08 +00008323 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00008324 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00008325
Eli Friedman9a14db32012-10-18 20:14:08 +00008326 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008327 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00008328 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008329 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008330 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00008331 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00008332 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008333 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00008334 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008335
8336 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008337 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008338
Eli Friedman86164e82013-09-05 00:02:25 +00008339 Constructor->markUsed(Context);
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008340 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008341
8342 if (ASTMutationListener *L = getASTMutationListener()) {
8343 L->CompletedImplicitDefinition(Constructor);
8344 }
Richard Trieu858d2ba2013-10-25 00:56:00 +00008345
8346 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008347}
8348
Richard Smith7a614d82011-06-11 17:19:42 +00008349void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Toker08235662013-10-18 05:54:19 +00008350 // Perform any delayed checks on exception specifications.
8351 CheckDelayedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00008352}
8353
Richard Smith4841ca52013-04-10 05:48:59 +00008354namespace {
8355/// Information on inheriting constructors to declare.
8356class InheritingConstructorInfo {
8357public:
8358 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8359 : SemaRef(SemaRef), Derived(Derived) {
8360 // Mark the constructors that we already have in the derived class.
8361 //
8362 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8363 // unless there is a user-declared constructor with the same signature in
8364 // the class where the using-declaration appears.
8365 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8366 }
8367
8368 void inheritAll(CXXRecordDecl *RD) {
8369 visitAll(RD, &InheritingConstructorInfo::inherit);
8370 }
8371
8372private:
8373 /// Information about an inheriting constructor.
8374 struct InheritingConstructor {
8375 InheritingConstructor()
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008376 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith4841ca52013-04-10 05:48:59 +00008377
8378 /// If \c true, a constructor with this signature is already declared
8379 /// in the derived class.
8380 bool DeclaredInDerived;
8381
8382 /// The constructor which is inherited.
8383 const CXXConstructorDecl *BaseCtor;
8384
8385 /// The derived constructor we declared.
8386 CXXConstructorDecl *DerivedCtor;
8387 };
8388
8389 /// Inheriting constructors with a given canonical type. There can be at
8390 /// most one such non-template constructor, and any number of templated
8391 /// constructors.
8392 struct InheritingConstructorsForType {
8393 InheritingConstructor NonTemplate;
Robert Wilhelme7205c02013-08-10 12:33:24 +00008394 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8395 Templates;
Richard Smith4841ca52013-04-10 05:48:59 +00008396
8397 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8398 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8399 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8400 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8401 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8402 false, S.TPL_TemplateMatch))
8403 return Templates[I].second;
8404 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8405 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008406 }
Richard Smith4841ca52013-04-10 05:48:59 +00008407
8408 return NonTemplate;
8409 }
8410 };
8411
8412 /// Get or create the inheriting constructor record for a constructor.
8413 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8414 QualType CtorType) {
8415 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8416 .getEntry(SemaRef, Ctor);
8417 }
8418
8419 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8420
8421 /// Process all constructors for a class.
8422 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Stephen Hines651f13c2014-04-23 16:59:28 -07008423 for (const auto *Ctor : RD->ctors())
8424 (this->*Callback)(Ctor);
Richard Smith4841ca52013-04-10 05:48:59 +00008425 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8426 I(RD->decls_begin()), E(RD->decls_end());
8427 I != E; ++I) {
8428 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8429 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8430 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008431 }
8432 }
Richard Smith4841ca52013-04-10 05:48:59 +00008433
8434 /// Note that a constructor (or constructor template) was declared in Derived.
8435 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8436 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8437 }
8438
8439 /// Inherit a single constructor.
8440 void inherit(const CXXConstructorDecl *Ctor) {
8441 const FunctionProtoType *CtorType =
8442 Ctor->getType()->castAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07008443 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
Richard Smith4841ca52013-04-10 05:48:59 +00008444 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8445
8446 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8447
8448 // Core issue (no number yet): the ellipsis is always discarded.
8449 if (EPI.Variadic) {
8450 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8451 SemaRef.Diag(Ctor->getLocation(),
8452 diag::note_using_decl_constructor_ellipsis);
8453 EPI.Variadic = false;
8454 }
8455
8456 // Declare a constructor for each number of parameters.
8457 //
8458 // C++11 [class.inhctor]p1:
8459 // The candidate set of inherited constructors from the class X named in
8460 // the using-declaration consists of [... modulo defects ...] for each
8461 // constructor or constructor template of X, the set of constructors or
8462 // constructor templates that results from omitting any ellipsis parameter
8463 // specification and successively omitting parameters with a default
8464 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008465 unsigned MinParams = minParamsToInherit(Ctor);
8466 unsigned Params = Ctor->getNumParams();
8467 if (Params >= MinParams) {
8468 do
8469 declareCtor(UsingLoc, Ctor,
8470 SemaRef.Context.getFunctionType(
Stephen Hines651f13c2014-04-23 16:59:28 -07008471 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith987c0302013-04-17 19:00:52 +00008472 while (Params > MinParams &&
8473 Ctor->getParamDecl(--Params)->hasDefaultArg());
8474 }
Richard Smith4841ca52013-04-10 05:48:59 +00008475 }
8476
8477 /// Find the using-declaration which specified that we should inherit the
8478 /// constructors of \p Base.
8479 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8480 // No fancy lookup required; just look for the base constructor name
8481 // directly within the derived class.
8482 ASTContext &Context = SemaRef.Context;
8483 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8484 Context.getCanonicalType(Context.getRecordType(Base)));
8485 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8486 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8487 }
8488
8489 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8490 // C++11 [class.inhctor]p3:
8491 // [F]or each constructor template in the candidate set of inherited
8492 // constructors, a constructor template is implicitly declared
8493 if (Ctor->getDescribedFunctionTemplate())
8494 return 0;
8495
8496 // For each non-template constructor in the candidate set of inherited
8497 // constructors other than a constructor having no parameters or a
8498 // copy/move constructor having a single parameter, a constructor is
8499 // implicitly declared [...]
8500 if (Ctor->getNumParams() == 0)
8501 return 1;
8502 if (Ctor->isCopyOrMoveConstructor())
8503 return 2;
8504
8505 // Per discussion on core reflector, never inherit a constructor which
8506 // would become a default, copy, or move constructor of Derived either.
8507 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8508 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8509 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8510 }
8511
8512 /// Declare a single inheriting constructor, inheriting the specified
8513 /// constructor, with the given type.
8514 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8515 QualType DerivedType) {
8516 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8517
8518 // C++11 [class.inhctor]p3:
8519 // ... a constructor is implicitly declared with the same constructor
8520 // characteristics unless there is a user-declared constructor with
8521 // the same signature in the class where the using-declaration appears
8522 if (Entry.DeclaredInDerived)
8523 return;
8524
8525 // C++11 [class.inhctor]p7:
8526 // If two using-declarations declare inheriting constructors with the
8527 // same signature, the program is ill-formed
8528 if (Entry.DerivedCtor) {
8529 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8530 // Only diagnose this once per constructor.
8531 if (Entry.DerivedCtor->isInvalidDecl())
8532 return;
8533 Entry.DerivedCtor->setInvalidDecl();
8534
8535 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8536 SemaRef.Diag(BaseCtor->getLocation(),
8537 diag::note_using_decl_constructor_conflict_current_ctor);
8538 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8539 diag::note_using_decl_constructor_conflict_previous_ctor);
8540 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8541 diag::note_using_decl_constructor_conflict_previous_using);
8542 } else {
8543 // Core issue (no number): if the same inheriting constructor is
8544 // produced by multiple base class constructors from the same base
8545 // class, the inheriting constructor is defined as deleted.
8546 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8547 }
8548
8549 return;
8550 }
8551
8552 ASTContext &Context = SemaRef.Context;
8553 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8554 Context.getCanonicalType(Context.getRecordType(Derived)));
8555 DeclarationNameInfo NameInfo(Name, UsingLoc);
8556
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008557 TemplateParameterList *TemplateParams = nullptr;
Richard Smith4841ca52013-04-10 05:48:59 +00008558 if (const FunctionTemplateDecl *FTD =
8559 BaseCtor->getDescribedFunctionTemplate()) {
8560 TemplateParams = FTD->getTemplateParameters();
8561 // We're reusing template parameters from a different DeclContext. This
8562 // is questionable at best, but works out because the template depth in
8563 // both places is guaranteed to be 0.
8564 // FIXME: Rebuild the template parameters in the new context, and
8565 // transform the function type to refer to them.
8566 }
8567
8568 // Build type source info pointing at the using-declaration. This is
8569 // required by template instantiation.
8570 TypeSourceInfo *TInfo =
8571 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8572 FunctionProtoTypeLoc ProtoLoc =
8573 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8574
8575 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8576 Context, Derived, UsingLoc, NameInfo, DerivedType,
8577 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8578 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8579
8580 // Build an unevaluated exception specification for this constructor.
8581 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8582 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8583 EPI.ExceptionSpecType = EST_Unevaluated;
8584 EPI.ExceptionSpecDecl = DerivedCtor;
Stephen Hines651f13c2014-04-23 16:59:28 -07008585 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
8586 FPT->getParamTypes(), EPI));
Richard Smith4841ca52013-04-10 05:48:59 +00008587
8588 // Build the parameter declarations.
8589 SmallVector<ParmVarDecl *, 16> ParamDecls;
Stephen Hines651f13c2014-04-23 16:59:28 -07008590 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith4841ca52013-04-10 05:48:59 +00008591 TypeSourceInfo *TInfo =
Stephen Hines651f13c2014-04-23 16:59:28 -07008592 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith4841ca52013-04-10 05:48:59 +00008593 ParmVarDecl *PD = ParmVarDecl::Create(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008594 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
8595 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith4841ca52013-04-10 05:48:59 +00008596 PD->setScopeInfo(0, I);
8597 PD->setImplicit();
8598 ParamDecls.push_back(PD);
Stephen Hines651f13c2014-04-23 16:59:28 -07008599 ProtoLoc.setParam(I, PD);
Richard Smith4841ca52013-04-10 05:48:59 +00008600 }
8601
8602 // Set up the new constructor.
8603 DerivedCtor->setAccess(BaseCtor->getAccess());
8604 DerivedCtor->setParams(ParamDecls);
8605 DerivedCtor->setInheritedConstructor(BaseCtor);
8606 if (BaseCtor->isDeleted())
8607 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8608
8609 // If this is a constructor template, build the template declaration.
8610 if (TemplateParams) {
8611 FunctionTemplateDecl *DerivedTemplate =
8612 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8613 TemplateParams, DerivedCtor);
8614 DerivedTemplate->setAccess(BaseCtor->getAccess());
8615 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8616 Derived->addDecl(DerivedTemplate);
8617 } else {
8618 Derived->addDecl(DerivedCtor);
8619 }
8620
8621 Entry.BaseCtor = BaseCtor;
8622 Entry.DerivedCtor = DerivedCtor;
8623 }
8624
8625 Sema &SemaRef;
8626 CXXRecordDecl *Derived;
8627 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8628 MapType Map;
8629};
8630}
8631
8632void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8633 // Defer declaring the inheriting constructors until the class is
8634 // instantiated.
8635 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008636 return;
8637
Richard Smith4841ca52013-04-10 05:48:59 +00008638 // Find base classes from which we might inherit constructors.
8639 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Stephen Hines651f13c2014-04-23 16:59:28 -07008640 for (const auto &BaseIt : ClassDecl->bases())
8641 if (BaseIt.getInheritConstructors())
8642 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008643
Richard Smith4841ca52013-04-10 05:48:59 +00008644 // Go no further if we're not inheriting any constructors.
8645 if (InheritedBases.empty())
8646 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008647
Richard Smith4841ca52013-04-10 05:48:59 +00008648 // Declare the inherited constructors.
8649 InheritingConstructorInfo ICI(*this, ClassDecl);
8650 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8651 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008652}
8653
Richard Smith07b0fdc2013-03-18 21:12:30 +00008654void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8655 CXXConstructorDecl *Constructor) {
8656 CXXRecordDecl *ClassDecl = Constructor->getParent();
8657 assert(Constructor->getInheritedConstructor() &&
8658 !Constructor->doesThisDeclarationHaveABody() &&
8659 !Constructor->isDeleted());
8660
8661 SynthesizedFunctionScope Scope(*this, Constructor);
8662 DiagnosticErrorTrap Trap(Diags);
8663 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8664 Trap.hasErrorOccurred()) {
8665 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8666 << Context.getTagDeclType(ClassDecl);
8667 Constructor->setInvalidDecl();
8668 return;
8669 }
8670
8671 SourceLocation Loc = Constructor->getLocation();
8672 Constructor->setBody(new (Context) CompoundStmt(Loc));
8673
Eli Friedman86164e82013-09-05 00:02:25 +00008674 Constructor->markUsed(Context);
Richard Smith07b0fdc2013-03-18 21:12:30 +00008675 MarkVTableUsed(CurrentLocation, ClassDecl);
8676
8677 if (ASTMutationListener *L = getASTMutationListener()) {
8678 L->CompletedImplicitDefinition(Constructor);
8679 }
8680}
8681
8682
Sean Huntcb45a0f2011-05-12 22:46:25 +00008683Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008684Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8685 CXXRecordDecl *ClassDecl = MD->getParent();
8686
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008687 // C++ [except.spec]p14:
8688 // An implicitly declared special member function (Clause 12) shall have
8689 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008690 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008691 if (ClassDecl->isInvalidDecl())
8692 return ExceptSpec;
8693
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008694 // Direct base-class destructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008695 for (const auto &B : ClassDecl->bases()) {
8696 if (B.isVirtual()) // Handled below.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008697 continue;
8698
Stephen Hines651f13c2014-04-23 16:59:28 -07008699 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8700 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008701 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008702 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008703
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008704 // Virtual base-class destructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008705 for (const auto &B : ClassDecl->vbases()) {
8706 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8707 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008708 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008709 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008710
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008711 // Field destructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008712 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008713 if (const RecordType *RecordTy
8714 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008715 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008716 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008717 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008718
Sean Huntcb45a0f2011-05-12 22:46:25 +00008719 return ExceptSpec;
8720}
8721
8722CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8723 // C++ [class.dtor]p2:
8724 // If a class has no user-declared destructor, a destructor is
8725 // declared implicitly. An implicitly-declared destructor is an
8726 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008727 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008728
Richard Smithafb49182012-11-29 01:34:07 +00008729 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8730 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008731 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +00008732
Douglas Gregor4923aa22010-07-02 20:37:36 +00008733 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008734 CanQualType ClassType
8735 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008736 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008737 DeclarationName Name
8738 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008739 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008740 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008741 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008742 QualType(), nullptr, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008743 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008744 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008745 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008746 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008747
8748 // Build an exception specification pointing back at this destructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008749 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008750 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008751
Richard Smithbc2a35d2012-12-08 08:32:28 +00008752 AddOverriddenMethods(ClassDecl, Destructor);
8753
8754 // We don't need to use SpecialMemberIsTrivial here; triviality for
8755 // destructors is easy to compute.
8756 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8757
8758 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008759 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008760
Douglas Gregor4923aa22010-07-02 20:37:36 +00008761 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008762 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008763
Douglas Gregor4923aa22010-07-02 20:37:36 +00008764 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008765 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008766 PushOnScopeChains(Destructor, S, false);
8767 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008768
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008769 return Destructor;
8770}
8771
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008772void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008773 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008774 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008775 !Destructor->doesThisDeclarationHaveABody() &&
8776 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008777 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008778 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008779 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008780
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008781 if (Destructor->isInvalidDecl())
8782 return;
8783
Eli Friedman9a14db32012-10-18 20:14:08 +00008784 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008785
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008786 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008787 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8788 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008789
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008790 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008791 Diag(CurrentLocation, diag::note_member_synthesized_at)
8792 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8793
8794 Destructor->setInvalidDecl();
8795 return;
8796 }
8797
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008798 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008799 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman86164e82013-09-05 00:02:25 +00008800 Destructor->markUsed(Context);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008801 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008802
8803 if (ASTMutationListener *L = getASTMutationListener()) {
8804 L->CompletedImplicitDefinition(Destructor);
8805 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008806}
8807
Richard Smitha4156b82012-04-21 18:42:51 +00008808/// \brief Perform any semantic analysis which needs to be delayed until all
8809/// pending class member declarations have been parsed.
8810void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008811 // If the context is an invalid C++ class, just suppress these checks.
8812 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8813 if (Record->isInvalidDecl()) {
Alp Toker08235662013-10-18 05:54:19 +00008814 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregor10318842013-02-01 04:49:10 +00008815 DelayedDestructorExceptionSpecChecks.clear();
8816 return;
8817 }
8818 }
Richard Smitha4156b82012-04-21 18:42:51 +00008819}
8820
Richard Smithb9d0b762012-07-27 04:22:15 +00008821void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8822 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008823 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008824 "adjusting dtor exception specs was introduced in c++11");
8825
Sebastian Redl0ee33912011-05-19 05:13:44 +00008826 // C++11 [class.dtor]p3:
8827 // A declaration of a destructor that does not have an exception-
8828 // specification is implicitly considered to have the same exception-
8829 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008830 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008831 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008832 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008833 return;
8834
Chandler Carruth3f224b22011-09-20 04:55:26 +00008835 // Replace the destructor's type, building off the existing one. Fortunately,
8836 // the only thing of interest in the destructor type is its extended info.
8837 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008838 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8839 EPI.ExceptionSpecType = EST_Unevaluated;
8840 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008841 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008842
Sebastian Redl0ee33912011-05-19 05:13:44 +00008843 // FIXME: If the destructor has a body that could throw, and the newly created
8844 // spec doesn't allow exceptions, we should emit a warning, because this
8845 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008846 // However, we don't have a body or an exception specification yet, so it
8847 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008848}
8849
Pavel Labath66ea35d2013-08-30 08:52:28 +00008850namespace {
8851/// \brief An abstract base class for all helper classes used in building the
8852// copy/move operators. These classes serve as factory functions and help us
8853// avoid using the same Expr* in the AST twice.
8854class ExprBuilder {
8855 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8856 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8857
8858protected:
8859 static Expr *assertNotNull(Expr *E) {
8860 assert(E && "Expression construction must not fail.");
8861 return E;
8862 }
8863
8864public:
8865 ExprBuilder() {}
8866 virtual ~ExprBuilder() {}
8867
8868 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8869};
8870
8871class RefBuilder: public ExprBuilder {
8872 VarDecl *Var;
8873 QualType VarType;
8874
8875public:
Stephen Hines651f13c2014-04-23 16:59:28 -07008876 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008877 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8878 }
8879
8880 RefBuilder(VarDecl *Var, QualType VarType)
8881 : Var(Var), VarType(VarType) {}
8882};
8883
8884class ThisBuilder: public ExprBuilder {
8885public:
Stephen Hines651f13c2014-04-23 16:59:28 -07008886 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008887 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8888 }
8889};
8890
8891class CastBuilder: public ExprBuilder {
8892 const ExprBuilder &Builder;
8893 QualType Type;
8894 ExprValueKind Kind;
8895 const CXXCastPath &Path;
8896
8897public:
Stephen Hines651f13c2014-04-23 16:59:28 -07008898 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008899 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8900 CK_UncheckedDerivedToBase, Kind,
8901 &Path).take());
8902 }
8903
8904 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8905 const CXXCastPath &Path)
8906 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8907};
8908
8909class DerefBuilder: public ExprBuilder {
8910 const ExprBuilder &Builder;
8911
8912public:
Stephen Hines651f13c2014-04-23 16:59:28 -07008913 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008914 return assertNotNull(
8915 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8916 }
8917
8918 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8919};
8920
8921class MemberBuilder: public ExprBuilder {
8922 const ExprBuilder &Builder;
8923 QualType Type;
8924 CXXScopeSpec SS;
8925 bool IsArrow;
8926 LookupResult &MemberLookup;
8927
8928public:
Stephen Hines651f13c2014-04-23 16:59:28 -07008929 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008930 return assertNotNull(S.BuildMemberReferenceExpr(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008931 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
8932 nullptr, MemberLookup, nullptr).take());
Pavel Labath66ea35d2013-08-30 08:52:28 +00008933 }
8934
8935 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8936 LookupResult &MemberLookup)
8937 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8938 MemberLookup(MemberLookup) {}
8939};
8940
8941class MoveCastBuilder: public ExprBuilder {
8942 const ExprBuilder &Builder;
8943
8944public:
Stephen Hines651f13c2014-04-23 16:59:28 -07008945 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008946 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8947 }
8948
8949 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8950};
8951
8952class LvalueConvBuilder: public ExprBuilder {
8953 const ExprBuilder &Builder;
8954
8955public:
Stephen Hines651f13c2014-04-23 16:59:28 -07008956 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008957 return assertNotNull(
8958 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8959 }
8960
8961 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8962};
8963
8964class SubscriptBuilder: public ExprBuilder {
8965 const ExprBuilder &Base;
8966 const ExprBuilder &Index;
8967
8968public:
Stephen Hines651f13c2014-04-23 16:59:28 -07008969 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008970 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8971 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8972 }
8973
8974 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8975 : Base(Base), Index(Index) {}
8976};
8977
8978} // end anonymous namespace
8979
Richard Smith8c889532012-11-14 00:50:40 +00008980/// When generating a defaulted copy or move assignment operator, if a field
8981/// should be copied with __builtin_memcpy rather than via explicit assignments,
8982/// do so. This optimization only applies for arrays of scalars, and for arrays
8983/// of class type where the selected copy/move-assignment operator is trivial.
8984static StmtResult
8985buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008986 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith8c889532012-11-14 00:50:40 +00008987 // Compute the size of the memory buffer to be copied.
8988 QualType SizeType = S.Context.getSizeType();
8989 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8990 S.Context.getTypeSizeInChars(T).getQuantity());
8991
8992 // Take the address of the field references for "from" and "to". We
8993 // directly construct UnaryOperators here because semantic analysis
8994 // does not permit us to take the address of an xvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00008995 Expr *From = FromB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008996 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8997 S.Context.getPointerType(From->getType()),
8998 VK_RValue, OK_Ordinary, Loc);
Pavel Labath66ea35d2013-08-30 08:52:28 +00008999 Expr *To = ToB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009000 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9001 S.Context.getPointerType(To->getType()),
9002 VK_RValue, OK_Ordinary, Loc);
9003
9004 const Type *E = T->getBaseElementTypeUnsafe();
9005 bool NeedsCollectableMemCpy =
9006 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9007
9008 // Create a reference to the __builtin_objc_memmove_collectable function
9009 StringRef MemCpyName = NeedsCollectableMemCpy ?
9010 "__builtin_objc_memmove_collectable" :
9011 "__builtin_memcpy";
9012 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9013 Sema::LookupOrdinaryName);
9014 S.LookupName(R, S.TUScope, true);
9015
9016 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9017 if (!MemCpy)
9018 // Something went horribly wrong earlier, and we will have complained
9019 // about it.
9020 return StmtError();
9021
9022 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009023 VK_RValue, Loc, nullptr);
Richard Smith8c889532012-11-14 00:50:40 +00009024 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9025
9026 Expr *CallArgs[] = {
9027 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9028 };
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009029 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.take(),
Richard Smith8c889532012-11-14 00:50:40 +00009030 Loc, CallArgs, Loc);
9031
9032 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9033 return S.Owned(Call.takeAs<Stmt>());
9034}
9035
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009036/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00009037/// \c To.
9038///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009039/// This routine is used to copy/move the members of a class with an
9040/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00009041/// copied are arrays, this routine builds for loops to copy them.
9042///
9043/// \param S The Sema object used for type-checking.
9044///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009045/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00009046///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009047/// \param T The type of the expressions being copied/moved. Both expressions
9048/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00009049///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009050/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00009051///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009052/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00009053///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009054/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009055/// Otherwise, it's a non-static member subobject.
9056///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009057/// \param Copying Whether we're copying or moving.
9058///
Douglas Gregor06a9f362010-05-01 20:49:11 +00009059/// \param Depth Internal parameter recording the depth of the recursion.
9060///
Richard Smith8c889532012-11-14 00:50:40 +00009061/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9062/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00009063static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00009064buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009065 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00009066 bool CopyingBaseSubobject, bool Copying,
9067 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00009068 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00009069 // Each subobject is assigned in the manner appropriate to its type:
9070 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009071 // - if the subobject is of class type, as if by a call to operator= with
9072 // the subobject as the object expression and the corresponding
9073 // subobject of x as a single function argument (as if by explicit
9074 // qualification; that is, ignoring any possible virtual overriding
9075 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00009076 //
9077 // C++03 [class.copy]p13:
9078 // - if the subobject is of class type, the copy assignment operator for
9079 // the class is used (as if by explicit qualification; that is,
9080 // ignoring any possible virtual overriding functions in more derived
9081 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009082 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9083 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00009084
Douglas Gregor06a9f362010-05-01 20:49:11 +00009085 // Look for operator=.
9086 DeclarationName Name
9087 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9088 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9089 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009090
Richard Smith044c8aa2012-11-13 00:54:12 +00009091 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9092 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00009093 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00009094 LookupResult::Filter F = OpLookup.makeFilter();
9095 while (F.hasNext()) {
9096 NamedDecl *D = F.next();
9097 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9098 if (Method->isCopyAssignmentOperator() ||
9099 (!Copying && Method->isMoveAssignmentOperator()))
9100 continue;
9101
9102 F.erase();
9103 }
9104 F.done();
John McCallb0207482010-03-16 06:11:48 +00009105 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009106
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009107 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00009108 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009109 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00009110 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009111 // ambiguities), we need to cast "this" to that subobject type; to
9112 // ensure that we don't go through the virtual call mechanism, we need
9113 // to qualify the operator= name with the base class (see below). However,
9114 // this means that if the base class has a protected copy assignment
9115 // operator, the protected member access check will fail. So, we
9116 // rewrite "protected" access to "public" access in this case, since we
9117 // know by construction that we're calling from a derived class.
9118 if (CopyingBaseSubobject) {
9119 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9120 L != LEnd; ++L) {
9121 if (L.getAccess() == AS_protected)
9122 L.setAccess(AS_public);
9123 }
9124 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009125
Douglas Gregor06a9f362010-05-01 20:49:11 +00009126 // Create the nested-name-specifier that will be used to qualify the
9127 // reference to operator=; this is required to suppress the virtual
9128 // call mechanism.
9129 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00009130 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00009131 SS.MakeTrivial(S.Context,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009132 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00009133 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00009134 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00009135
Douglas Gregor06a9f362010-05-01 20:49:11 +00009136 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00009137 ExprResult OpEqualRef
Pavel Labath66ea35d2013-08-30 08:52:28 +00009138 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9139 SS, /*TemplateKWLoc=*/SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009140 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009141 OpLookup,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009142 /*TemplateArgs=*/nullptr,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009143 /*SuppressQualifierCheck=*/true);
9144 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009145 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00009146
Douglas Gregor06a9f362010-05-01 20:49:11 +00009147 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00009148
Pavel Labath66ea35d2013-08-30 08:52:28 +00009149 Expr *FromInst = From.build(S, Loc);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009150 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Douglas Gregora1a04782010-09-09 16:33:13 +00009151 OpEqualRef.takeAs<Expr>(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00009152 Loc, FromInst, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009153 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009154 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00009155
Richard Smith8c889532012-11-14 00:50:40 +00009156 // If we built a call to a trivial 'operator=' while copying an array,
9157 // bail out. We'll replace the whole shebang with a memcpy.
9158 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9159 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009160 return StmtResult((Stmt*)nullptr);
Richard Smith8c889532012-11-14 00:50:40 +00009161
Richard Smith044c8aa2012-11-13 00:54:12 +00009162 // Convert to an expression-statement, and clean up any produced
9163 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00009164 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009165 }
John McCallb0207482010-03-16 06:11:48 +00009166
Richard Smith044c8aa2012-11-13 00:54:12 +00009167 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00009168 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00009169 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009170 if (!ArrayTy) {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009171 ExprResult Assignment = S.CreateBuiltinBinOp(
9172 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009173 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009174 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00009175 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009176 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009177
9178 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00009179 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00009180
Douglas Gregor06a9f362010-05-01 20:49:11 +00009181 // Construct a loop over the array bounds, e.g.,
9182 //
9183 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9184 //
9185 // that will copy each of the array elements.
9186 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00009187
Douglas Gregor06a9f362010-05-01 20:49:11 +00009188 // Create the iteration variable.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009189 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009190 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009191 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009192 llvm::raw_svector_ostream OS(Str);
9193 OS << "__i" << Depth;
9194 IterationVarName = &S.Context.Idents.get(OS.str());
9195 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009196 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009197 IterationVarName, SizeType,
9198 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009199 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00009200
Douglas Gregor06a9f362010-05-01 20:49:11 +00009201 // Initialize the iteration variable to zero.
9202 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009203 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009204
Pavel Labath66ea35d2013-08-30 08:52:28 +00009205 // Creates a reference to the iteration variable.
9206 RefBuilder IterationVarRef(IterationVar, SizeType);
9207 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman8c382062012-01-23 02:35:22 +00009208
Douglas Gregor06a9f362010-05-01 20:49:11 +00009209 // Create the DeclStmt that holds the iteration variable.
9210 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009211
Douglas Gregor06a9f362010-05-01 20:49:11 +00009212 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009213 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9214 MoveCastBuilder FromIndexMove(FromIndexCopy);
9215 const ExprBuilder *FromIndex;
9216 if (Copying)
9217 FromIndex = &FromIndexCopy;
9218 else
9219 FromIndex = &FromIndexMove;
9220
9221 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009222
9223 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00009224 StmtResult Copy =
9225 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00009226 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith8c889532012-11-14 00:50:40 +00009227 Copying, Depth + 1);
9228 // Bail out if copying fails or if we determined that we should use memcpy.
9229 if (Copy.isInvalid() || !Copy.get())
9230 return Copy;
9231
9232 // Create the comparison against the array bound.
9233 llvm::APInt Upper
9234 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9235 Expr *Comparison
Pavel Labath66ea35d2013-08-30 08:52:28 +00009236 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith8c889532012-11-14 00:50:40 +00009237 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9238 BO_NE, S.Context.BoolTy,
9239 VK_RValue, OK_Ordinary, Loc, false);
9240
9241 // Create the pre-increment of the iteration variable.
9242 Expr *Increment
Pavel Labath66ea35d2013-08-30 08:52:28 +00009243 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9244 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009245
Douglas Gregor06a9f362010-05-01 20:49:11 +00009246 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00009247 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009248 S.MakeFullExpr(Comparison),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009249 nullptr, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00009250 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009251}
9252
Richard Smith8c889532012-11-14 00:50:40 +00009253static StmtResult
9254buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009255 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00009256 bool CopyingBaseSubobject, bool Copying) {
9257 // Maybe we should use a memcpy?
9258 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9259 T.isTriviallyCopyableType(S.Context))
9260 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9261
9262 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9263 CopyingBaseSubobject,
9264 Copying, 0));
9265
9266 // If we ended up picking a trivial assignment operator for an array of a
9267 // non-trivially-copyable class type, just emit a memcpy.
9268 if (!Result.isInvalid() && !Result.get())
9269 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9270
9271 return Result;
9272}
9273
Richard Smithb9d0b762012-07-27 04:22:15 +00009274Sema::ImplicitExceptionSpecification
9275Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9276 CXXRecordDecl *ClassDecl = MD->getParent();
9277
9278 ImplicitExceptionSpecification ExceptSpec(*this);
9279 if (ClassDecl->isInvalidDecl())
9280 return ExceptSpec;
9281
9282 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07009283 assert(T->getNumParams() == 1 && "not a copy assignment op");
9284 unsigned ArgQuals =
9285 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithb9d0b762012-07-27 04:22:15 +00009286
Douglas Gregorb87786f2010-07-01 17:48:08 +00009287 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00009288 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00009289 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00009290
9291 // It is unspecified whether or not an implicit copy assignment operator
9292 // attempts to deduplicate calls to assignment operators of virtual bases are
9293 // made. As such, this exception specification is effectively unspecified.
9294 // Based on a similar decision made for constness in C++0x, we're erring on
9295 // the side of assuming such calls to be made regardless of whether they
9296 // actually happen.
Stephen Hines651f13c2014-04-23 16:59:28 -07009297 for (const auto &Base : ClassDecl->bases()) {
9298 if (Base.isVirtual())
Sean Hunt661c67a2011-06-21 23:42:56 +00009299 continue;
9300
Douglas Gregora376d102010-07-02 21:50:04 +00009301 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -07009302 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00009303 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9304 ArgQuals, false, 0))
Stephen Hines651f13c2014-04-23 16:59:28 -07009305 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00009306 }
Sean Hunt661c67a2011-06-21 23:42:56 +00009307
Stephen Hines651f13c2014-04-23 16:59:28 -07009308 for (const auto &Base : ClassDecl->vbases()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00009309 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -07009310 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00009311 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9312 ArgQuals, false, 0))
Stephen Hines651f13c2014-04-23 16:59:28 -07009313 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00009314 }
9315
Stephen Hines651f13c2014-04-23 16:59:28 -07009316 for (const auto *Field : ClassDecl->fields()) {
David Blaikie262bc182012-04-30 02:36:29 +00009317 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00009318 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9319 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009320 LookupCopyingAssignment(FieldClassDecl,
9321 ArgQuals | FieldType.getCVRQualifiers(),
9322 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009323 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00009324 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00009325 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009326
Richard Smithb9d0b762012-07-27 04:22:15 +00009327 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00009328}
9329
9330CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9331 // Note: The following rules are largely analoguous to the copy
9332 // constructor rules. Note that virtual bases are not taken into account
9333 // for determining the argument type of the operator. Note also that
9334 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00009335 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00009336
Richard Smithafb49182012-11-29 01:34:07 +00009337 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9338 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009339 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +00009340
Sean Hunt30de05c2011-05-14 05:23:20 +00009341 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9342 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00009343 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9344 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00009345 ArgType = ArgType.withConst();
9346 ArgType = Context.getLValueReferenceType(ArgType);
9347
Richard Smitha8942d72013-05-07 03:19:20 +00009348 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9349 CXXCopyAssignment,
9350 Const);
9351
Douglas Gregord3c35902010-07-01 16:36:15 +00009352 // An implicitly-declared copy assignment operator is an inline public
9353 // member of its class.
9354 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009355 SourceLocation ClassLoc = ClassDecl->getLocation();
9356 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009357 CXXMethodDecl *CopyAssignment =
9358 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009359 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9360 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00009361 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00009362 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00009363 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00009364
9365 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009366 FunctionProtoType::ExtProtoInfo EPI =
9367 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009368 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009369
Douglas Gregord3c35902010-07-01 16:36:15 +00009370 // Add the parameter to the operator.
9371 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009372 ClassLoc, ClassLoc,
9373 /*Id=*/nullptr, ArgType,
9374 /*TInfo=*/nullptr, SC_None,
9375 nullptr);
David Blaikie4278c652011-09-21 18:16:56 +00009376 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00009377
Richard Smithbc2a35d2012-12-08 08:32:28 +00009378 AddOverriddenMethods(ClassDecl, CopyAssignment);
9379
9380 CopyAssignment->setTrivial(
9381 ClassDecl->needsOverloadResolutionForCopyAssignment()
9382 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9383 : ClassDecl->hasTrivialCopyAssignment());
9384
Richard Smith6c4c36c2012-03-30 20:53:28 +00009385 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009386 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009387
Richard Smithbc2a35d2012-12-08 08:32:28 +00009388 // Note that we have added this copy-assignment operator.
9389 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9390
9391 if (Scope *S = getScopeForContext(ClassDecl))
9392 PushOnScopeChains(CopyAssignment, S, false);
9393 ClassDecl->addDecl(CopyAssignment);
9394
Douglas Gregord3c35902010-07-01 16:36:15 +00009395 return CopyAssignment;
9396}
9397
Richard Smith36155c12013-06-13 03:23:42 +00009398/// Diagnose an implicit copy operation for a class which is odr-used, but
9399/// which is deprecated because the class has a user-declared copy constructor,
9400/// copy assignment operator, or destructor.
9401static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9402 SourceLocation UseLoc) {
9403 assert(CopyOp->isImplicit());
9404
9405 CXXRecordDecl *RD = CopyOp->getParent();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009406 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smith36155c12013-06-13 03:23:42 +00009407
9408 // In Microsoft mode, assignment operations don't affect constructors and
9409 // vice versa.
9410 if (RD->hasUserDeclaredDestructor()) {
9411 UserDeclaredOperation = RD->getDestructor();
9412 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9413 RD->hasUserDeclaredCopyConstructor() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07009414 !S.getLangOpts().MSVCCompat) {
Richard Smith36155c12013-06-13 03:23:42 +00009415 // Find any user-declared copy constructor.
Stephen Hines651f13c2014-04-23 16:59:28 -07009416 for (auto *I : RD->ctors()) {
Richard Smith36155c12013-06-13 03:23:42 +00009417 if (I->isCopyConstructor()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07009418 UserDeclaredOperation = I;
Richard Smith36155c12013-06-13 03:23:42 +00009419 break;
9420 }
9421 }
9422 assert(UserDeclaredOperation);
9423 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9424 RD->hasUserDeclaredCopyAssignment() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07009425 !S.getLangOpts().MSVCCompat) {
Richard Smith36155c12013-06-13 03:23:42 +00009426 // Find any user-declared move assignment operator.
Stephen Hines651f13c2014-04-23 16:59:28 -07009427 for (auto *I : RD->methods()) {
Richard Smith36155c12013-06-13 03:23:42 +00009428 if (I->isCopyAssignmentOperator()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07009429 UserDeclaredOperation = I;
Richard Smith36155c12013-06-13 03:23:42 +00009430 break;
9431 }
9432 }
9433 assert(UserDeclaredOperation);
9434 }
9435
9436 if (UserDeclaredOperation) {
9437 S.Diag(UserDeclaredOperation->getLocation(),
9438 diag::warn_deprecated_copy_operation)
9439 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9440 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9441 S.Diag(UseLoc, diag::note_member_synthesized_at)
9442 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9443 : Sema::CXXCopyAssignment)
9444 << RD;
9445 }
9446}
9447
Douglas Gregor06a9f362010-05-01 20:49:11 +00009448void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9449 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00009450 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009451 CopyAssignOperator->isOverloadedOperator() &&
9452 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009453 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9454 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009455 "DefineImplicitCopyAssignment called for wrong function");
9456
9457 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9458
9459 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9460 CopyAssignOperator->setInvalidDecl();
9461 return;
9462 }
Richard Smith36155c12013-06-13 03:23:42 +00009463
9464 // C++11 [class.copy]p18:
9465 // The [definition of an implicitly declared copy assignment operator] is
9466 // deprecated if the class has a user-declared copy constructor or a
9467 // user-declared destructor.
9468 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9469 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9470
Eli Friedman86164e82013-09-05 00:02:25 +00009471 CopyAssignOperator->markUsed(Context);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009472
Eli Friedman9a14db32012-10-18 20:14:08 +00009473 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009474 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009475
9476 // C++0x [class.copy]p30:
9477 // The implicitly-defined or explicitly-defaulted copy assignment operator
9478 // for a non-union class X performs memberwise copy assignment of its
9479 // subobjects. The direct base classes of X are assigned first, in the
9480 // order of their declaration in the base-specifier-list, and then the
9481 // immediate non-static data members of X are assigned, in the order in
9482 // which they were declared in the class definition.
9483
9484 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009485 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009486
9487 // The parameter for the "other" object, which we are copying from.
9488 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9489 Qualifiers OtherQuals = Other->getType().getQualifiers();
9490 QualType OtherRefType = Other->getType();
9491 if (const LValueReferenceType *OtherRef
9492 = OtherRefType->getAs<LValueReferenceType>()) {
9493 OtherRefType = OtherRef->getPointeeType();
9494 OtherQuals = OtherRefType.getQualifiers();
9495 }
9496
9497 // Our location for everything implicitly-generated.
9498 SourceLocation Loc = CopyAssignOperator->getLocation();
9499
Pavel Labath66ea35d2013-08-30 08:52:28 +00009500 // Builds a DeclRefExpr for the "other" object.
9501 RefBuilder OtherRef(Other, OtherRefType);
9502
9503 // Builds the "this" pointer.
9504 ThisBuilder This;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009505
9506 // Assign base classes.
9507 bool Invalid = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07009508 for (auto &Base : ClassDecl->bases()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009509 // Form the assignment:
9510 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Stephen Hines651f13c2014-04-23 16:59:28 -07009511 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009512 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009513 Invalid = true;
9514 continue;
9515 }
9516
John McCallf871d0c2010-08-07 06:22:56 +00009517 CXXCastPath BasePath;
Stephen Hines651f13c2014-04-23 16:59:28 -07009518 BasePath.push_back(&Base);
John McCallf871d0c2010-08-07 06:22:56 +00009519
Douglas Gregor06a9f362010-05-01 20:49:11 +00009520 // Construct the "from" expression, which is an implicit cast to the
9521 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009522 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9523 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009524
9525 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009526 DerefBuilder DerefThis(This);
9527 CastBuilder To(DerefThis,
9528 Context.getCVRQualifiedType(
9529 BaseType, CopyAssignOperator->getTypeQualifiers()),
9530 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009531
9532 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00009533 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009534 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009535 /*CopyingBaseSubobject=*/true,
9536 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009537 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009538 Diag(CurrentLocation, diag::note_member_synthesized_at)
9539 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9540 CopyAssignOperator->setInvalidDecl();
9541 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009542 }
9543
9544 // Success! Record the copy.
9545 Statements.push_back(Copy.takeAs<Expr>());
9546 }
9547
Douglas Gregor06a9f362010-05-01 20:49:11 +00009548 // Assign non-static members.
Stephen Hines651f13c2014-04-23 16:59:28 -07009549 for (auto *Field : ClassDecl->fields()) {
Douglas Gregord61db332011-10-10 17:22:13 +00009550 if (Field->isUnnamedBitfield())
9551 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00009552
9553 if (Field->isInvalidDecl()) {
9554 Invalid = true;
9555 continue;
9556 }
9557
Douglas Gregor06a9f362010-05-01 20:49:11 +00009558 // Check for members of reference type; we can't copy those.
9559 if (Field->getType()->isReferenceType()) {
9560 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9561 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9562 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009563 Diag(CurrentLocation, diag::note_member_synthesized_at)
9564 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009565 Invalid = true;
9566 continue;
9567 }
9568
9569 // Check for members of const-qualified, non-class type.
9570 QualType BaseType = Context.getBaseElementType(Field->getType());
9571 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9572 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9573 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9574 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009575 Diag(CurrentLocation, diag::note_member_synthesized_at)
9576 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009577 Invalid = true;
9578 continue;
9579 }
John McCallb77115d2011-06-17 00:18:42 +00009580
9581 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009582 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9583 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009584
9585 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009586 if (FieldType->isIncompleteArrayType()) {
9587 assert(ClassDecl->hasFlexibleArrayMember() &&
9588 "Incomplete array type is not valid");
9589 continue;
9590 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009591
9592 // Build references to the field in the object we're copying from and to.
9593 CXXScopeSpec SS; // Intentionally empty
9594 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9595 LookupMemberName);
Stephen Hines651f13c2014-04-23 16:59:28 -07009596 MemberLookup.addDecl(Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009597 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009598
9599 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9600
9601 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009602
Douglas Gregor06a9f362010-05-01 20:49:11 +00009603 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009604 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009605 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009606 /*CopyingBaseSubobject=*/false,
9607 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009608 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009609 Diag(CurrentLocation, diag::note_member_synthesized_at)
9610 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9611 CopyAssignOperator->setInvalidDecl();
9612 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009613 }
9614
9615 // Success! Record the copy.
9616 Statements.push_back(Copy.takeAs<Stmt>());
9617 }
9618
9619 if (!Invalid) {
9620 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009621 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009622
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009623 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009624 if (Return.isInvalid())
9625 Invalid = true;
9626 else {
9627 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009628
9629 if (Trap.hasErrorOccurred()) {
9630 Diag(CurrentLocation, diag::note_member_synthesized_at)
9631 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9632 Invalid = true;
9633 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009634 }
9635 }
9636
9637 if (Invalid) {
9638 CopyAssignOperator->setInvalidDecl();
9639 return;
9640 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009641
9642 StmtResult Body;
9643 {
9644 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009645 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009646 /*isStmtExpr=*/false);
9647 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9648 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009649 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009650
9651 if (ASTMutationListener *L = getASTMutationListener()) {
9652 L->CompletedImplicitDefinition(CopyAssignOperator);
9653 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009654}
9655
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009656Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009657Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9658 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009659
Richard Smithb9d0b762012-07-27 04:22:15 +00009660 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009661 if (ClassDecl->isInvalidDecl())
9662 return ExceptSpec;
9663
9664 // C++0x [except.spec]p14:
9665 // An implicitly declared special member function (Clause 12) shall have an
9666 // exception-specification. [...]
9667
9668 // It is unspecified whether or not an implicit move assignment operator
9669 // attempts to deduplicate calls to assignment operators of virtual bases are
9670 // made. As such, this exception specification is effectively unspecified.
9671 // Based on a similar decision made for constness in C++0x, we're erring on
9672 // the side of assuming such calls to be made regardless of whether they
9673 // actually happen.
9674 // Note that a move constructor is not implicitly declared when there are
9675 // virtual bases, but it can still be user-declared and explicitly defaulted.
Stephen Hines651f13c2014-04-23 16:59:28 -07009676 for (const auto &Base : ClassDecl->bases()) {
9677 if (Base.isVirtual())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009678 continue;
9679
9680 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -07009681 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009682 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009683 0, false, 0))
Stephen Hines651f13c2014-04-23 16:59:28 -07009684 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009685 }
9686
Stephen Hines651f13c2014-04-23 16:59:28 -07009687 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009688 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -07009689 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009690 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009691 0, false, 0))
Stephen Hines651f13c2014-04-23 16:59:28 -07009692 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009693 }
9694
Stephen Hines651f13c2014-04-23 16:59:28 -07009695 for (const auto *Field : ClassDecl->fields()) {
David Blaikie262bc182012-04-30 02:36:29 +00009696 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009697 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009698 if (CXXMethodDecl *MoveAssign =
9699 LookupMovingAssignment(FieldClassDecl,
9700 FieldType.getCVRQualifiers(),
9701 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009702 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009703 }
9704 }
9705
9706 return ExceptSpec;
9707}
9708
9709CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009710 assert(ClassDecl->needsImplicitMoveAssignment());
9711
Richard Smithafb49182012-11-29 01:34:07 +00009712 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9713 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009714 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +00009715
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009716 // Note: The following rules are largely analoguous to the move
9717 // constructor rules.
9718
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009719 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9720 QualType RetType = Context.getLValueReferenceType(ArgType);
9721 ArgType = Context.getRValueReferenceType(ArgType);
9722
Richard Smitha8942d72013-05-07 03:19:20 +00009723 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9724 CXXMoveAssignment,
9725 false);
9726
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009727 // An implicitly-declared move assignment operator is an inline public
9728 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009729 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9730 SourceLocation ClassLoc = ClassDecl->getLocation();
9731 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009732 CXXMethodDecl *MoveAssignment =
9733 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009734 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smitha8942d72013-05-07 03:19:20 +00009735 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009736 MoveAssignment->setAccess(AS_public);
9737 MoveAssignment->setDefaulted();
9738 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009739
Richard Smithb9d0b762012-07-27 04:22:15 +00009740 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009741 FunctionProtoType::ExtProtoInfo EPI =
9742 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009743 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009744
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009745 // Add the parameter to the operator.
9746 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009747 ClassLoc, ClassLoc,
9748 /*Id=*/nullptr, ArgType,
9749 /*TInfo=*/nullptr, SC_None,
9750 nullptr);
David Blaikie4278c652011-09-21 18:16:56 +00009751 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009752
Richard Smithbc2a35d2012-12-08 08:32:28 +00009753 AddOverriddenMethods(ClassDecl, MoveAssignment);
9754
9755 MoveAssignment->setTrivial(
9756 ClassDecl->needsOverloadResolutionForMoveAssignment()
9757 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9758 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009759
Richard Smith7d5088a2012-02-18 02:02:13 +00009760 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith743cbb92013-11-04 01:48:18 +00009761 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9762 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009763 }
9764
Richard Smithbc2a35d2012-12-08 08:32:28 +00009765 // Note that we have added this copy-assignment operator.
9766 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9767
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009768 if (Scope *S = getScopeForContext(ClassDecl))
9769 PushOnScopeChains(MoveAssignment, S, false);
9770 ClassDecl->addDecl(MoveAssignment);
9771
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009772 return MoveAssignment;
9773}
9774
Richard Smith33b1f632013-11-04 04:26:14 +00009775/// Check if we're implicitly defining a move assignment operator for a class
9776/// with virtual bases. Such a move assignment might move-assign the virtual
9777/// base multiple times.
9778static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9779 SourceLocation CurrentLocation) {
9780 assert(!Class->isDependentContext() && "should not define dependent move");
9781
9782 // Only a virtual base could get implicitly move-assigned multiple times.
9783 // Only a non-trivial move assignment can observe this. We only want to
9784 // diagnose if we implicitly define an assignment operator that assigns
9785 // two base classes, both of which move-assign the same virtual base.
9786 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9787 Class->getNumBases() < 2)
9788 return;
9789
9790 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9791 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9792 VBaseMap VBases;
9793
Stephen Hines651f13c2014-04-23 16:59:28 -07009794 for (auto &BI : Class->bases()) {
9795 Worklist.push_back(&BI);
Richard Smith33b1f632013-11-04 04:26:14 +00009796 while (!Worklist.empty()) {
9797 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9798 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9799
9800 // If the base has no non-trivial move assignment operators,
9801 // we don't care about moves from it.
9802 if (!Base->hasNonTrivialMoveAssignment())
9803 continue;
9804
9805 // If there's nothing virtual here, skip it.
9806 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9807 continue;
9808
9809 // If we're not actually going to call a move assignment for this base,
9810 // or the selected move assignment is trivial, skip it.
9811 Sema::SpecialMemberOverloadResult *SMOR =
9812 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9813 /*ConstArg*/false, /*VolatileArg*/false,
9814 /*RValueThis*/true, /*ConstThis*/false,
9815 /*VolatileThis*/false);
9816 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9817 !SMOR->getMethod()->isMoveAssignmentOperator())
9818 continue;
9819
9820 if (BaseSpec->isVirtual()) {
9821 // We're going to move-assign this virtual base, and its move
9822 // assignment operator is not trivial. If this can happen for
9823 // multiple distinct direct bases of Class, diagnose it. (If it
9824 // only happens in one base, we'll diagnose it when synthesizing
9825 // that base class's move assignment operator.)
9826 CXXBaseSpecifier *&Existing =
Stephen Hines651f13c2014-04-23 16:59:28 -07009827 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smith33b1f632013-11-04 04:26:14 +00009828 .first->second;
Stephen Hines651f13c2014-04-23 16:59:28 -07009829 if (Existing && Existing != &BI) {
Richard Smith33b1f632013-11-04 04:26:14 +00009830 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9831 << Class << Base;
9832 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9833 << (Base->getCanonicalDecl() ==
9834 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9835 << Base << Existing->getType() << Existing->getSourceRange();
Stephen Hines651f13c2014-04-23 16:59:28 -07009836 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smith33b1f632013-11-04 04:26:14 +00009837 << (Base->getCanonicalDecl() ==
Stephen Hines651f13c2014-04-23 16:59:28 -07009838 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9839 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smith33b1f632013-11-04 04:26:14 +00009840
9841 // Only diagnose each vbase once.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009842 Existing = nullptr;
Richard Smith33b1f632013-11-04 04:26:14 +00009843 }
9844 } else {
9845 // Only walk over bases that have defaulted move assignment operators.
9846 // We assume that any user-provided move assignment operator handles
9847 // the multiple-moves-of-vbase case itself somehow.
9848 if (!SMOR->getMethod()->isDefaulted())
9849 continue;
9850
9851 // We're going to move the base classes of Base. Add them to the list.
Stephen Hines651f13c2014-04-23 16:59:28 -07009852 for (auto &BI : Base->bases())
9853 Worklist.push_back(&BI);
Richard Smith33b1f632013-11-04 04:26:14 +00009854 }
9855 }
9856 }
9857}
9858
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009859void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9860 CXXMethodDecl *MoveAssignOperator) {
9861 assert((MoveAssignOperator->isDefaulted() &&
9862 MoveAssignOperator->isOverloadedOperator() &&
9863 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009864 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9865 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009866 "DefineImplicitMoveAssignment called for wrong function");
9867
9868 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9869
9870 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9871 MoveAssignOperator->setInvalidDecl();
9872 return;
9873 }
9874
Eli Friedman86164e82013-09-05 00:02:25 +00009875 MoveAssignOperator->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009876
Eli Friedman9a14db32012-10-18 20:14:08 +00009877 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009878 DiagnosticErrorTrap Trap(Diags);
9879
9880 // C++0x [class.copy]p28:
9881 // The implicitly-defined or move assignment operator for a non-union class
9882 // X performs memberwise move assignment of its subobjects. The direct base
9883 // classes of X are assigned first, in the order of their declaration in the
9884 // base-specifier-list, and then the immediate non-static data members of X
9885 // are assigned, in the order in which they were declared in the class
9886 // definition.
9887
Richard Smith33b1f632013-11-04 04:26:14 +00009888 // Issue a warning if our implicit move assignment operator will move
9889 // from a virtual base more than once.
9890 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith743cbb92013-11-04 01:48:18 +00009891
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009892 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009893 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009894
9895 // The parameter for the "other" object, which we are move from.
9896 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9897 QualType OtherRefType = Other->getType()->
9898 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009899 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009900 "Bad argument type of defaulted move assignment");
9901
9902 // Our location for everything implicitly-generated.
9903 SourceLocation Loc = MoveAssignOperator->getLocation();
9904
Pavel Labath66ea35d2013-08-30 08:52:28 +00009905 // Builds a reference to the "other" object.
9906 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009907 // Cast to rvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009908 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009909
Pavel Labath66ea35d2013-08-30 08:52:28 +00009910 // Builds the "this" pointer.
9911 ThisBuilder This;
Richard Smith1c931be2012-04-02 18:40:40 +00009912
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009913 // Assign base classes.
9914 bool Invalid = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07009915 for (auto &Base : ClassDecl->bases()) {
Richard Smith33b1f632013-11-04 04:26:14 +00009916 // C++11 [class.copy]p28:
9917 // It is unspecified whether subobjects representing virtual base classes
9918 // are assigned more than once by the implicitly-defined copy assignment
9919 // operator.
9920 // FIXME: Do not assign to a vbase that will be assigned by some other base
9921 // class. For a move-assignment, this can result in the vbase being moved
9922 // multiple times.
9923
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009924 // Form the assignment:
9925 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Stephen Hines651f13c2014-04-23 16:59:28 -07009926 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009927 if (!BaseType->isRecordType()) {
9928 Invalid = true;
9929 continue;
9930 }
9931
9932 CXXCastPath BasePath;
Stephen Hines651f13c2014-04-23 16:59:28 -07009933 BasePath.push_back(&Base);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009934
9935 // Construct the "from" expression, which is an implicit cast to the
9936 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009937 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009938
9939 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009940 DerefBuilder DerefThis(This);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009941
9942 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009943 CastBuilder To(DerefThis,
9944 Context.getCVRQualifiedType(
9945 BaseType, MoveAssignOperator->getTypeQualifiers()),
9946 VK_LValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009947
9948 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009949 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009950 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009951 /*CopyingBaseSubobject=*/true,
9952 /*Copying=*/false);
9953 if (Move.isInvalid()) {
9954 Diag(CurrentLocation, diag::note_member_synthesized_at)
9955 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9956 MoveAssignOperator->setInvalidDecl();
9957 return;
9958 }
9959
9960 // Success! Record the move.
9961 Statements.push_back(Move.takeAs<Expr>());
9962 }
9963
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009964 // Assign non-static members.
Stephen Hines651f13c2014-04-23 16:59:28 -07009965 for (auto *Field : ClassDecl->fields()) {
Douglas Gregord61db332011-10-10 17:22:13 +00009966 if (Field->isUnnamedBitfield())
9967 continue;
9968
Eli Friedman8150da32013-06-07 01:48:56 +00009969 if (Field->isInvalidDecl()) {
9970 Invalid = true;
9971 continue;
9972 }
9973
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009974 // Check for members of reference type; we can't move those.
9975 if (Field->getType()->isReferenceType()) {
9976 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9977 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9978 Diag(Field->getLocation(), diag::note_declared_at);
9979 Diag(CurrentLocation, diag::note_member_synthesized_at)
9980 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9981 Invalid = true;
9982 continue;
9983 }
9984
9985 // Check for members of const-qualified, non-class type.
9986 QualType BaseType = Context.getBaseElementType(Field->getType());
9987 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9988 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9989 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9990 Diag(Field->getLocation(), diag::note_declared_at);
9991 Diag(CurrentLocation, diag::note_member_synthesized_at)
9992 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9993 Invalid = true;
9994 continue;
9995 }
9996
9997 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009998 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9999 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010000
10001 QualType FieldType = Field->getType().getNonReferenceType();
10002 if (FieldType->isIncompleteArrayType()) {
10003 assert(ClassDecl->hasFlexibleArrayMember() &&
10004 "Incomplete array type is not valid");
10005 continue;
10006 }
10007
10008 // Build references to the field in the object we're copying from and to.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010009 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10010 LookupMemberName);
Stephen Hines651f13c2014-04-23 16:59:28 -070010011 MemberLookup.addDecl(Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010012 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +000010013 MemberBuilder From(MoveOther, OtherRefType,
10014 /*IsArrow=*/false, MemberLookup);
10015 MemberBuilder To(This, getCurrentThisType(),
10016 /*IsArrow=*/true, MemberLookup);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010017
Pavel Labath66ea35d2013-08-30 08:52:28 +000010018 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010019 "Member reference with rvalue base must be rvalue except for reference "
10020 "members, which aren't allowed for move assignment.");
10021
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010022 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +000010023 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +000010024 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010025 /*CopyingBaseSubobject=*/false,
10026 /*Copying=*/false);
10027 if (Move.isInvalid()) {
10028 Diag(CurrentLocation, diag::note_member_synthesized_at)
10029 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10030 MoveAssignOperator->setInvalidDecl();
10031 return;
10032 }
Richard Smithe7ce7092012-11-12 23:33:00 +000010033
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010034 // Success! Record the copy.
10035 Statements.push_back(Move.takeAs<Stmt>());
10036 }
10037
10038 if (!Invalid) {
10039 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +000010040 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010041
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010042 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010043 if (Return.isInvalid())
10044 Invalid = true;
10045 else {
10046 Statements.push_back(Return.takeAs<Stmt>());
10047
10048 if (Trap.hasErrorOccurred()) {
10049 Diag(CurrentLocation, diag::note_member_synthesized_at)
10050 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10051 Invalid = true;
10052 }
10053 }
10054 }
10055
10056 if (Invalid) {
10057 MoveAssignOperator->setInvalidDecl();
10058 return;
10059 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010060
10061 StmtResult Body;
10062 {
10063 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010064 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010065 /*isStmtExpr=*/false);
10066 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10067 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010068 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
10069
10070 if (ASTMutationListener *L = getASTMutationListener()) {
10071 L->CompletedImplicitDefinition(MoveAssignOperator);
10072 }
10073}
10074
Richard Smithb9d0b762012-07-27 04:22:15 +000010075Sema::ImplicitExceptionSpecification
10076Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10077 CXXRecordDecl *ClassDecl = MD->getParent();
10078
10079 ImplicitExceptionSpecification ExceptSpec(*this);
10080 if (ClassDecl->isInvalidDecl())
10081 return ExceptSpec;
10082
10083 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -070010084 assert(T->getNumParams() >= 1 && "not a copy ctor");
10085 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithb9d0b762012-07-27 04:22:15 +000010086
Douglas Gregor0d405db2010-07-01 20:59:04 +000010087 // C++ [except.spec]p14:
10088 // An implicitly declared special member function (Clause 12) shall have an
10089 // exception-specification. [...]
Stephen Hines651f13c2014-04-23 16:59:28 -070010090 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor0d405db2010-07-01 20:59:04 +000010091 // Virtual bases are handled below.
Stephen Hines651f13c2014-04-23 16:59:28 -070010092 if (Base.isVirtual())
Douglas Gregor0d405db2010-07-01 20:59:04 +000010093 continue;
10094
Douglas Gregor22584312010-07-02 23:41:54 +000010095 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -070010096 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +000010097 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +000010098 LookupCopyingConstructor(BaseClassDecl, Quals))
Stephen Hines651f13c2014-04-23 16:59:28 -070010099 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010100 }
Stephen Hines651f13c2014-04-23 16:59:28 -070010101 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregor22584312010-07-02 23:41:54 +000010102 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -070010103 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +000010104 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +000010105 LookupCopyingConstructor(BaseClassDecl, Quals))
Stephen Hines651f13c2014-04-23 16:59:28 -070010106 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010107 }
Stephen Hines651f13c2014-04-23 16:59:28 -070010108 for (const auto *Field : ClassDecl->fields()) {
David Blaikie262bc182012-04-30 02:36:29 +000010109 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +000010110 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10111 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +000010112 LookupCopyingConstructor(FieldClassDecl,
10113 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +000010114 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010115 }
10116 }
Sebastian Redl60618fa2011-03-12 11:50:43 +000010117
Richard Smithb9d0b762012-07-27 04:22:15 +000010118 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +000010119}
10120
10121CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10122 CXXRecordDecl *ClassDecl) {
10123 // C++ [class.copy]p4:
10124 // If the class definition does not explicitly declare a copy
10125 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +000010126 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +000010127
Richard Smithafb49182012-11-29 01:34:07 +000010128 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10129 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010130 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +000010131
Sean Hunt49634cf2011-05-13 06:10:58 +000010132 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10133 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +000010134 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +000010135 if (Const)
10136 ArgType = ArgType.withConst();
10137 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +000010138
Richard Smith7756afa2012-06-10 05:43:50 +000010139 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10140 CXXCopyConstructor,
10141 Const);
10142
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010143 DeclarationName Name
10144 = Context.DeclarationNames.getCXXConstructorName(
10145 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010146 SourceLocation ClassLoc = ClassDecl->getLocation();
10147 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +000010148
10149 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010150 // member of its class.
10151 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010152 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smith61802452011-12-22 02:22:31 +000010153 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010154 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010155 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +000010156 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010157
Richard Smithb9d0b762012-07-27 04:22:15 +000010158 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010159 FunctionProtoType::ExtProtoInfo EPI =
10160 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010161 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010162 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010163
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010164 // Add the parameter to the constructor.
10165 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010166 ClassLoc, ClassLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010167 /*IdentifierInfo=*/nullptr,
10168 ArgType, /*TInfo=*/nullptr,
10169 SC_None, nullptr);
David Blaikie4278c652011-09-21 18:16:56 +000010170 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +000010171
Richard Smithbc2a35d2012-12-08 08:32:28 +000010172 CopyConstructor->setTrivial(
10173 ClassDecl->needsOverloadResolutionForCopyConstructor()
10174 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10175 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +000010176
Richard Smith6c4c36c2012-03-30 20:53:28 +000010177 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +000010178 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +000010179
Richard Smithbc2a35d2012-12-08 08:32:28 +000010180 // Note that we have declared this constructor.
10181 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10182
10183 if (Scope *S = getScopeForContext(ClassDecl))
10184 PushOnScopeChains(CopyConstructor, S, false);
10185 ClassDecl->addDecl(CopyConstructor);
10186
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010187 return CopyConstructor;
10188}
10189
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010190void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +000010191 CXXConstructorDecl *CopyConstructor) {
10192 assert((CopyConstructor->isDefaulted() &&
10193 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010194 !CopyConstructor->doesThisDeclarationHaveABody() &&
10195 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010196 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +000010197
Anders Carlsson63010a72010-04-23 16:24:12 +000010198 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010199 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010200
Richard Smith36155c12013-06-13 03:23:42 +000010201 // C++11 [class.copy]p7:
Benjamin Kramere5753592013-09-09 14:48:42 +000010202 // The [definition of an implicitly declared copy constructor] is
Richard Smith36155c12013-06-13 03:23:42 +000010203 // deprecated if the class has a user-declared copy assignment operator
10204 // or a user-declared destructor.
10205 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10206 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10207
Eli Friedman9a14db32012-10-18 20:14:08 +000010208 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +000010209 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010210
David Blaikie93c86172013-01-17 05:26:25 +000010211 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +000010212 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +000010213 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010214 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +000010215 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010216 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010217 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010218 CopyConstructor->setBody(ActOnCompoundStmt(
10219 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10220 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +000010221 }
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010222
Eli Friedman86164e82013-09-05 00:02:25 +000010223 CopyConstructor->markUsed(Context);
Sebastian Redl58a2cd82011-04-24 16:28:06 +000010224 if (ASTMutationListener *L = getASTMutationListener()) {
10225 L->CompletedImplicitDefinition(CopyConstructor);
10226 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010227}
10228
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010229Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +000010230Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10231 CXXRecordDecl *ClassDecl = MD->getParent();
10232
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010233 // C++ [except.spec]p14:
10234 // An implicitly declared special member function (Clause 12) shall have an
10235 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +000010236 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010237 if (ClassDecl->isInvalidDecl())
10238 return ExceptSpec;
10239
10240 // Direct base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -070010241 for (const auto &B : ClassDecl->bases()) {
10242 if (B.isVirtual()) // Handled below.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010243 continue;
10244
Stephen Hines651f13c2014-04-23 16:59:28 -070010245 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010246 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010247 CXXConstructorDecl *Constructor =
10248 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010249 // If this is a deleted function, add it anyway. This might be conformant
10250 // with the standard. This might not. I'm not sure. It might not matter.
10251 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -070010252 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010253 }
10254 }
10255
10256 // Virtual base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -070010257 for (const auto &B : ClassDecl->vbases()) {
10258 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010259 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010260 CXXConstructorDecl *Constructor =
10261 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010262 // If this is a deleted function, add it anyway. This might be conformant
10263 // with the standard. This might not. I'm not sure. It might not matter.
10264 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -070010265 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010266 }
10267 }
10268
10269 // Field constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -070010270 for (const auto *F : ClassDecl->fields()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +000010271 QualType FieldType = Context.getBaseElementType(F->getType());
10272 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10273 CXXConstructorDecl *Constructor =
10274 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010275 // If this is a deleted function, add it anyway. This might be conformant
10276 // with the standard. This might not. I'm not sure. It might not matter.
10277 // In particular, the problem is that this function never gets called. It
10278 // might just be ill-formed because this function attempts to refer to
10279 // a deleted function here.
10280 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010281 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010282 }
10283 }
10284
10285 return ExceptSpec;
10286}
10287
10288CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10289 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +000010290 assert(ClassDecl->needsImplicitMoveConstructor());
10291
Richard Smithafb49182012-11-29 01:34:07 +000010292 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10293 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010294 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +000010295
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010296 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10297 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010298
Richard Smith7756afa2012-06-10 05:43:50 +000010299 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10300 CXXMoveConstructor,
10301 false);
10302
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010303 DeclarationName Name
10304 = Context.DeclarationNames.getCXXConstructorName(
10305 Context.getCanonicalType(ClassType));
10306 SourceLocation ClassLoc = ClassDecl->getLocation();
10307 DeclarationNameInfo NameInfo(Name, ClassLoc);
10308
Richard Smitha8942d72013-05-07 03:19:20 +000010309 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010310 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010311 // member of its class.
10312 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010313 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smith61802452011-12-22 02:22:31 +000010314 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010315 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010316 MoveConstructor->setAccess(AS_public);
10317 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010318
Richard Smithb9d0b762012-07-27 04:22:15 +000010319 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010320 FunctionProtoType::ExtProtoInfo EPI =
10321 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010322 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010323 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010324
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010325 // Add the parameter to the constructor.
10326 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10327 ClassLoc, ClassLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010328 /*IdentifierInfo=*/nullptr,
10329 ArgType, /*TInfo=*/nullptr,
10330 SC_None, nullptr);
David Blaikie4278c652011-09-21 18:16:56 +000010331 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010332
Richard Smithbc2a35d2012-12-08 08:32:28 +000010333 MoveConstructor->setTrivial(
10334 ClassDecl->needsOverloadResolutionForMoveConstructor()
10335 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10336 : ClassDecl->hasTrivialMoveConstructor());
10337
Sean Hunt769bb2d2011-10-11 06:43:29 +000010338 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith743cbb92013-11-04 01:48:18 +000010339 ClassDecl->setImplicitMoveConstructorIsDeleted();
10340 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010341 }
10342
10343 // Note that we have declared this constructor.
10344 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10345
10346 if (Scope *S = getScopeForContext(ClassDecl))
10347 PushOnScopeChains(MoveConstructor, S, false);
10348 ClassDecl->addDecl(MoveConstructor);
10349
10350 return MoveConstructor;
10351}
10352
10353void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10354 CXXConstructorDecl *MoveConstructor) {
10355 assert((MoveConstructor->isDefaulted() &&
10356 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010357 !MoveConstructor->doesThisDeclarationHaveABody() &&
10358 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010359 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10360
10361 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10362 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10363
Eli Friedman9a14db32012-10-18 20:14:08 +000010364 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010365 DiagnosticErrorTrap Trap(Diags);
10366
David Blaikie93c86172013-01-17 05:26:25 +000010367 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010368 Trap.hasErrorOccurred()) {
10369 Diag(CurrentLocation, diag::note_member_synthesized_at)
10370 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10371 MoveConstructor->setInvalidDecl();
10372 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010373 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010374 MoveConstructor->setBody(ActOnCompoundStmt(
10375 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10376 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010377 }
10378
Eli Friedman86164e82013-09-05 00:02:25 +000010379 MoveConstructor->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010380
10381 if (ASTMutationListener *L = getASTMutationListener()) {
10382 L->CompletedImplicitDefinition(MoveConstructor);
10383 }
10384}
10385
Douglas Gregore4e68d42012-02-15 19:33:52 +000010386bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +000010387 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010388}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010389
10390void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Valid6992ab2013-09-29 08:45:24 +000010391 SourceLocation CurrentLocation,
10392 CXXConversionDecl *Conv) {
10393 CXXRecordDecl *Lambda = Conv->getParent();
10394 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10395 // If we are defining a specialization of a conversion to function-ptr
10396 // cache the deduced template arguments for this specialization
10397 // so that we can use them to retrieve the corresponding call-operator
10398 // and static-invoker.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010399 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10400
Faisal Valid6992ab2013-09-29 08:45:24 +000010401 // Retrieve the corresponding call-operator specialization.
10402 if (Lambda->isGenericLambda()) {
10403 assert(Conv->isFunctionTemplateSpecialization());
10404 FunctionTemplateDecl *CallOpTemplate =
10405 CallOp->getDescribedFunctionTemplate();
10406 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010407 void *InsertPos = nullptr;
Faisal Valid6992ab2013-09-29 08:45:24 +000010408 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10409 DeducedTemplateArgs->data(),
10410 DeducedTemplateArgs->size(),
10411 InsertPos);
10412 assert(CallOpSpec &&
10413 "Conversion operator must have a corresponding call operator");
10414 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10415 }
10416 // Mark the call operator referenced (and add to pending instantiations
10417 // if necessary).
10418 // For both the conversion and static-invoker template specializations
10419 // we construct their body's in this function, so no need to add them
10420 // to the PendingInstantiations.
10421 MarkFunctionReferenced(CurrentLocation, CallOp);
10422
Eli Friedman9a14db32012-10-18 20:14:08 +000010423 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010424 DiagnosticErrorTrap Trap(Diags);
Faisal Valid6992ab2013-09-29 08:45:24 +000010425
Stephen Hines651f13c2014-04-23 16:59:28 -070010426 // Retrieve the static invoker...
Faisal Valid6992ab2013-09-29 08:45:24 +000010427 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10428 // ... and get the corresponding specialization for a generic lambda.
10429 if (Lambda->isGenericLambda()) {
10430 assert(DeducedTemplateArgs &&
10431 "Must have deduced template arguments from Conversion Operator");
10432 FunctionTemplateDecl *InvokeTemplate =
10433 Invoker->getDescribedFunctionTemplate();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010434 void *InsertPos = nullptr;
Faisal Valid6992ab2013-09-29 08:45:24 +000010435 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10436 DeducedTemplateArgs->data(),
10437 DeducedTemplateArgs->size(),
10438 InsertPos);
10439 assert(InvokeSpec &&
10440 "Must have a corresponding static invoker specialization");
10441 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10442 }
10443 // Construct the body of the conversion function { return __invoke; }.
10444 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10445 VK_LValue, Conv->getLocation()).take();
10446 assert(FunctionRef && "Can't refer to __invoke function?");
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010447 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).take();
Faisal Valid6992ab2013-09-29 08:45:24 +000010448 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10449 Conv->getLocation(),
10450 Conv->getLocation()));
10451
10452 Conv->markUsed(Context);
10453 Conv->setReferenced();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010454
Faisal Valid6992ab2013-09-29 08:45:24 +000010455 // Fill in the __invoke function with a dummy implementation. IR generation
10456 // will fill in the actual details.
10457 Invoker->markUsed(Context);
10458 Invoker->setReferenced();
10459 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10460
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010461 if (ASTMutationListener *L = getASTMutationListener()) {
10462 L->CompletedImplicitDefinition(Conv);
Faisal Valid6992ab2013-09-29 08:45:24 +000010463 L->CompletedImplicitDefinition(Invoker);
10464 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010465}
10466
Faisal Valid6992ab2013-09-29 08:45:24 +000010467
10468
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010469void Sema::DefineImplicitLambdaToBlockPointerConversion(
10470 SourceLocation CurrentLocation,
10471 CXXConversionDecl *Conv)
10472{
Faisal Vali56fe35b2013-09-29 17:08:32 +000010473 assert(!Conv->getParent()->isGenericLambda());
Faisal Valid6992ab2013-09-29 08:45:24 +000010474
Eli Friedman86164e82013-09-05 00:02:25 +000010475 Conv->markUsed(Context);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010476
Eli Friedman9a14db32012-10-18 20:14:08 +000010477 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010478 DiagnosticErrorTrap Trap(Diags);
10479
Douglas Gregorac1303e2012-02-22 05:02:47 +000010480 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010481 Expr *This = ActOnCXXThis(CurrentLocation).take();
10482 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010483
Eli Friedman23f02672012-03-01 04:01:32 +000010484 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10485 Conv->getLocation(),
10486 Conv, DerefThis);
10487
10488 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10489 // behavior. Note that only the general conversion function does this
10490 // (since it's unusable otherwise); in the case where we inline the
10491 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010492 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000010493 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10494 CK_CopyAndAutoreleaseBlockObject,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010495 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman23f02672012-03-01 04:01:32 +000010496
10497 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010498 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000010499 Conv->setInvalidDecl();
10500 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010501 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010502
Douglas Gregorac1303e2012-02-22 05:02:47 +000010503 // Create the return statement that returns the block from the conversion
10504 // function.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010505 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010506 if (Return.isInvalid()) {
10507 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10508 Conv->setInvalidDecl();
10509 return;
10510 }
10511
10512 // Set the body of the conversion function.
10513 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010514 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010515 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010516 Conv->getLocation()));
10517
Douglas Gregorac1303e2012-02-22 05:02:47 +000010518 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010519 if (ASTMutationListener *L = getASTMutationListener()) {
10520 L->CompletedImplicitDefinition(Conv);
10521 }
10522}
10523
Douglas Gregorf52757d2012-03-10 06:53:13 +000010524/// \brief Determine whether the given list arguments contains exactly one
10525/// "real" (non-default) argument.
10526static bool hasOneRealArgument(MultiExprArg Args) {
10527 switch (Args.size()) {
10528 case 0:
10529 return false;
10530
10531 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010532 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010533 return false;
10534
10535 // fall through
10536 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010537 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010538 }
10539
10540 return false;
10541}
10542
John McCall60d7b3a2010-08-24 06:29:42 +000010543ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010544Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010545 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010546 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010547 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010548 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010549 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010550 unsigned ConstructKind,
10551 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010552 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010553
Douglas Gregor2f599792010-04-02 18:24:57 +000010554 // C++0x [class.copy]p34:
10555 // When certain criteria are met, an implementation is allowed to
10556 // omit the copy/move construction of a class object, even if the
10557 // copy/move constructor and/or destructor for the object have
10558 // side effects. [...]
10559 // - when a temporary class object that has not been bound to a
10560 // reference (12.2) would be copied/moved to a class object
10561 // with the same cv-unqualified type, the copy/move operation
10562 // can be omitted by constructing the temporary object
10563 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010564 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010565 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010566 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010567 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010568 }
Mike Stump1eb44332009-09-09 15:08:12 +000010569
10570 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010571 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010572 IsListInitialization, RequiresZeroInit,
10573 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010574}
10575
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010576/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10577/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010578ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010579Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10580 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010581 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010582 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010583 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010584 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010585 unsigned ConstructKind,
10586 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010587 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010588 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010589 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010590 HadMultipleCandidates,
10591 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010592 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10593 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010594}
10595
John McCall68c6c9a2010-02-02 09:10:11 +000010596void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010597 if (VD->isInvalidDecl()) return;
10598
John McCall68c6c9a2010-02-02 09:10:11 +000010599 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010600 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010601 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010602 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010603
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010604 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010605 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010606 CheckDestructorAccess(VD->getLocation(), Destructor,
10607 PDiag(diag::err_access_dtor_var)
10608 << VD->getDeclName()
10609 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010610 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010611
Stephen Hines651f13c2014-04-23 16:59:28 -070010612 if (Destructor->isTrivial()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010613 if (!VD->hasGlobalStorage()) return;
10614
10615 // Emit warning for non-trivial dtor in global scope (a real global,
10616 // class-static, function-static).
10617 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10618
10619 // TODO: this should be re-enabled for static locals by !CXAAtExit
10620 if (!VD->isStaticLocal())
10621 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010622}
10623
Douglas Gregor39da0b82009-09-09 23:08:42 +000010624/// \brief Given a constructor and the set of arguments provided for the
10625/// constructor, convert the arguments and add any required default arguments
10626/// to form a proper call to this constructor.
10627///
10628/// \returns true if an error occurred, false otherwise.
10629bool
10630Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10631 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010632 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010633 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010634 bool AllowExplicit,
10635 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010636 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10637 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010638 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010639
10640 const FunctionProtoType *Proto
10641 = Constructor->getType()->getAs<FunctionProtoType>();
10642 assert(Proto && "Constructor without a prototype?");
Stephen Hines651f13c2014-04-23 16:59:28 -070010643 unsigned NumParams = Proto->getNumParams();
10644
Douglas Gregor39da0b82009-09-09 23:08:42 +000010645 // If too few arguments are available, we'll fill in the rest with defaults.
Stephen Hines651f13c2014-04-23 16:59:28 -070010646 if (NumArgs < NumParams)
10647 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010648 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010649 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010650
10651 VariadicCallType CallType =
10652 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010653 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010654 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010655 Proto, 0,
10656 llvm::makeArrayRef(Args, NumArgs),
10657 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010658 CallType, AllowExplicit,
10659 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010660 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010661
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010662 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010663
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010664 CheckConstructorCall(Constructor,
10665 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10666 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010667 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010668
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010669 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010670}
10671
Anders Carlsson20d45d22009-12-12 00:32:00 +000010672static inline bool
10673CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10674 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010675 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010676 if (isa<NamespaceDecl>(DC)) {
10677 return SemaRef.Diag(FnDecl->getLocation(),
10678 diag::err_operator_new_delete_declared_in_namespace)
10679 << FnDecl->getDeclName();
10680 }
10681
10682 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010683 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010684 return SemaRef.Diag(FnDecl->getLocation(),
10685 diag::err_operator_new_delete_declared_static)
10686 << FnDecl->getDeclName();
10687 }
10688
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010689 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010690}
10691
Anders Carlsson156c78e2009-12-13 17:53:43 +000010692static inline bool
10693CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10694 CanQualType ExpectedResultType,
10695 CanQualType ExpectedFirstParamType,
10696 unsigned DependentParamTypeDiag,
10697 unsigned InvalidParamTypeDiag) {
Stephen Hines651f13c2014-04-23 16:59:28 -070010698 QualType ResultType =
10699 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson156c78e2009-12-13 17:53:43 +000010700
10701 // Check that the result type is not dependent.
10702 if (ResultType->isDependentType())
10703 return SemaRef.Diag(FnDecl->getLocation(),
10704 diag::err_operator_new_delete_dependent_result_type)
10705 << FnDecl->getDeclName() << ExpectedResultType;
10706
10707 // Check that the result type is what we expect.
10708 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10709 return SemaRef.Diag(FnDecl->getLocation(),
10710 diag::err_operator_new_delete_invalid_result_type)
10711 << FnDecl->getDeclName() << ExpectedResultType;
10712
10713 // A function template must have at least 2 parameters.
10714 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10715 return SemaRef.Diag(FnDecl->getLocation(),
10716 diag::err_operator_new_delete_template_too_few_parameters)
10717 << FnDecl->getDeclName();
10718
10719 // The function decl must have at least 1 parameter.
10720 if (FnDecl->getNumParams() == 0)
10721 return SemaRef.Diag(FnDecl->getLocation(),
10722 diag::err_operator_new_delete_too_few_parameters)
10723 << FnDecl->getDeclName();
10724
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010725 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010726 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10727 if (FirstParamType->isDependentType())
10728 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10729 << FnDecl->getDeclName() << ExpectedFirstParamType;
10730
10731 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010732 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010733 ExpectedFirstParamType)
10734 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10735 << FnDecl->getDeclName() << ExpectedFirstParamType;
10736
10737 return false;
10738}
10739
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010740static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010741CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010742 // C++ [basic.stc.dynamic.allocation]p1:
10743 // A program is ill-formed if an allocation function is declared in a
10744 // namespace scope other than global scope or declared static in global
10745 // scope.
10746 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10747 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010748
10749 CanQualType SizeTy =
10750 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10751
10752 // C++ [basic.stc.dynamic.allocation]p1:
10753 // The return type shall be void*. The first parameter shall have type
10754 // std::size_t.
10755 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10756 SizeTy,
10757 diag::err_operator_new_dependent_param_type,
10758 diag::err_operator_new_param_type))
10759 return true;
10760
10761 // C++ [basic.stc.dynamic.allocation]p1:
10762 // The first parameter shall not have an associated default argument.
10763 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010764 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010765 diag::err_operator_new_default_arg)
10766 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10767
10768 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010769}
10770
10771static bool
Richard Smith444d3842012-10-20 08:26:51 +000010772CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010773 // C++ [basic.stc.dynamic.deallocation]p1:
10774 // A program is ill-formed if deallocation functions are declared in a
10775 // namespace scope other than global scope or declared static in global
10776 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010777 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10778 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010779
10780 // C++ [basic.stc.dynamic.deallocation]p2:
10781 // Each deallocation function shall return void and its first parameter
10782 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010783 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10784 SemaRef.Context.VoidPtrTy,
10785 diag::err_operator_delete_dependent_param_type,
10786 diag::err_operator_delete_param_type))
10787 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010788
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010789 return false;
10790}
10791
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010792/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10793/// of this overloaded operator is well-formed. If so, returns false;
10794/// otherwise, emits appropriate diagnostics and returns true.
10795bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010796 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010797 "Expected an overloaded operator declaration");
10798
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010799 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10800
Mike Stump1eb44332009-09-09 15:08:12 +000010801 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010802 // The allocation and deallocation functions, operator new,
10803 // operator new[], operator delete and operator delete[], are
10804 // described completely in 3.7.3. The attributes and restrictions
10805 // found in the rest of this subclause do not apply to them unless
10806 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010807 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010808 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010809
Anders Carlssona3ccda52009-12-12 00:26:23 +000010810 if (Op == OO_New || Op == OO_Array_New)
10811 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010812
10813 // C++ [over.oper]p6:
10814 // An operator function shall either be a non-static member
10815 // function or be a non-member function and have at least one
10816 // parameter whose type is a class, a reference to a class, an
10817 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010818 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10819 if (MethodDecl->isStatic())
10820 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010821 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010822 } else {
10823 bool ClassOrEnumParam = false;
Stephen Hines651f13c2014-04-23 16:59:28 -070010824 for (auto Param : FnDecl->params()) {
10825 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010826 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10827 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010828 ClassOrEnumParam = true;
10829 break;
10830 }
10831 }
10832
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010833 if (!ClassOrEnumParam)
10834 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010835 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010836 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010837 }
10838
10839 // C++ [over.oper]p8:
10840 // An operator function cannot have default arguments (8.3.6),
10841 // except where explicitly stated below.
10842 //
Mike Stump1eb44332009-09-09 15:08:12 +000010843 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010844 // (C++ [over.call]p1).
10845 if (Op != OO_Call) {
Stephen Hines651f13c2014-04-23 16:59:28 -070010846 for (auto Param : FnDecl->params()) {
10847 if (Param->hasDefaultArg())
10848 return Diag(Param->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010849 diag::err_operator_overload_default_arg)
Stephen Hines651f13c2014-04-23 16:59:28 -070010850 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010851 }
10852 }
10853
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010854 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10855 { false, false, false }
10856#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10857 , { Unary, Binary, MemberOnly }
10858#include "clang/Basic/OperatorKinds.def"
10859 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010860
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010861 bool CanBeUnaryOperator = OperatorUses[Op][0];
10862 bool CanBeBinaryOperator = OperatorUses[Op][1];
10863 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010864
10865 // C++ [over.oper]p8:
10866 // [...] Operator functions cannot have more or fewer parameters
10867 // than the number required for the corresponding operator, as
10868 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010869 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010870 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010871 if (Op != OO_Call &&
10872 ((NumParams == 1 && !CanBeUnaryOperator) ||
10873 (NumParams == 2 && !CanBeBinaryOperator) ||
10874 (NumParams < 1) || (NumParams > 2))) {
10875 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010876 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010877 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010878 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010879 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010880 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010881 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010882 assert(CanBeBinaryOperator &&
10883 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010884 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010885 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010886
Chris Lattner416e46f2008-11-21 07:57:12 +000010887 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010888 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010889 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010890
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010891 // Overloaded operators other than operator() cannot be variadic.
10892 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010893 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010894 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010895 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010896 }
10897
10898 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010899 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10900 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010901 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010902 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010903 }
10904
10905 // C++ [over.inc]p1:
10906 // The user-defined function called operator++ implements the
10907 // prefix and postfix ++ operator. If this function is a member
10908 // function with no parameters, or a non-member function with one
10909 // parameter of class or enumeration type, it defines the prefix
10910 // increment operator ++ for objects of that type. If the function
10911 // is a member function with one parameter (which shall be of type
10912 // int) or a non-member function with two parameters (the second
10913 // of which shall be of type int), it defines the postfix
10914 // increment operator ++ for objects of that type.
10915 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10916 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Stephen Hines651f13c2014-04-23 16:59:28 -070010917 QualType ParamType = LastParam->getType();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010918
Stephen Hines651f13c2014-04-23 16:59:28 -070010919 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
10920 !ParamType->isDependentType())
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010921 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010922 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010923 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010924 }
10925
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010926 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010927}
Chris Lattner5a003a42008-12-17 07:09:26 +000010928
Sean Hunta6c058d2010-01-13 09:01:02 +000010929/// CheckLiteralOperatorDeclaration - Check whether the declaration
10930/// of this literal operator function is well-formed. If so, returns
10931/// false; otherwise, emits appropriate diagnostics and returns true.
10932bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010933 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010934 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10935 << FnDecl->getDeclName();
10936 return true;
10937 }
10938
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010939 if (FnDecl->isExternC()) {
10940 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10941 return true;
10942 }
10943
Sean Hunta6c058d2010-01-13 09:01:02 +000010944 bool Valid = false;
10945
Richard Smith36f5cfe2012-03-09 08:00:36 +000010946 // This might be the definition of a literal operator template.
10947 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10948 // This might be a specialization of a literal operator template.
10949 if (!TpDecl)
10950 TpDecl = FnDecl->getPrimaryTemplate();
10951
Richard Smithb328e292013-10-07 19:57:58 +000010952 // template <char...> type operator "" name() and
10953 // template <class T, T...> type operator "" name() are the only valid
10954 // template signatures, and the only valid signatures with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010955 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010956 if (FnDecl->param_size() == 0) {
Richard Smithb328e292013-10-07 19:57:58 +000010957 // Must have one or two template parameters
Sean Hunt216c2782010-04-07 23:11:06 +000010958 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10959 if (Params->size() == 1) {
10960 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010961 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010962
Sean Hunt216c2782010-04-07 23:11:06 +000010963 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010964 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10965 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10966 Valid = true;
Richard Smithb328e292013-10-07 19:57:58 +000010967 } else if (Params->size() == 2) {
10968 TemplateTypeParmDecl *PmType =
10969 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10970 NonTypeTemplateParmDecl *PmArgs =
10971 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10972
10973 // The second template parameter must be a parameter pack with the
10974 // first template parameter as its type.
10975 if (PmType && PmArgs &&
10976 !PmType->isTemplateParameterPack() &&
10977 PmArgs->isTemplateParameterPack()) {
10978 const TemplateTypeParmType *TArgs =
10979 PmArgs->getType()->getAs<TemplateTypeParmType>();
10980 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10981 TArgs->getIndex() == PmType->getIndex()) {
10982 Valid = true;
10983 if (ActiveTemplateInstantiations.empty())
10984 Diag(FnDecl->getLocation(),
10985 diag::ext_string_literal_operator_template);
10986 }
10987 }
Sean Hunt216c2782010-04-07 23:11:06 +000010988 }
10989 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010990 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010991 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010992 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10993
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010994 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010995
Sean Hunt30019c02010-04-07 22:57:35 +000010996 // unsigned long long int, long double, and any character type are allowed
10997 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010998 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10999 Context.hasSameType(T, Context.LongDoubleTy) ||
11000 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000011001 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000011002 Context.hasSameType(T, Context.Char16Ty) ||
11003 Context.hasSameType(T, Context.Char32Ty)) {
11004 if (++Param == FnDecl->param_end())
11005 Valid = true;
11006 goto FinishedParams;
11007 }
11008
Sean Hunt30019c02010-04-07 22:57:35 +000011009 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000011010 const PointerType *PT = T->getAs<PointerType>();
11011 if (!PT)
11012 goto FinishedParams;
11013 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000011014 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000011015 goto FinishedParams;
11016 T = T.getUnqualifiedType();
11017
11018 // Move on to the second parameter;
11019 ++Param;
11020
11021 // If there is no second parameter, the first must be a const char *
11022 if (Param == FnDecl->param_end()) {
11023 if (Context.hasSameType(T, Context.CharTy))
11024 Valid = true;
11025 goto FinishedParams;
11026 }
11027
11028 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11029 // are allowed as the first parameter to a two-parameter function
11030 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000011031 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000011032 Context.hasSameType(T, Context.Char16Ty) ||
11033 Context.hasSameType(T, Context.Char32Ty)))
11034 goto FinishedParams;
11035
11036 // The second and final parameter must be an std::size_t
11037 T = (*Param)->getType().getUnqualifiedType();
11038 if (Context.hasSameType(T, Context.getSizeType()) &&
11039 ++Param == FnDecl->param_end())
11040 Valid = true;
11041 }
11042
11043 // FIXME: This diagnostic is absolutely terrible.
11044FinishedParams:
11045 if (!Valid) {
11046 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11047 << FnDecl->getDeclName();
11048 return true;
11049 }
11050
Richard Smitha9e88b22012-03-09 08:16:22 +000011051 // A parameter-declaration-clause containing a default argument is not
11052 // equivalent to any of the permitted forms.
Stephen Hines651f13c2014-04-23 16:59:28 -070011053 for (auto Param : FnDecl->params()) {
11054 if (Param->hasDefaultArg()) {
11055 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smitha9e88b22012-03-09 08:16:22 +000011056 diag::err_literal_operator_default_argument)
Stephen Hines651f13c2014-04-23 16:59:28 -070011057 << Param->getDefaultArgRange();
Richard Smitha9e88b22012-03-09 08:16:22 +000011058 break;
11059 }
11060 }
11061
Richard Smith2fb4ae32012-03-08 02:39:21 +000011062 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000011063 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11064 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000011065 // C++11 [usrlit.suffix]p1:
11066 // Literal suffix identifiers that do not start with an underscore
11067 // are reserved for future standardization.
Richard Smith4ac537b2013-07-23 08:14:48 +000011068 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11069 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor1155c422011-08-30 22:40:35 +000011070 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000011071
Sean Hunta6c058d2010-01-13 09:01:02 +000011072 return false;
11073}
11074
Douglas Gregor074149e2009-01-05 19:45:36 +000011075/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11076/// linkage specification, including the language and (if present)
Stephen Hines651f13c2014-04-23 16:59:28 -070011077/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11078/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor074149e2009-01-05 19:45:36 +000011079/// the '{' brace. Otherwise, this linkage specification does not
11080/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000011081Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Stephen Hines651f13c2014-04-23 16:59:28 -070011082 Expr *LangStr,
Chris Lattner7d642712010-11-09 20:15:55 +000011083 SourceLocation LBraceLoc) {
Stephen Hines651f13c2014-04-23 16:59:28 -070011084 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11085 if (!Lit->isAscii()) {
11086 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11087 << LangStr->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011088 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -070011089 }
11090
11091 StringRef Lang = Lit->getString();
Chris Lattnercc98eac2008-12-17 07:13:27 +000011092 LinkageSpecDecl::LanguageIDs Language;
Stephen Hines651f13c2014-04-23 16:59:28 -070011093 if (Lang == "C")
Chris Lattnercc98eac2008-12-17 07:13:27 +000011094 Language = LinkageSpecDecl::lang_c;
Stephen Hines651f13c2014-04-23 16:59:28 -070011095 else if (Lang == "C++")
Chris Lattnercc98eac2008-12-17 07:13:27 +000011096 Language = LinkageSpecDecl::lang_cxx;
11097 else {
Stephen Hines651f13c2014-04-23 16:59:28 -070011098 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11099 << LangStr->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011100 return nullptr;
Chris Lattnercc98eac2008-12-17 07:13:27 +000011101 }
Mike Stump1eb44332009-09-09 15:08:12 +000011102
Chris Lattnercc98eac2008-12-17 07:13:27 +000011103 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000011104
Stephen Hines651f13c2014-04-23 16:59:28 -070011105 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11106 LangStr->getExprLoc(), Language,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000011107 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011108 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000011109 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000011110 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000011111}
11112
Abramo Bagnara35f9a192010-07-30 16:47:02 +000011113/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000011114/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11115/// valid, it's the position of the closing '}' brace in a linkage
11116/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000011117Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000011118 Decl *LinkageSpec,
11119 SourceLocation RBraceLoc) {
Stephen Hines651f13c2014-04-23 16:59:28 -070011120 if (RBraceLoc.isValid()) {
11121 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11122 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000011123 }
Stephen Hines651f13c2014-04-23 16:59:28 -070011124 PopDeclContext();
Douglas Gregor074149e2009-01-05 19:45:36 +000011125 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000011126}
11127
Michael Han684aa732013-02-22 17:15:32 +000011128Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11129 AttributeList *AttrList,
11130 SourceLocation SemiLoc) {
11131 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11132 // Attribute declarations appertain to empty declaration so we handle
11133 // them here.
11134 if (AttrList)
11135 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000011136
Michael Han684aa732013-02-22 17:15:32 +000011137 CurContext->addDecl(ED);
11138 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000011139}
11140
Douglas Gregord308e622009-05-18 20:51:54 +000011141/// \brief Perform semantic analysis for the variable declaration that
11142/// occurs within a C++ catch clause, returning the newly-created
11143/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011144VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000011145 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011146 SourceLocation StartLoc,
11147 SourceLocation Loc,
11148 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000011149 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000011150 QualType ExDeclType = TInfo->getType();
11151
Sebastian Redl4b07b292008-12-22 19:15:10 +000011152 // Arrays and functions decay.
11153 if (ExDeclType->isArrayType())
11154 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11155 else if (ExDeclType->isFunctionType())
11156 ExDeclType = Context.getPointerType(ExDeclType);
11157
11158 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11159 // The exception-declaration shall not denote a pointer or reference to an
11160 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011161 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000011162 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000011163 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011164 Invalid = true;
11165 }
Douglas Gregord308e622009-05-18 20:51:54 +000011166
Sebastian Redl4b07b292008-12-22 19:15:10 +000011167 QualType BaseType = ExDeclType;
11168 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000011169 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000011170 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011171 BaseType = Ptr->getPointeeType();
11172 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000011173 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000011174 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011175 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011176 BaseType = Ref->getPointeeType();
11177 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000011178 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011179 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011180 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000011181 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000011182 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011183
Mike Stump1eb44332009-09-09 15:08:12 +000011184 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000011185 RequireNonAbstractType(Loc, ExDeclType,
11186 diag::err_abstract_type_in_decl,
11187 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000011188 Invalid = true;
11189
John McCall5a180392010-07-24 00:37:23 +000011190 // Only the non-fragile NeXT runtime currently supports C++ catches
11191 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000011192 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000011193 QualType T = ExDeclType;
11194 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11195 T = RT->getPointeeType();
11196
11197 if (T->isObjCObjectType()) {
11198 Diag(Loc, diag::err_objc_object_catch);
11199 Invalid = true;
11200 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000011201 // FIXME: should this be a test for macosx-fragile specifically?
11202 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000011203 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000011204 }
11205 }
11206
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011207 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000011208 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000011209 ExDecl->setExceptionVariable(true);
11210
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011211 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011212 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011213 Invalid = true;
11214
Douglas Gregorc41b8782011-07-06 18:14:43 +000011215 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000011216 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000011217 // Insulate this from anything else we might currently be parsing.
11218 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11219
Douglas Gregor6d182892010-03-05 23:38:39 +000011220 // C++ [except.handle]p16:
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011221 // The object declared in an exception-declaration or, if the
11222 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6d182892010-03-05 23:38:39 +000011223 // copy-initialized (8.5) from the exception object. [...]
11224 // The object is destroyed when the handler exits, after the destruction
11225 // of any automatic objects initialized within the handler.
11226 //
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011227 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6d182892010-03-05 23:38:39 +000011228 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000011229 QualType initType = ExDeclType;
11230
11231 InitializedEntity entity =
11232 InitializedEntity::InitializeVariable(ExDecl);
11233 InitializationKind initKind =
11234 InitializationKind::CreateCopy(Loc, SourceLocation());
11235
11236 Expr *opaqueValue =
11237 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000011238 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11239 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000011240 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000011241 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000011242 else {
11243 // If the constructor used was non-trivial, set this as the
11244 // "initializer".
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011245 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCalle996ffd2011-02-16 08:02:54 +000011246 if (!construct->getConstructor()->isTrivial()) {
11247 Expr *init = MaybeCreateExprWithCleanups(construct);
11248 ExDecl->setInit(init);
11249 }
11250
11251 // And make sure it's destructable.
11252 FinalizeVarWithDestructor(ExDecl, recordType);
11253 }
Douglas Gregor6d182892010-03-05 23:38:39 +000011254 }
11255 }
11256
Douglas Gregord308e622009-05-18 20:51:54 +000011257 if (Invalid)
11258 ExDecl->setInvalidDecl();
11259
11260 return ExDecl;
11261}
11262
11263/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11264/// handler.
John McCalld226f652010-08-21 09:40:31 +000011265Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000011266 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000011267 bool Invalid = D.isInvalidType();
11268
11269 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000011270 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11271 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000011272 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11273 D.getIdentifierLoc());
11274 Invalid = true;
11275 }
11276
Sebastian Redl4b07b292008-12-22 19:15:10 +000011277 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000011278 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000011279 LookupOrdinaryName,
11280 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011281 // The scope should be freshly made just for us. There is just no way
11282 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000011283 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000011284 if (PrevDecl->isTemplateParameter()) {
11285 // Maybe we will complain about the shadowed template parameter.
11286 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011287 PrevDecl = nullptr;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011288 }
11289 }
11290
Chris Lattnereaaebc72009-04-25 08:06:05 +000011291 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011292 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11293 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000011294 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011295 }
11296
Douglas Gregor83cb9422010-09-09 17:09:21 +000011297 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000011298 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011299 D.getIdentifierLoc(),
11300 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000011301 if (Invalid)
11302 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000011303
Sebastian Redl4b07b292008-12-22 19:15:10 +000011304 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011305 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000011306 PushOnScopeChains(ExDecl, S);
11307 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011308 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000011309
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011310 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000011311 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011312}
Anders Carlssonfb311762009-03-14 00:25:26 +000011313
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011314Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000011315 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000011316 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011317 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000011318 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000011319
Richard Smithe3f470a2012-07-11 22:37:56 +000011320 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011321 return nullptr;
Richard Smithe3f470a2012-07-11 22:37:56 +000011322
11323 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11324 AssertMessage, RParenLoc, false);
11325}
11326
11327Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11328 Expr *AssertExpr,
11329 StringLiteral *AssertMessage,
11330 SourceLocation RParenLoc,
11331 bool Failed) {
11332 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11333 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000011334 // In a static_assert-declaration, the constant-expression shall be a
11335 // constant expression that can be contextually converted to bool.
11336 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11337 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011338 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000011339
Richard Smithdaaefc52011-12-14 23:32:26 +000011340 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000011341 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011342 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000011343 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011344 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000011345
Richard Smithe3f470a2012-07-11 22:37:56 +000011346 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011347 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000011348 llvm::raw_svector_ostream Msg(MsgBuffer);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011349 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011350 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000011351 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000011352 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000011353 }
Anders Carlssonc3082412009-03-14 00:33:21 +000011354 }
Mike Stump1eb44332009-09-09 15:08:12 +000011355
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011356 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000011357 AssertExpr, AssertMessage, RParenLoc,
11358 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000011359
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011360 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000011361 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000011362}
Sebastian Redl50de12f2009-03-24 22:27:57 +000011363
Douglas Gregor1d869352010-04-07 16:53:43 +000011364/// \brief Perform semantic analysis of the given friend type declaration.
11365///
11366/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000011367FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000011368 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011369 TypeSourceInfo *TSInfo) {
11370 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11371
11372 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000011373 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000011374
Richard Smith6b130222011-10-18 21:39:00 +000011375 // C++03 [class.friend]p2:
11376 // An elaborated-type-specifier shall be used in a friend declaration
11377 // for a class.*
11378 //
11379 // * The class-key of the elaborated-type-specifier is required.
11380 if (!ActiveTemplateInstantiations.empty()) {
11381 // Do not complain about the form of friend template types during
11382 // template instantiation; we will already have complained when the
11383 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011384 } else {
11385 if (!T->isElaboratedTypeSpecifier()) {
11386 // If we evaluated the type to a record type, suggest putting
11387 // a tag in front.
11388 if (const RecordType *RT = T->getAs<RecordType>()) {
11389 RecordDecl *RD = RT->getDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011390
11391 SmallString<16> InsertionText(" ");
11392 InsertionText += RD->getKindName();
11393
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011394 Diag(TypeRange.getBegin(),
11395 getLangOpts().CPlusPlus11 ?
11396 diag::warn_cxx98_compat_unelaborated_friend_type :
11397 diag::ext_unelaborated_friend_type)
11398 << (unsigned) RD->getTagKind()
11399 << T
11400 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11401 InsertionText);
11402 } else {
11403 Diag(FriendLoc,
11404 getLangOpts().CPlusPlus11 ?
11405 diag::warn_cxx98_compat_nonclass_type_friend :
11406 diag::ext_nonclass_type_friend)
11407 << T
11408 << TypeRange;
11409 }
11410 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000011411 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000011412 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011413 diag::warn_cxx98_compat_enum_friend :
11414 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000011415 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000011416 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000011417 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011418
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011419 // C++11 [class.friend]p3:
11420 // A friend declaration that does not declare a function shall have one
11421 // of the following forms:
11422 // friend elaborated-type-specifier ;
11423 // friend simple-type-specifier ;
11424 // friend typename-specifier ;
11425 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11426 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11427 }
Richard Smithd6f80da2012-09-20 01:31:00 +000011428
Douglas Gregor06245bf2010-04-07 17:57:12 +000011429 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000011430 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000011431 // the friend declaration is ignored.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011432 return FriendDecl::Create(Context, CurContext,
11433 TSInfo->getTypeLoc().getLocStart(), TSInfo,
11434 FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000011435}
11436
John McCall9a34edb2010-10-19 01:40:49 +000011437/// Handle a friend tag declaration where the scope specifier was
11438/// templated.
11439Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11440 unsigned TagSpec, SourceLocation TagLoc,
11441 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011442 IdentifierInfo *Name,
11443 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000011444 AttributeList *Attr,
11445 MultiTemplateParamsArg TempParamLists) {
11446 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11447
11448 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000011449 bool Invalid = false;
11450
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000011451 if (TemplateParameterList *TemplateParams =
11452 MatchTemplateParametersToScopeSpecifier(
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011453 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000011454 isExplicitSpecialization, Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000011455 if (TemplateParams->size() > 0) {
11456 // This is a declaration of a class template.
11457 if (Invalid)
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011458 return nullptr;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000011459
Eric Christopher4110e132011-07-21 05:34:24 +000011460 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11461 SS, Name, NameLoc, Attr,
11462 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000011463 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000011464 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011465 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000011466 } else {
11467 // The "template<>" header is extraneous.
11468 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11469 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11470 isExplicitSpecialization = true;
11471 }
11472 }
11473
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011474 if (Invalid) return nullptr;
John McCall9a34edb2010-10-19 01:40:49 +000011475
John McCall9a34edb2010-10-19 01:40:49 +000011476 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000011477 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011478 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000011479 isAllExplicitSpecializations = false;
11480 break;
11481 }
11482 }
11483
11484 // FIXME: don't ignore attributes.
11485
11486 // If it's explicit specializations all the way down, just forget
11487 // about the template header and build an appropriate non-templated
11488 // friend. TODO: for source fidelity, remember the headers.
11489 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011490 if (SS.isEmpty()) {
11491 bool Owned = false;
11492 bool IsDependent = false;
11493 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Stephen Hines651f13c2014-04-23 16:59:28 -070011494 Attr, AS_public,
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011495 /*ModulePrivateLoc=*/SourceLocation(),
Stephen Hines651f13c2014-04-23 16:59:28 -070011496 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000011497 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011498 /*ScopedEnumUsesClassTag=*/false,
Stephen Hines651f13c2014-04-23 16:59:28 -070011499 /*UnderlyingType=*/TypeResult(),
11500 /*IsTypeSpecifier=*/false);
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011501 }
Stephen Hines651f13c2014-04-23 16:59:28 -070011502
Douglas Gregor2494dd02011-03-01 01:34:45 +000011503 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000011504 ElaboratedTypeKeyword Keyword
11505 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011506 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000011507 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011508 if (T.isNull())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011509 return nullptr;
John McCall9a34edb2010-10-19 01:40:49 +000011510
11511 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11512 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000011513 DependentNameTypeLoc TL =
11514 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011515 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011516 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011517 TL.setNameLoc(NameLoc);
11518 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000011519 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011520 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000011521 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000011522 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011523 }
11524
11525 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011526 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011527 Friend->setAccess(AS_public);
11528 CurContext->addDecl(Friend);
11529 return Friend;
11530 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011531
11532 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11533
11534
John McCall9a34edb2010-10-19 01:40:49 +000011535
11536 // Handle the case of a templated-scope friend class. e.g.
11537 // template <class T> class A<T>::B;
11538 // FIXME: we don't support these right now.
Richard Smithce6426f2013-11-08 18:59:56 +000011539 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11540 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCall9a34edb2010-10-19 01:40:49 +000011541 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11542 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11543 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011544 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011545 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011546 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011547 TL.setNameLoc(NameLoc);
11548
11549 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011550 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011551 Friend->setAccess(AS_public);
11552 Friend->setUnsupportedFriend(true);
11553 CurContext->addDecl(Friend);
11554 return Friend;
11555}
11556
11557
John McCalldd4a3b02009-09-16 22:47:08 +000011558/// Handle a friend type declaration. This works in tandem with
11559/// ActOnTag.
11560///
11561/// Notes on friend class templates:
11562///
11563/// We generally treat friend class declarations as if they were
11564/// declaring a class. So, for example, the elaborated type specifier
11565/// in a friend declaration is required to obey the restrictions of a
11566/// class-head (i.e. no typedefs in the scope chain), template
11567/// parameters are required to match up with simple template-ids, &c.
11568/// However, unlike when declaring a template specialization, it's
11569/// okay to refer to a template specialization without an empty
11570/// template parameter declaration, e.g.
11571/// friend class A<T>::B<unsigned>;
11572/// We permit this as a special case; if there are any template
11573/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011574/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011575Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011576 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011577 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011578
11579 assert(DS.isFriendSpecified());
11580 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11581
John McCalldd4a3b02009-09-16 22:47:08 +000011582 // Try to convert the decl specifier to a type. This works for
11583 // friend templates because ActOnTag never produces a ClassTemplateDecl
11584 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011585 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011586 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11587 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011588 if (TheDeclarator.isInvalidType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011589 return nullptr;
John McCall67d1a672009-08-06 02:15:43 +000011590
Douglas Gregor6ccab972010-12-16 01:14:37 +000011591 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011592 return nullptr;
Douglas Gregor6ccab972010-12-16 01:14:37 +000011593
John McCalldd4a3b02009-09-16 22:47:08 +000011594 // This is definitely an error in C++98. It's probably meant to
11595 // be forbidden in C++0x, too, but the specification is just
11596 // poorly written.
11597 //
11598 // The problem is with declarations like the following:
11599 // template <T> friend A<T>::foo;
11600 // where deciding whether a class C is a friend or not now hinges
11601 // on whether there exists an instantiation of A that causes
11602 // 'foo' to equal C. There are restrictions on class-heads
11603 // (which we declare (by fiat) elaborated friend declarations to
11604 // be) that makes this tractable.
11605 //
11606 // FIXME: handle "template <> friend class A<T>;", which
11607 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011608 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011609 Diag(Loc, diag::err_tagless_friend_type_template)
11610 << DS.getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011611 return nullptr;
John McCalldd4a3b02009-09-16 22:47:08 +000011612 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011613
John McCall02cace72009-08-28 07:59:38 +000011614 // C++98 [class.friend]p1: A friend of a class is a function
11615 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011616 // This is fixed in DR77, which just barely didn't make the C++03
11617 // deadline. It's also a very silly restriction that seriously
11618 // affects inner classes and which nobody else seems to implement;
11619 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011620 //
11621 // But note that we could warn about it: it's always useless to
11622 // friend one of your own members (it's not, however, worthless to
11623 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011624
John McCalldd4a3b02009-09-16 22:47:08 +000011625 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011626 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011627 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011628 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011629 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011630 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011631 DS.getFriendSpecLoc());
11632 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011633 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011634
11635 if (!D)
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011636 return nullptr;
11637
John McCalldd4a3b02009-09-16 22:47:08 +000011638 D->setAccess(AS_public);
11639 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011640
John McCalld226f652010-08-21 09:40:31 +000011641 return D;
John McCall02cace72009-08-28 07:59:38 +000011642}
11643
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011644NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11645 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011646 const DeclSpec &DS = D.getDeclSpec();
11647
11648 assert(DS.isFriendSpecified());
11649 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11650
11651 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011652 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011653
11654 // C++ [class.friend]p1
11655 // A friend of a class is a function or class....
11656 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011657 // It *doesn't* see through dependent types, which is correct
11658 // according to [temp.arg.type]p3:
11659 // If a declaration acquires a function type through a
11660 // type dependent on a template-parameter and this causes
11661 // a declaration that does not use the syntactic form of a
11662 // function declarator to have a function type, the program
11663 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011664 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011665 Diag(Loc, diag::err_unexpected_friend);
11666
11667 // It might be worthwhile to try to recover by creating an
11668 // appropriate declaration.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011669 return nullptr;
John McCall67d1a672009-08-06 02:15:43 +000011670 }
11671
11672 // C++ [namespace.memdef]p3
11673 // - If a friend declaration in a non-local class first declares a
11674 // class or function, the friend class or function is a member
11675 // of the innermost enclosing namespace.
11676 // - The name of the friend is not found by simple name lookup
11677 // until a matching declaration is provided in that namespace
11678 // scope (either before or after the class declaration granting
11679 // friendship).
11680 // - If a friend function is called, its name may be found by the
11681 // name lookup that considers functions from namespaces and
11682 // classes associated with the types of the function arguments.
11683 // - When looking for a prior declaration of a class or a function
11684 // declared as a friend, scopes outside the innermost enclosing
11685 // namespace scope are not considered.
11686
John McCall337ec3d2010-10-12 23:13:28 +000011687 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011688 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11689 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011690 assert(Name);
11691
Douglas Gregor6ccab972010-12-16 01:14:37 +000011692 // Check for unexpanded parameter packs.
11693 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11694 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11695 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011696 return nullptr;
Douglas Gregor6ccab972010-12-16 01:14:37 +000011697
John McCall67d1a672009-08-06 02:15:43 +000011698 // The context we found the declaration in, or in which we should
11699 // create the declaration.
11700 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011701 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011702 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011703 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011704
Richard Smith4e9686b2013-08-09 04:35:01 +000011705 // There are five cases here.
11706 // - There's no scope specifier and we're in a local class. Only look
11707 // for functions declared in the immediately-enclosing block scope.
11708 // We recover from invalid scope qualifiers as if they just weren't there.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011709 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith4e9686b2013-08-09 04:35:01 +000011710 if ((SS.isInvalid() || !SS.isSet()) &&
11711 (FunctionContainingLocalClass =
11712 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11713 // C++11 [class.friend]p11:
John McCall29ae6e52010-10-13 05:45:15 +000011714 // If a friend declaration appears in a local class and the name
11715 // specified is an unqualified name, a prior declaration is
11716 // looked up without considering scopes that are outside the
11717 // innermost enclosing non-class scope. For a friend function
11718 // declaration, if there is no prior declaration, the program is
11719 // ill-formed.
Richard Smith4e9686b2013-08-09 04:35:01 +000011720
11721 // Find the innermost enclosing non-class scope. This is the block
11722 // scope containing the local class definition (or for a nested class,
11723 // the outer local class).
11724 DCScope = S->getFnParent();
11725
11726 // Look up the function name in the scope.
11727 Previous.clear(LookupLocalFriendName);
11728 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11729
11730 if (!Previous.empty()) {
11731 // All possible previous declarations must have the same context:
11732 // either they were declared at block scope or they are members of
11733 // one of the enclosing local classes.
11734 DC = Previous.getRepresentativeDecl()->getDeclContext();
11735 } else {
11736 // This is ill-formed, but provide the context that we would have
11737 // declared the function in, if we were permitted to, for error recovery.
11738 DC = FunctionContainingLocalClass;
11739 }
Richard Smitha41c97a2013-09-20 01:15:31 +000011740 adjustContextForLocalExternDecl(DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011741
11742 // C++ [class.friend]p6:
11743 // A function can be defined in a friend declaration of a class if and
11744 // only if the class is a non-local class (9.8), the function name is
11745 // unqualified, and the function has namespace scope.
11746 if (D.isFunctionDefinition()) {
11747 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11748 }
11749
11750 // - There's no scope specifier, in which case we just go to the
11751 // appropriate scope and look for a function or function template
11752 // there as appropriate.
11753 } else if (SS.isInvalid() || !SS.isSet()) {
11754 // C++11 [namespace.memdef]p3:
11755 // If the name in a friend declaration is neither qualified nor
11756 // a template-id and the declaration is a function or an
11757 // elaborated-type-specifier, the lookup to determine whether
11758 // the entity has been previously declared shall not consider
11759 // any scopes outside the innermost enclosing namespace.
John McCall8a407372010-10-14 22:22:28 +000011760 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011761
John McCall29ae6e52010-10-13 05:45:15 +000011762 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011763 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011764
Rafael Espindola11dc6342013-04-25 20:12:36 +000011765 // Skip class contexts. If someone can cite chapter and verse
11766 // for this behavior, that would be nice --- it's what GCC and
11767 // EDG do, and it seems like a reasonable intent, but the spec
11768 // really only says that checks for unqualified existing
11769 // declarations should stop at the nearest enclosing namespace,
11770 // not that they should only consider the nearest enclosing
11771 // namespace.
11772 while (DC->isRecord())
11773 DC = DC->getParent();
11774
11775 DeclContext *LookupDC = DC;
11776 while (LookupDC->isTransparentContext())
11777 LookupDC = LookupDC->getParent();
11778
11779 while (true) {
11780 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011781
Rafael Espindola11dc6342013-04-25 20:12:36 +000011782 if (!Previous.empty()) {
11783 DC = LookupDC;
11784 break;
John McCall8a407372010-10-14 22:22:28 +000011785 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011786
11787 if (isTemplateId) {
11788 if (isa<TranslationUnitDecl>(LookupDC)) break;
11789 } else {
11790 if (LookupDC->isFileContext()) break;
11791 }
11792 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011793 }
11794
John McCall380aaa42010-10-13 06:22:15 +000011795 DCScope = getScopeForDeclContext(S, DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011796
John McCall337ec3d2010-10-12 23:13:28 +000011797 // - There's a non-dependent scope specifier, in which case we
11798 // compute it and do a previous lookup there for a function
11799 // or function template.
11800 } else if (!SS.getScopeRep()->isDependent()) {
11801 DC = computeDeclContext(SS);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011802 if (!DC) return nullptr;
John McCall337ec3d2010-10-12 23:13:28 +000011803
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011804 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCall337ec3d2010-10-12 23:13:28 +000011805
11806 LookupQualifiedName(Previous, DC);
11807
11808 // Ignore things found implicitly in the wrong scope.
11809 // TODO: better diagnostics for this case. Suggesting the right
11810 // qualified scope would be nice...
11811 LookupResult::Filter F = Previous.makeFilter();
11812 while (F.hasNext()) {
11813 NamedDecl *D = F.next();
11814 if (!DC->InEnclosingNamespaceSetOf(
11815 D->getDeclContext()->getRedeclContext()))
11816 F.erase();
11817 }
11818 F.done();
11819
11820 if (Previous.empty()) {
11821 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011822 Diag(Loc, diag::err_qualified_friend_not_found)
11823 << Name << TInfo->getType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011824 return nullptr;
John McCall337ec3d2010-10-12 23:13:28 +000011825 }
11826
11827 // C++ [class.friend]p1: A friend of a class is a function or
11828 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011829 if (DC->Equals(CurContext))
11830 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011831 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011832 diag::warn_cxx98_compat_friend_is_member :
11833 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011834
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011835 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011836 // C++ [class.friend]p6:
11837 // A function can be defined in a friend declaration of a class if and
11838 // only if the class is a non-local class (9.8), the function name is
11839 // unqualified, and the function has namespace scope.
11840 SemaDiagnosticBuilder DB
11841 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11842
11843 DB << SS.getScopeRep();
11844 if (DC->isFileContext())
11845 DB << FixItHint::CreateRemoval(SS.getRange());
11846 SS.clear();
11847 }
John McCall337ec3d2010-10-12 23:13:28 +000011848
11849 // - There's a scope specifier that does not match any template
11850 // parameter lists, in which case we use some arbitrary context,
11851 // create a method or method template, and wait for instantiation.
11852 // - There's a scope specifier that does match some template
11853 // parameter lists, which we don't handle right now.
11854 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011855 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011856 // C++ [class.friend]p6:
11857 // A function can be defined in a friend declaration of a class if and
11858 // only if the class is a non-local class (9.8), the function name is
11859 // unqualified, and the function has namespace scope.
11860 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11861 << SS.getScopeRep();
11862 }
11863
John McCall337ec3d2010-10-12 23:13:28 +000011864 DC = CurContext;
11865 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011866 }
Douglas Gregor883af832011-10-10 01:11:59 +000011867
John McCall29ae6e52010-10-13 05:45:15 +000011868 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011869 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011870 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11871 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11872 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011873 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011874 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11875 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011876 return nullptr;
John McCall67d1a672009-08-06 02:15:43 +000011877 }
John McCall67d1a672009-08-06 02:15:43 +000011878 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011879
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011880 // FIXME: This is an egregious hack to cope with cases where the scope stack
11881 // does not contain the declaration context, i.e., in an out-of-line
11882 // definition of a class.
11883 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11884 if (!DCScope) {
11885 FakeDCScope.setEntity(DC);
11886 DCScope = &FakeDCScope;
11887 }
Richard Smith4e9686b2013-08-09 04:35:01 +000011888
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011889 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011890 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011891 TemplateParams, AddToScope);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011892 if (!ND) return nullptr;
John McCallab88d972009-08-31 22:39:49 +000011893
Douglas Gregor182ddf02009-09-28 00:08:27 +000011894 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011895
Richard Smith4e9686b2013-08-09 04:35:01 +000011896 // If we performed typo correction, we might have added a scope specifier
11897 // and changed the decl context.
11898 DC = ND->getDeclContext();
11899
John McCallab88d972009-08-31 22:39:49 +000011900 // Add the function declaration to the appropriate lookup tables,
11901 // adjusting the redeclarations list as necessary. We don't
11902 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011903 //
John McCallab88d972009-08-31 22:39:49 +000011904 // Also update the scope-based lookup if the target context's
11905 // lookup context is in lexical scope.
11906 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011907 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011908 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011909 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011910 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011911 }
John McCall02cace72009-08-28 07:59:38 +000011912
11913 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011914 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011915 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011916 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011917 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011918
John McCall1f2e1a92012-08-10 03:15:35 +000011919 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011920 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011921 } else {
11922 if (DC->isRecord()) CheckFriendAccess(ND);
11923
John McCall6102ca12010-10-16 06:59:13 +000011924 FunctionDecl *FD;
11925 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11926 FD = FTD->getTemplatedDecl();
11927 else
11928 FD = cast<FunctionDecl>(ND);
11929
David Majnemerf6a144f2013-06-25 23:09:30 +000011930 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11931 // default argument expression, that declaration shall be a definition
11932 // and shall be the only declaration of the function or function
11933 // template in the translation unit.
11934 if (functionDeclHasDefaultArgument(FD)) {
11935 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11936 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11937 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11938 } else if (!D.isFunctionDefinition())
11939 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11940 }
11941
John McCall6102ca12010-10-16 06:59:13 +000011942 // Mark templated-scope function declarations as unsupported.
11943 if (FD->getNumTemplateParameterLists())
11944 FrD->setUnsupportedFriend(true);
11945 }
John McCall337ec3d2010-10-12 23:13:28 +000011946
John McCalld226f652010-08-21 09:40:31 +000011947 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011948}
11949
John McCalld226f652010-08-21 09:40:31 +000011950void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11951 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011952
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011953 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011954 if (!Fn) {
11955 Diag(DelLoc, diag::err_deleted_non_function);
11956 return;
11957 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011958
Douglas Gregoref96ee02012-01-14 16:38:05 +000011959 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011960 // Don't consider the implicit declaration we generate for explicit
11961 // specializations. FIXME: Do not generate these implicit declarations.
Stephen Hines651f13c2014-04-23 16:59:28 -070011962 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
11963 Prev->getPreviousDecl()) &&
11964 !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011965 Diag(DelLoc, diag::err_deleted_decl_not_first);
Stephen Hines651f13c2014-04-23 16:59:28 -070011966 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
11967 Prev->isImplicit() ? diag::note_previous_implicit_declaration
11968 : diag::note_previous_declaration);
David Blaikied9cf8262012-06-25 21:55:30 +000011969 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011970 // If the declaration wasn't the first, we delete the function anyway for
11971 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011972 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011973 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011974
11975 if (Fn->isDeleted())
11976 return;
11977
11978 // See if we're deleting a function which is already known to override a
11979 // non-deleted virtual function.
11980 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11981 bool IssuedDiagnostic = false;
11982 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11983 E = MD->end_overridden_methods();
11984 I != E; ++I) {
11985 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11986 if (!IssuedDiagnostic) {
11987 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11988 IssuedDiagnostic = true;
11989 }
11990 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11991 }
11992 }
11993 }
11994
Stephen Hines651f13c2014-04-23 16:59:28 -070011995 // C++11 [basic.start.main]p3:
11996 // A program that defines main as deleted [...] is ill-formed.
11997 if (Fn->isMain())
11998 Diag(DelLoc, diag::err_deleted_main);
11999
Sean Hunt10620eb2011-05-06 20:44:56 +000012000 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000012001}
Sebastian Redl13e88542009-04-27 21:33:24 +000012002
Sean Hunte4246a62011-05-12 06:15:49 +000012003void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000012004 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000012005
12006 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000012007 if (MD->getParent()->isDependentType()) {
12008 MD->setDefaulted();
12009 MD->setExplicitlyDefaulted();
12010 return;
12011 }
12012
Sean Hunte4246a62011-05-12 06:15:49 +000012013 CXXSpecialMember Member = getSpecialMember(MD);
12014 if (Member == CXXInvalid) {
Eli Friedmanfcb5a252013-07-11 23:55:07 +000012015 if (!MD->isInvalidDecl())
12016 Diag(DefaultLoc, diag::err_default_special_members);
Sean Hunte4246a62011-05-12 06:15:49 +000012017 return;
12018 }
12019
12020 MD->setDefaulted();
12021 MD->setExplicitlyDefaulted();
12022
Sean Huntcd10dec2011-05-23 23:14:04 +000012023 // If this definition appears within the record, do the checking when
12024 // the record is complete.
12025 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000012026 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000012027 // Find the uninstantiated declaration that actually had the '= default'
12028 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000012029 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000012030
Richard Smith12fef492013-03-27 00:22:47 +000012031 // If the method was defaulted on its first declaration, we will have
12032 // already performed the checking in CheckCompletedCXXClass. Such a
12033 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000012034 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000012035 return;
12036
Richard Smithb9d0b762012-07-27 04:22:15 +000012037 CheckExplicitlyDefaultedSpecialMember(MD);
12038
Richard Smith1d28caf2012-12-11 01:14:52 +000012039 // The exception specification is needed because we are defining the
12040 // function.
12041 ResolveExceptionSpec(DefaultLoc,
12042 MD->getType()->castAs<FunctionProtoType>());
12043
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012044 if (MD->isInvalidDecl())
12045 return;
12046
Sean Hunte4246a62011-05-12 06:15:49 +000012047 switch (Member) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012048 case CXXDefaultConstructor:
12049 DefineImplicitDefaultConstructor(DefaultLoc,
12050 cast<CXXConstructorDecl>(MD));
Sean Hunt49634cf2011-05-13 06:10:58 +000012051 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012052 case CXXCopyConstructor:
12053 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunte4246a62011-05-12 06:15:49 +000012054 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012055 case CXXCopyAssignment:
12056 DefineImplicitCopyAssignment(DefaultLoc, MD);
Sean Hunt2b188082011-05-14 05:23:28 +000012057 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012058 case CXXDestructor:
12059 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Sean Huntcb45a0f2011-05-12 22:46:25 +000012060 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012061 case CXXMoveConstructor:
12062 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunt82713172011-05-25 23:16:36 +000012063 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012064 case CXXMoveAssignment:
12065 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000012066 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000012067 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000012068 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000012069 }
12070 } else {
12071 Diag(DefaultLoc, diag::err_default_special_members);
12072 }
12073}
12074
Sebastian Redl13e88542009-04-27 21:33:24 +000012075static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000012076 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000012077 Stmt *SubStmt = *CI;
12078 if (!SubStmt)
12079 continue;
12080 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000012081 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000012082 diag::err_return_in_constructor_handler);
12083 if (!isa<Expr>(SubStmt))
12084 SearchForReturnInStmt(Self, SubStmt);
12085 }
12086}
12087
12088void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12089 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12090 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12091 SearchForReturnInStmt(*this, Handler);
12092 }
12093}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012094
David Blaikie299adab2013-01-18 23:03:15 +000012095bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000012096 const CXXMethodDecl *Old) {
12097 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12098 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12099
12100 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12101
12102 // If the calling conventions match, everything is fine
12103 if (NewCC == OldCC)
12104 return false;
12105
Stephen Hines651f13c2014-04-23 16:59:28 -070012106 // If the calling conventions mismatch because the new function is static,
12107 // suppress the calling convention mismatch error; the error about static
12108 // function override (err_static_overrides_virtual from
12109 // Sema::CheckFunctionDeclaration) is more clear.
12110 if (New->getStorageClass() == SC_Static)
12111 return false;
12112
Reid Kleckneref072032013-08-27 23:08:25 +000012113 Diag(New->getLocation(),
12114 diag::err_conflicting_overriding_cc_attributes)
12115 << New->getDeclName() << New->getType() << Old->getType();
12116 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12117 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000012118}
12119
Mike Stump1eb44332009-09-09 15:08:12 +000012120bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012121 const CXXMethodDecl *Old) {
Stephen Hines651f13c2014-04-23 16:59:28 -070012122 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12123 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012124
Chandler Carruth73857792010-02-15 11:53:20 +000012125 if (Context.hasSameType(NewTy, OldTy) ||
12126 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012127 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000012128
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012129 // Check if the return types are covariant
12130 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000012131
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012132 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012133 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12134 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012135 NewClassTy = NewPT->getPointeeType();
12136 OldClassTy = OldPT->getPointeeType();
12137 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012138 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12139 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12140 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12141 NewClassTy = NewRT->getPointeeType();
12142 OldClassTy = OldRT->getPointeeType();
12143 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012144 }
12145 }
Mike Stump1eb44332009-09-09 15:08:12 +000012146
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012147 // The return types aren't either both pointers or references to a class type.
12148 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000012149 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012150 diag::err_different_return_type_for_overriding_virtual_function)
12151 << New->getDeclName() << NewTy << OldTy;
12152 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000012153
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012154 return true;
12155 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012156
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012157 // C++ [class.virtual]p6:
12158 // If the return type of D::f differs from the return type of B::f, the
12159 // class type in the return type of D::f shall be complete at the point of
12160 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000012161 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12162 if (!RT->isBeingDefined() &&
12163 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000012164 diag::err_covariant_return_incomplete,
12165 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012166 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000012167 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012168
Douglas Gregora4923eb2009-11-16 21:35:15 +000012169 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012170 // Check if the new class derives from the old class.
12171 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12172 Diag(New->getLocation(),
12173 diag::err_covariant_return_not_derived)
12174 << New->getDeclName() << NewTy << OldTy;
12175 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12176 return true;
12177 }
Mike Stump1eb44332009-09-09 15:08:12 +000012178
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012179 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000012180 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000012181 diag::err_covariant_return_inaccessible_base,
12182 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12183 // FIXME: Should this point to the return type?
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012184 New->getLocation(), SourceRange(), New->getDeclName(),
12185 nullptr)) {
John McCalleee1d542011-02-14 07:13:47 +000012186 // FIXME: this note won't trigger for delayed access control
12187 // diagnostics, and it's impossible to get an undelayed error
12188 // here from access control during the original parse because
12189 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012190 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12191 return true;
12192 }
12193 }
Mike Stump1eb44332009-09-09 15:08:12 +000012194
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012195 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012196 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012197 Diag(New->getLocation(),
12198 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012199 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012200 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12201 return true;
12202 };
Mike Stump1eb44332009-09-09 15:08:12 +000012203
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012204
12205 // The new class type must have the same or less qualifiers as the old type.
12206 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12207 Diag(New->getLocation(),
12208 diag::err_covariant_return_type_class_type_more_qualified)
12209 << New->getDeclName() << NewTy << OldTy;
12210 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12211 return true;
12212 };
Mike Stump1eb44332009-09-09 15:08:12 +000012213
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012214 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012215}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012216
Douglas Gregor4ba31362009-12-01 17:24:26 +000012217/// \brief Mark the given method pure.
12218///
12219/// \param Method the method to be marked pure.
12220///
12221/// \param InitRange the source range that covers the "0" initializer.
12222bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000012223 SourceLocation EndLoc = InitRange.getEnd();
12224 if (EndLoc.isValid())
12225 Method->setRangeEnd(EndLoc);
12226
Douglas Gregor4ba31362009-12-01 17:24:26 +000012227 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12228 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000012229 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000012230 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000012231
12232 if (!Method->isInvalidDecl())
12233 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12234 << Method->getDeclName() << InitRange;
12235 return true;
12236}
12237
Douglas Gregor552e2992012-02-21 02:22:07 +000012238/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012239static bool isStaticDataMember(const Decl *D) {
12240 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12241 return Var->isStaticDataMember();
12242
12243 return false;
Douglas Gregor552e2992012-02-21 02:22:07 +000012244}
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012245
John McCall731ad842009-12-19 09:28:58 +000012246/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12247/// an initializer for the out-of-line declaration 'Dcl'. The scope
12248/// is a fresh scope pushed for just this purpose.
12249///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012250/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12251/// static data member of class X, names should be looked up in the scope of
12252/// class X.
John McCalld226f652010-08-21 09:40:31 +000012253void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012254 // If there is no declaration, there was an error parsing it.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012255 if (!D || D->isInvalidDecl())
12256 return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012257
Stephen Hines651f13c2014-04-23 16:59:28 -070012258 // We will always have a nested name specifier here, but this declaration
12259 // might not be out of line if the specifier names the current namespace:
12260 // extern int n;
12261 // int ::n = 0;
12262 if (D->isOutOfLine())
12263 EnterDeclaratorContext(S, D->getDeclContext());
12264
Douglas Gregor552e2992012-02-21 02:22:07 +000012265 // If we are parsing the initializer for a static data member, push a
12266 // new expression evaluation context that is associated with this static
12267 // data member.
12268 if (isStaticDataMember(D))
12269 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012270}
12271
12272/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000012273/// initializer for the out-of-line declaration 'D'.
12274void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012275 // If there is no declaration, there was an error parsing it.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012276 if (!D || D->isInvalidDecl())
12277 return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012278
Douglas Gregor552e2992012-02-21 02:22:07 +000012279 if (isStaticDataMember(D))
Stephen Hines651f13c2014-04-23 16:59:28 -070012280 PopExpressionEvaluationContext();
Douglas Gregor552e2992012-02-21 02:22:07 +000012281
Stephen Hines651f13c2014-04-23 16:59:28 -070012282 if (D->isOutOfLine())
12283 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012284}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012285
12286/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12287/// C++ if/switch/while/for statement.
12288/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000012289DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012290 // C++ 6.4p2:
12291 // The declarator shall not specify a function or an array.
12292 // The type-specifier-seq shall not contain typedef and shall not declare a
12293 // new class or enumeration.
12294 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12295 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012296
12297 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000012298 if (!Dcl)
12299 return true;
12300
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012301 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12302 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012303 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000012304 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012305 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012306
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012307 return Dcl;
12308}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012309
Douglas Gregordfe65432011-07-28 19:11:31 +000012310void Sema::LoadExternalVTableUses() {
12311 if (!ExternalSource)
12312 return;
12313
12314 SmallVector<ExternalVTableUse, 4> VTables;
12315 ExternalSource->ReadUsedVTables(VTables);
12316 SmallVector<VTableUse, 4> NewUses;
12317 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12318 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12319 = VTablesUsed.find(VTables[I].Record);
12320 // Even if a definition wasn't required before, it may be required now.
12321 if (Pos != VTablesUsed.end()) {
12322 if (!Pos->second && VTables[I].DefinitionRequired)
12323 Pos->second = true;
12324 continue;
12325 }
12326
12327 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12328 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12329 }
12330
12331 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12332}
12333
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012334void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12335 bool DefinitionRequired) {
12336 // Ignore any vtable uses in unevaluated operands or for classes that do
12337 // not have a vtable.
12338 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000012339 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000012340 return;
12341
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012342 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000012343 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012344 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12345 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12346 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12347 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000012348 // If we already had an entry, check to see if we are promoting this vtable
12349 // to required a definition. If so, we need to reappend to the VTableUses
12350 // list, since we may have already processed the first entry.
12351 if (DefinitionRequired && !Pos.first->second) {
12352 Pos.first->second = true;
12353 } else {
12354 // Otherwise, we can early exit.
12355 return;
12356 }
Stephen Hines651f13c2014-04-23 16:59:28 -070012357 } else {
12358 // The Microsoft ABI requires that we perform the destructor body
12359 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12360 // the deleting destructor is emitted with the vtable, not with the
12361 // destructor definition as in the Itanium ABI.
12362 // If it has a definition, we do the check at that point instead.
12363 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12364 Class->hasUserDeclaredDestructor() &&
12365 !Class->getDestructor()->isDefined() &&
12366 !Class->getDestructor()->isDeleted()) {
12367 CheckDestructor(Class->getDestructor());
12368 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012369 }
12370
12371 // Local classes need to have their virtual members marked
12372 // immediately. For all other classes, we mark their virtual members
12373 // at the end of the translation unit.
12374 if (Class->isLocalClass())
12375 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000012376 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012377 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000012378}
12379
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012380bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000012381 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012382 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000012383 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000012384
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012385 // Note: The VTableUses vector could grow as a result of marking
12386 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000012387 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012388 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000012389 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012390 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000012391 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012392 if (!Class)
12393 continue;
12394
12395 SourceLocation Loc = VTableUses[I].second;
12396
Richard Smithb9d0b762012-07-27 04:22:15 +000012397 bool DefineVTable = true;
12398
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012399 // If this class has a key function, but that key function is
12400 // defined in another translation unit, we don't need to emit the
12401 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000012402 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000012403 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolafc218132013-08-26 23:23:21 +000012404 // The key function is in another translation unit.
12405 DefineVTable = false;
12406 TemplateSpecializationKind TSK =
12407 KeyFunction->getTemplateSpecializationKind();
12408 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12409 TSK != TSK_ImplicitInstantiation &&
12410 "Instantiations don't have key functions");
12411 (void)TSK;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012412 } else if (!KeyFunction) {
12413 // If we have a class with no key function that is the subject
12414 // of an explicit instantiation declaration, suppress the
12415 // vtable; it will live with the explicit instantiation
12416 // definition.
12417 bool IsExplicitInstantiationDeclaration
12418 = Class->getTemplateSpecializationKind()
12419 == TSK_ExplicitInstantiationDeclaration;
Stephen Hines651f13c2014-04-23 16:59:28 -070012420 for (auto R : Class->redecls()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012421 TemplateSpecializationKind TSK
Stephen Hines651f13c2014-04-23 16:59:28 -070012422 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012423 if (TSK == TSK_ExplicitInstantiationDeclaration)
12424 IsExplicitInstantiationDeclaration = true;
12425 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12426 IsExplicitInstantiationDeclaration = false;
12427 break;
12428 }
12429 }
12430
12431 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000012432 DefineVTable = false;
12433 }
12434
12435 // The exception specifications for all virtual members may be needed even
12436 // if we are not providing an authoritative form of the vtable in this TU.
12437 // We may choose to emit it available_externally anyway.
12438 if (!DefineVTable) {
12439 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12440 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012441 }
12442
12443 // Mark all of the virtual members of this class as referenced, so
12444 // that we can build a vtable. Then, tell the AST consumer that a
12445 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000012446 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012447 MarkVirtualMembersReferenced(Loc, Class);
12448 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12449 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12450
12451 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000012452 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012453 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012454 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregora120d012011-09-23 19:04:03 +000012455 if (!KeyFunction ||
12456 (KeyFunction->hasBody(KeyFunctionDef) &&
12457 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000012458 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12459 TSK_ExplicitInstantiationDefinition
12460 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12461 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012462 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012463 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012464 VTableUses.clear();
12465
Douglas Gregor78844032011-04-22 22:25:37 +000012466 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012467}
Anders Carlssond6a637f2009-12-07 08:24:59 +000012468
Richard Smithb9d0b762012-07-27 04:22:15 +000012469void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12470 const CXXRecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -070012471 for (const auto *I : RD->methods())
12472 if (I->isVirtual() && !I->isPure())
12473 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithb9d0b762012-07-27 04:22:15 +000012474}
12475
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012476void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12477 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000012478 // Mark all functions which will appear in RD's vtable as used.
12479 CXXFinalOverriderMap FinalOverriders;
12480 RD->getFinalOverriders(FinalOverriders);
12481 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12482 E = FinalOverriders.end();
12483 I != E; ++I) {
12484 for (OverridingMethods::const_iterator OI = I->second.begin(),
12485 OE = I->second.end();
12486 OI != OE; ++OI) {
12487 assert(OI->second.size() > 0 && "no final overrider");
12488 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000012489
Richard Smithff817f72012-07-07 06:59:51 +000012490 // C++ [basic.def.odr]p2:
12491 // [...] A virtual member function is used if it is not pure. [...]
12492 if (!Overrider->isPure())
12493 MarkFunctionReferenced(Loc, Overrider);
12494 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012495 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012496
12497 // Only classes that have virtual bases need a VTT.
12498 if (RD->getNumVBases() == 0)
12499 return;
12500
Stephen Hines651f13c2014-04-23 16:59:28 -070012501 for (const auto &I : RD->bases()) {
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012502 const CXXRecordDecl *Base =
Stephen Hines651f13c2014-04-23 16:59:28 -070012503 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012504 if (Base->getNumVBases() == 0)
12505 continue;
12506 MarkVirtualMembersReferenced(Loc, Base);
12507 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012508}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012509
12510/// SetIvarInitializers - This routine builds initialization ASTs for the
12511/// Objective-C implementation whose ivars need be initialized.
12512void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012513 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012514 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000012515 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000012516 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012517 CollectIvarsToConstructOrDestruct(OID, ivars);
12518 if (ivars.empty())
12519 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000012520 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012521 for (unsigned i = 0; i < ivars.size(); i++) {
12522 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012523 if (Field->isInvalidDecl())
12524 continue;
12525
Sean Huntcbb67482011-01-08 20:30:50 +000012526 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012527 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12528 InitializationKind InitKind =
12529 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000012530
12531 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12532 ExprResult MemberInit =
12533 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000012534 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012535 // Note, MemberInit could actually come back empty if no initialization
12536 // is required (e.g., because it would call a trivial default constructor)
12537 if (!MemberInit.get() || MemberInit.isInvalid())
12538 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000012539
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012540 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000012541 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12542 SourceLocation(),
12543 MemberInit.takeAs<Expr>(),
12544 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012545 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012546
12547 // Be sure that the destructor is accessible and is marked as referenced.
12548 if (const RecordType *RecordTy
12549 = Context.getBaseElementType(Field->getType())
12550 ->getAs<RecordType>()) {
12551 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012552 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012553 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012554 CheckDestructorAccess(Field->getLocation(), Destructor,
12555 PDiag(diag::err_access_dtor_ivar)
12556 << Context.getBaseElementType(Field->getType()));
12557 }
12558 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012559 }
12560 ObjCImplementation->setIvarInitializers(Context,
12561 AllToInit.data(), AllToInit.size());
12562 }
12563}
Sean Huntfe57eef2011-05-04 05:57:24 +000012564
Sean Huntebcbe1d2011-05-04 23:29:54 +000012565static
12566void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12567 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12568 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12569 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12570 Sema &S) {
Sean Huntebcbe1d2011-05-04 23:29:54 +000012571 if (Ctor->isInvalidDecl())
12572 return;
12573
Richard Smitha8eaf002012-08-23 06:16:52 +000012574 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12575
12576 // Target may not be determinable yet, for instance if this is a dependent
12577 // call in an uninstantiated template.
12578 if (Target) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012579 const FunctionDecl *FNTarget = nullptr;
Richard Smitha8eaf002012-08-23 06:16:52 +000012580 (void)Target->hasBody(FNTarget);
12581 Target = const_cast<CXXConstructorDecl*>(
12582 cast_or_null<CXXConstructorDecl>(FNTarget));
12583 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012584
12585 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12586 // Avoid dereferencing a null pointer here.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012587 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012588
12589 if (!Current.insert(Canonical))
12590 return;
12591
12592 // We know that beyond here, we aren't chaining into a cycle.
12593 if (!Target || !Target->isDelegatingConstructor() ||
12594 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012595 Valid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012596 Current.clear();
12597 // We've hit a cycle.
12598 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12599 Current.count(TCanonical)) {
12600 // If we haven't diagnosed this cycle yet, do so now.
12601 if (!Invalid.count(TCanonical)) {
12602 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012603 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012604 << Ctor;
12605
Richard Smitha8eaf002012-08-23 06:16:52 +000012606 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012607 if (TCanonical != Canonical)
12608 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12609
12610 CXXConstructorDecl *C = Target;
12611 while (C->getCanonicalDecl() != Canonical) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012612 const FunctionDecl *FNTarget = nullptr;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012613 (void)C->getTargetConstructor()->hasBody(FNTarget);
12614 assert(FNTarget && "Ctor cycle through bodiless function");
12615
Richard Smitha8eaf002012-08-23 06:16:52 +000012616 C = const_cast<CXXConstructorDecl*>(
12617 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012618 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12619 }
12620 }
12621
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012622 Invalid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012623 Current.clear();
12624 } else {
12625 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12626 }
12627}
12628
12629
Sean Huntfe57eef2011-05-04 05:57:24 +000012630void Sema::CheckDelegatingCtorCycles() {
12631 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12632
Douglas Gregor0129b562011-07-27 21:57:17 +000012633 for (DelegatingCtorDeclsType::iterator
12634 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012635 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012636 I != E; ++I)
12637 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012638
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012639 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12640 CE = Invalid.end();
12641 CI != CE; ++CI)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012642 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012643}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012644
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012645namespace {
12646 /// \brief AST visitor that finds references to the 'this' expression.
12647 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12648 Sema &S;
12649
12650 public:
12651 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12652
12653 bool VisitCXXThisExpr(CXXThisExpr *E) {
12654 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12655 << E->isImplicit();
12656 return false;
12657 }
12658 };
12659}
12660
12661bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12662 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12663 if (!TSInfo)
12664 return false;
12665
12666 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012667 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012668 if (!ProtoTL)
12669 return false;
12670
12671 // C++11 [expr.prim.general]p3:
12672 // [The expression this] shall not appear before the optional
12673 // cv-qualifier-seq and it shall not appear within the declaration of a
12674 // static member function (although its type and value category are defined
12675 // within a static member function as they are within a non-static member
12676 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012677 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012678 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012679 FindCXXThisExpr Finder(*this);
12680
12681 // If the return type came after the cv-qualifier-seq, check it now.
12682 if (Proto->hasTrailingReturn() &&
Stephen Hines651f13c2014-04-23 16:59:28 -070012683 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012684 return true;
12685
12686 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012687 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12688 return true;
12689
12690 return checkThisInStaticMemberFunctionAttributes(Method);
12691}
12692
12693bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12694 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12695 if (!TSInfo)
12696 return false;
12697
12698 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012699 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012700 if (!ProtoTL)
12701 return false;
12702
David Blaikie39e6ab42013-02-18 22:06:02 +000012703 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012704 FindCXXThisExpr Finder(*this);
12705
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012706 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012707 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012708 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012709 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012710 case EST_DynamicNone:
12711 case EST_MSAny:
12712 case EST_None:
12713 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012714
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012715 case EST_ComputedNoexcept:
12716 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12717 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012718
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012719 case EST_Dynamic:
Stephen Hines651f13c2014-04-23 16:59:28 -070012720 for (const auto &E : Proto->exceptions()) {
12721 if (!Finder.TraverseType(E))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012722 return true;
12723 }
12724 break;
12725 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012726
12727 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012728}
12729
12730bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12731 FindCXXThisExpr Finder(*this);
12732
12733 // Check attributes.
Stephen Hines651f13c2014-04-23 16:59:28 -070012734 for (const auto *A : Method->attrs()) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012735 // FIXME: This should be emitted by tblgen.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012736 Expr *Arg = nullptr;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012737 ArrayRef<Expr *> Args;
Stephen Hines651f13c2014-04-23 16:59:28 -070012738 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012739 Arg = G->getArg();
Stephen Hines651f13c2014-04-23 16:59:28 -070012740 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012741 Arg = G->getArg();
Stephen Hines651f13c2014-04-23 16:59:28 -070012742 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012743 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070012744 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012745 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070012746 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012747 Arg = ETLF->getSuccessValue();
12748 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070012749 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012750 Arg = STLF->getSuccessValue();
12751 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070012752 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012753 Arg = LR->getArg();
Stephen Hines651f13c2014-04-23 16:59:28 -070012754 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012755 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070012756 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
12757 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
12758 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
12759 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12760 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12761 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12762 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
12763 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012764
12765 if (Arg && !Finder.TraverseStmt(Arg))
12766 return true;
12767
12768 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12769 if (!Finder.TraverseStmt(Args[I]))
12770 return true;
12771 }
12772 }
12773
12774 return false;
12775}
12776
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012777void
12778Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12779 ArrayRef<ParsedType> DynamicExceptions,
12780 ArrayRef<SourceRange> DynamicExceptionRanges,
12781 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012782 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012783 FunctionProtoType::ExtProtoInfo &EPI) {
12784 Exceptions.clear();
12785 EPI.ExceptionSpecType = EST;
12786 if (EST == EST_Dynamic) {
12787 Exceptions.reserve(DynamicExceptions.size());
12788 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12789 // FIXME: Preserve type source info.
12790 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12791
12792 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12793 collectUnexpandedParameterPacks(ET, Unexpanded);
12794 if (!Unexpanded.empty()) {
12795 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12796 UPPC_ExceptionType,
12797 Unexpanded);
12798 continue;
12799 }
12800
12801 // Check that the type is valid for an exception spec, and
12802 // drop it if not.
12803 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12804 Exceptions.push_back(ET);
12805 }
12806 EPI.NumExceptions = Exceptions.size();
12807 EPI.Exceptions = Exceptions.data();
12808 return;
12809 }
12810
12811 if (EST == EST_ComputedNoexcept) {
12812 // If an error occurred, there's no expression here.
12813 if (NoexceptExpr) {
12814 assert((NoexceptExpr->isTypeDependent() ||
12815 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12816 Context.BoolTy) &&
12817 "Parser should have made sure that the expression is boolean");
12818 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12819 EPI.ExceptionSpecType = EST_BasicNoexcept;
12820 return;
12821 }
12822
12823 if (!NoexceptExpr->isValueDependent())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012824 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012825 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012826 /*AllowFold*/ false).take();
12827 EPI.NoexceptExpr = NoexceptExpr;
12828 }
12829 return;
12830 }
12831}
12832
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012833/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12834Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12835 // Implicitly declared functions (e.g. copy constructors) are
12836 // __host__ __device__
12837 if (D->isImplicit())
12838 return CFT_HostDevice;
12839
12840 if (D->hasAttr<CUDAGlobalAttr>())
12841 return CFT_Global;
12842
12843 if (D->hasAttr<CUDADeviceAttr>()) {
12844 if (D->hasAttr<CUDAHostAttr>())
12845 return CFT_HostDevice;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012846 return CFT_Device;
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012847 }
12848
12849 return CFT_Host;
12850}
12851
12852bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12853 CUDAFunctionTarget CalleeTarget) {
12854 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12855 // Callable from the device only."
12856 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12857 return true;
12858
12859 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12860 // Callable from the host only."
12861 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12862 // Callable from the host only."
12863 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12864 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12865 return true;
12866
12867 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12868 return true;
12869
12870 return false;
12871}
John McCall76da55d2013-04-16 07:28:30 +000012872
12873/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12874///
12875MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12876 SourceLocation DeclStart,
12877 Declarator &D, Expr *BitWidth,
12878 InClassInitStyle InitStyle,
12879 AccessSpecifier AS,
12880 AttributeList *MSPropertyAttr) {
12881 IdentifierInfo *II = D.getIdentifier();
12882 if (!II) {
12883 Diag(DeclStart, diag::err_anonymous_property);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012884 return nullptr;
John McCall76da55d2013-04-16 07:28:30 +000012885 }
12886 SourceLocation Loc = D.getIdentifierLoc();
12887
12888 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12889 QualType T = TInfo->getType();
12890 if (getLangOpts().CPlusPlus) {
12891 CheckExtraCXXDefaultArguments(D);
12892
12893 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12894 UPPC_DataMemberType)) {
12895 D.setInvalidType();
12896 T = Context.IntTy;
12897 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12898 }
12899 }
12900
12901 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12902
12903 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12904 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12905 diag::err_invalid_thread)
12906 << DeclSpec::getSpecifierName(TSCS);
12907
12908 // Check to see if this name was declared as a member previously
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012909 NamedDecl *PrevDecl = nullptr;
John McCall76da55d2013-04-16 07:28:30 +000012910 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12911 LookupName(Previous, S);
12912 switch (Previous.getResultKind()) {
12913 case LookupResult::Found:
12914 case LookupResult::FoundUnresolvedValue:
12915 PrevDecl = Previous.getAsSingle<NamedDecl>();
12916 break;
12917
12918 case LookupResult::FoundOverloaded:
12919 PrevDecl = Previous.getRepresentativeDecl();
12920 break;
12921
12922 case LookupResult::NotFound:
12923 case LookupResult::NotFoundInCurrentInstantiation:
12924 case LookupResult::Ambiguous:
12925 break;
12926 }
12927
12928 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12929 // Maybe we will complain about the shadowed template parameter.
12930 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12931 // Just pretend that we didn't see the previous declaration.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012932 PrevDecl = nullptr;
John McCall76da55d2013-04-16 07:28:30 +000012933 }
12934
12935 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012936 PrevDecl = nullptr;
John McCall76da55d2013-04-16 07:28:30 +000012937
12938 SourceLocation TSSL = D.getLocStart();
John McCall76da55d2013-04-16 07:28:30 +000012939 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Stephen Hines651f13c2014-04-23 16:59:28 -070012940 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
12941 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall76da55d2013-04-16 07:28:30 +000012942 ProcessDeclAttributes(TUScope, NewPD, D);
12943 NewPD->setAccess(AS);
12944
12945 if (NewPD->isInvalidDecl())
12946 Record->setInvalidDecl();
12947
12948 if (D.getDeclSpec().isModulePrivateSpecified())
12949 NewPD->setModulePrivate();
12950
12951 if (NewPD->isInvalidDecl() && PrevDecl) {
12952 // Don't introduce NewFD into scope; there's already something
12953 // with the same name in the same scope.
12954 } else if (II) {
12955 PushOnScopeChains(NewPD, S);
12956 } else
12957 Record->addDecl(NewPD);
12958
12959 return NewPD;
12960}