blob: 850db26e9afa02efdc682547856029bef2f1ac55 [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"
Anders Carlsson8211eff2009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000028#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000029#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000030#include "clang/Basic/TargetInfo.h"
Richard Smith4ac537b2013-07-23 08:14:48 +000031#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000032#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000033#include "clang/Sema/CXXFieldCollector.h"
34#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Initialization.h"
36#include "clang/Sema/Lookup.h"
37#include "clang/Sema/ParsedTemplate.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000041#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000042#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000043#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000044
45using namespace clang;
46
Chris Lattner8123a952008-04-10 02:22:51 +000047//===----------------------------------------------------------------------===//
48// CheckDefaultArgumentVisitor
49//===----------------------------------------------------------------------===//
50
Chris Lattner9e979552008-04-12 23:52:44 +000051namespace {
52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53 /// the default argument of a parameter to determine whether it
54 /// contains any ill-formed subexpressions. For example, this will
55 /// diagnose the use of local variables or parameters within the
56 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000057 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000058 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000059 Expr *DefaultArg;
60 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000061
Chris Lattner9e979552008-04-12 23:52:44 +000062 public:
Mike Stump1eb44332009-09-09 15:08:12 +000063 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000064 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000065
Chris Lattner9e979552008-04-12 23:52:44 +000066 bool VisitExpr(Expr *Node);
67 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000068 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000069 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000070 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000071 };
Chris Lattner8123a952008-04-10 02:22:51 +000072
Chris Lattner9e979552008-04-12 23:52:44 +000073 /// VisitExpr - Visit all of the children of this expression.
74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000076 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000077 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000078 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000079 }
80
Chris Lattner9e979552008-04-12 23:52:44 +000081 /// VisitDeclRefExpr - Visit a reference to a declaration, to
82 /// determine whether this declaration can be used in the default
83 /// argument expression.
84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000085 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000086 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87 // C++ [dcl.fct.default]p9
88 // Default arguments are evaluated each time the function is
89 // called. The order of evaluation of function arguments is
90 // unspecified. Consequently, parameters of a function shall not
91 // be used in default argument expressions, even if they are not
92 // evaluated. Parameters of a function declared before a default
93 // argument expression are in scope and can hide namespace and
94 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000095 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000097 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000098 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000099 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
101 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000102 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000103 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000106 }
Chris Lattner8123a952008-04-10 02:22:51 +0000107
Douglas Gregor3996f232008-11-04 13:41:56 +0000108 return false;
109 }
Chris Lattner9e979552008-04-12 23:52:44 +0000110
Douglas Gregor796da182008-11-04 14:32:21 +0000111 /// VisitCXXThisExpr - Visit a C++ "this" expression.
112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113 // C++ [dcl.fct.default]p8:
114 // The keyword this shall not be used in a default argument of a
115 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000116 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000119 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000120
John McCall045d2522013-04-09 01:56:28 +0000121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122 bool Invalid = false;
123 for (PseudoObjectExpr::semantics_iterator
124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125 Expr *E = *i;
126
127 // Look through bindings.
128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129 E = OVE->getSourceExpr();
130 assert(E && "pseudo-object binding without source expression?");
131 }
132
133 Invalid |= Visit(E);
134 }
135 return Invalid;
136 }
137
Douglas Gregorf0459f82012-02-10 23:30:22 +0000138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139 // C++11 [expr.lambda.prim]p13:
140 // A lambda-expression appearing in a default argument shall not
141 // implicitly or explicitly capture any entity.
142 if (Lambda->capture_begin() == Lambda->capture_end())
143 return false;
144
145 return S->Diag(Lambda->getLocStart(),
146 diag::err_lambda_capture_default_arg);
147 }
Chris Lattner8123a952008-04-10 02:22:51 +0000148}
149
Richard Smith0b0ca472013-04-10 06:11:48 +0000150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000162
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
165 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000166 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000167 ClearExceptions();
168 ComputedEST = EST;
169 return;
170 }
171
Richard Smith7a614d82011-06-11 17:19:42 +0000172 // FIXME: If the call to this decl is using any of its default arguments, we
173 // need to search them for potentially-throwing calls.
174
Sean Hunt001cad92011-05-10 00:49:42 +0000175 // If this function has a basic noexcept, it doesn't affect the outcome.
176 if (EST == EST_BasicNoexcept)
177 return;
178
179 // If we have a throw-all spec at this point, ignore the function.
180 if (ComputedEST == EST_None)
181 return;
182
183 // If we're still at noexcept(true) and there's a nothrow() callee,
184 // change to that specification.
185 if (EST == EST_DynamicNone) {
186 if (ComputedEST == EST_BasicNoexcept)
187 ComputedEST = EST_DynamicNone;
188 return;
189 }
190
191 // Check out noexcept specs.
192 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000193 FunctionProtoType::NoexceptResult NR =
194 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000195 assert(NR != FunctionProtoType::NR_NoNoexcept &&
196 "Must have noexcept result for EST_ComputedNoexcept.");
197 assert(NR != FunctionProtoType::NR_Dependent &&
198 "Should not generate implicit declarations for dependent cases, "
199 "and don't know how to handle them anyway.");
200
201 // noexcept(false) -> no spec on the new function
202 if (NR == FunctionProtoType::NR_Throw) {
203 ClearExceptions();
204 ComputedEST = EST_None;
205 }
206 // noexcept(true) won't change anything either.
207 return;
208 }
209
210 assert(EST == EST_Dynamic && "EST case not considered earlier.");
211 assert(ComputedEST != EST_None &&
212 "Shouldn't collect exceptions when throw-all is guaranteed.");
213 ComputedEST = EST_Dynamic;
214 // Record the exceptions in this function's exception specification.
Stephen Hines651f13c2014-04-23 16:59:28 -0700215 for (const auto &E : Proto->exceptions())
216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)))
217 Exceptions.push_back(E);
Sean Hunt001cad92011-05-10 00:49:42 +0000218}
219
Richard Smith7a614d82011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithe6975e92012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssoned961f92009-08-25 02:29:20 +0000249bool
John McCall9ae2f072010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000271 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000273
Richard Smith6c3af3d2013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Anders Carlssoned961f92009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson9351c172009-08-25 03:18:48 +0000292 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000293}
294
Chris Lattner8123a952008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000298void
John McCalld226f652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000302 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCalld226f652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner3d1cee32008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6f526752010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlsson66e30672009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
John McCall9ae2f072010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000329}
330
Douglas Gregor61366e92008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCalld226f652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +0000342 Param->setUnparsedDefaultArg();
Anders Carlsson5e300d12009-06-12 16:51:40 +0000343 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000344}
345
Douglas Gregor72b505b2008-12-16 21:30:33 +0000346/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
347/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000348void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000349 if (!param)
350 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000351
John McCalld226f652010-08-21 09:40:31 +0000352 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000353 Param->setInvalidDecl();
Anders Carlsson5e300d12009-06-12 16:51:40 +0000354 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000355}
356
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000357/// CheckExtraCXXDefaultArguments - Check for any extra default
358/// arguments in the declarator, which is not a function declaration
359/// or definition and therefore is not permitted to have default
360/// arguments. This routine should be invoked for every declarator
361/// that is not a function declaration or definition.
362void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
363 // C++ [dcl.fct.default]p3
364 // A default argument expression shall be specified only in the
365 // parameter-declaration-clause of a function declaration or in a
366 // template-parameter (14.1). It shall not be specified for a
367 // parameter pack. If it is specified in a
368 // parameter-declaration-clause, it shall not occur within a
369 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000370 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000371 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000372 DeclaratorChunk &chunk = D.getTypeObject(i);
373 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000374 if (MightBeFunction) {
375 // This is a function declaration. It can have default arguments, but
376 // keep looking in case its return type is a function type with default
377 // arguments.
378 MightBeFunction = false;
379 continue;
380 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700381 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
382 ++argIdx) {
383 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000384 if (Param->hasUnparsedDefaultArg()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700385 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000386 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000387 << SourceRange((*Toks)[1].getLocation(),
388 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000389 delete Toks;
Stephen Hines651f13c2014-04-23 16:59:28 -0700390 chunk.Fun.Params[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000391 } else if (Param->getDefaultArg()) {
392 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
393 << Param->getDefaultArg()->getSourceRange();
394 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000395 }
396 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000397 } else if (chunk.Kind != DeclaratorChunk::Paren) {
398 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000399 }
400 }
401}
402
David Majnemerf6a144f2013-06-25 23:09:30 +0000403static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
404 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
405 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
406 if (!PVD->hasDefaultArg())
407 return false;
408 if (!PVD->hasInheritedDefaultArg())
409 return true;
410 }
411 return false;
412}
413
Craig Topper1a6eac82012-09-21 04:33:26 +0000414/// MergeCXXFunctionDecl - Merge two declarations of the same C++
415/// function, once we already know that they have the same
416/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
417/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000418bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
419 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000420 bool Invalid = false;
421
Chris Lattner3d1cee32008-04-08 05:04:30 +0000422 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000423 // For non-template functions, default arguments can be added in
424 // later declarations of a function in the same
425 // scope. Declarations in different scopes have completely
426 // distinct sets of default arguments. That is, declarations in
427 // inner scopes do not acquire default arguments from
428 // declarations in outer scopes, and vice versa. In a given
429 // function declaration, all parameters subsequent to a
430 // parameter with a default argument shall have default
431 // arguments supplied in this or previous declarations. A
432 // default argument shall not be redefined by a later
433 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000434 //
435 // C++ [dcl.fct.default]p6:
Richard Smitha41c97a2013-09-20 01:15:31 +0000436 // Except for member functions of class templates, the default arguments
437 // in a member function definition that appears outside of the class
438 // definition are added to the set of default arguments provided by the
Douglas Gregor6cc15182009-09-11 18:44:32 +0000439 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000440 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
441 ParmVarDecl *OldParam = Old->getParamDecl(p);
442 ParmVarDecl *NewParam = New->getParamDecl(p);
443
James Molloy9cda03f2012-03-13 08:55:35 +0000444 bool OldParamHasDfl = OldParam->hasDefaultArg();
445 bool NewParamHasDfl = NewParam->hasDefaultArg();
446
447 NamedDecl *ND = Old;
Richard Smitha41c97a2013-09-20 01:15:31 +0000448
449 // The declaration context corresponding to the scope is the semantic
450 // parent, unless this is a local function declaration, in which case
451 // it is that surrounding function.
452 DeclContext *ScopeDC = New->getLexicalDeclContext();
453 if (!ScopeDC->isFunctionOrMethod())
454 ScopeDC = New->getDeclContext();
455 if (S && !isDeclInScope(ND, ScopeDC, S) &&
456 !New->getDeclContext()->isRecord())
James Molloy9cda03f2012-03-13 08:55:35 +0000457 // Ignore default parameters of old decl if they are not in
Richard Smitha41c97a2013-09-20 01:15:31 +0000458 // the same scope and this is not an out-of-line definition of
459 // a member function.
James Molloy9cda03f2012-03-13 08:55:35 +0000460 OldParamHasDfl = false;
461
462 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000463
Francois Pichet8d051e02011-04-10 03:03:52 +0000464 unsigned DiagDefaultParamID =
465 diag::err_param_default_argument_redefinition;
466
467 // MSVC accepts that default parameters be redefined for member functions
468 // of template class. The new default parameter's value is ignored.
469 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000470 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000471 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
472 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000473 // Merge the old default argument into the new parameter.
474 NewParam->setHasInheritedDefaultArg();
475 if (OldParam->hasUninstantiatedDefaultArg())
476 NewParam->setUninstantiatedDefaultArg(
477 OldParam->getUninstantiatedDefaultArg());
478 else
479 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000480 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000481 Invalid = false;
482 }
483 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000484
Francois Pichet8cf90492011-04-10 04:58:30 +0000485 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
486 // hint here. Alternatively, we could walk the type-source information
487 // for NewParam to find the last source location in the type... but it
488 // isn't worth the effort right now. This is the kind of test case that
489 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000490 // int f(int);
491 // void g(int (*fp)(int) = f);
492 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000493 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000494 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000495
496 // Look for the function declaration where the default argument was
497 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000498 for (FunctionDecl *Older = Old->getPreviousDecl();
499 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000500 if (!Older->getParamDecl(p)->hasDefaultArg())
501 break;
502
503 OldParam = Older->getParamDecl(p);
504 }
505
506 Diag(OldParam->getLocation(), diag::note_previous_definition)
507 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000508 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000509 // Merge the old default argument into the new parameter.
510 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000511 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000512 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000513 if (OldParam->hasUninstantiatedDefaultArg())
514 NewParam->setUninstantiatedDefaultArg(
515 OldParam->getUninstantiatedDefaultArg());
516 else
John McCall3d6c1782010-05-04 01:53:42 +0000517 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000518 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000519 if (New->getDescribedFunctionTemplate()) {
520 // Paragraph 4, quoted above, only applies to non-template functions.
521 Diag(NewParam->getLocation(),
522 diag::err_param_default_argument_template_redecl)
523 << NewParam->getDefaultArgRange();
524 Diag(Old->getLocation(), diag::note_template_prev_declaration)
525 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000526 } else if (New->getTemplateSpecializationKind()
527 != TSK_ImplicitInstantiation &&
528 New->getTemplateSpecializationKind() != TSK_Undeclared) {
529 // C++ [temp.expr.spec]p21:
530 // Default function arguments shall not be specified in a declaration
531 // or a definition for one of the following explicit specializations:
532 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000533 // - the explicit specialization of a member function template;
534 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000535 // template where the class template specialization to which the
536 // member function specialization belongs is implicitly
537 // instantiated.
538 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
539 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
540 << New->getDeclName()
541 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000542 } else if (New->getDeclContext()->isDependentContext()) {
543 // C++ [dcl.fct.default]p6 (DR217):
544 // Default arguments for a member function of a class template shall
545 // be specified on the initial declaration of the member function
546 // within the class template.
547 //
548 // Reading the tea leaves a bit in DR217 and its reference to DR205
549 // leads me to the conclusion that one cannot add default function
550 // arguments for an out-of-line definition of a member function of a
551 // dependent type.
552 int WhichKind = 2;
553 if (CXXRecordDecl *Record
554 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
555 if (Record->getDescribedClassTemplate())
556 WhichKind = 0;
557 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
558 WhichKind = 1;
559 else
560 WhichKind = 2;
561 }
562
563 Diag(NewParam->getLocation(),
564 diag::err_param_default_argument_member_template_redecl)
565 << WhichKind
566 << NewParam->getDefaultArgRange();
567 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000568 }
569 }
570
Richard Smithb8abff62012-11-28 03:45:24 +0000571 // DR1344: If a default argument is added outside a class definition and that
572 // default argument makes the function a special member function, the program
573 // is ill-formed. This can only happen for constructors.
574 if (isa<CXXConstructorDecl>(New) &&
575 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
576 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
577 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
578 if (NewSM != OldSM) {
579 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
580 assert(NewParam->hasDefaultArg());
581 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
582 << NewParam->getDefaultArgRange() << NewSM;
583 Diag(Old->getLocation(), diag::note_previous_declaration);
584 }
585 }
586
Stephen Hines651f13c2014-04-23 16:59:28 -0700587 const FunctionDecl *Def;
Richard Smithff234882012-02-20 23:28:05 +0000588 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000589 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000590 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000591 if (New->isConstexpr() != Old->isConstexpr()) {
592 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
593 << New << New->isConstexpr();
594 Diag(Old->getLocation(), diag::note_previous_declaration);
595 Invalid = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700596 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
597 // C++11 [dcl.fcn.spec]p4:
598 // If the definition of a function appears in a translation unit before its
599 // first declaration as inline, the program is ill-formed.
600 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
601 Diag(Def->getLocation(), diag::note_previous_definition);
602 Invalid = true;
Richard Smith9f569cc2011-10-01 02:31:28 +0000603 }
604
David Majnemerf6a144f2013-06-25 23:09:30 +0000605 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumifd527a42013-07-17 17:57:52 +0000606 // argument expression, that declaration shall be a definition and shall be
David Majnemerf6a144f2013-06-25 23:09:30 +0000607 // the only declaration of the function or function template in the
608 // translation unit.
609 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
610 functionDeclHasDefaultArgument(Old)) {
611 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
612 Diag(Old->getLocation(), diag::note_previous_declaration);
613 Invalid = true;
614 }
615
Douglas Gregore13ad832010-02-12 07:32:17 +0000616 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000617 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000618
Douglas Gregorcda9c672009-02-16 17:45:42 +0000619 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000620}
621
Sebastian Redl60618fa2011-03-12 11:50:43 +0000622/// \brief Merge the exception specifications of two variable declarations.
623///
624/// This is called when there's a redeclaration of a VarDecl. The function
625/// checks if the redeclaration might have an exception specification and
626/// validates compatibility and merges the specs if necessary.
627void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
628 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000629 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000630 return;
631
632 assert(Context.hasSameType(New->getType(), Old->getType()) &&
633 "Should only be called if types are otherwise the same.");
634
635 QualType NewType = New->getType();
636 QualType OldType = Old->getType();
637
638 // We're only interested in pointers and references to functions, as well
639 // as pointers to member functions.
640 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
641 NewType = R->getPointeeType();
642 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
643 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
644 NewType = P->getPointeeType();
645 OldType = OldType->getAs<PointerType>()->getPointeeType();
646 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
647 NewType = M->getPointeeType();
648 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
649 }
650
651 if (!NewType->isFunctionProtoType())
652 return;
653
654 // There's lots of special cases for functions. For function pointers, system
655 // libraries are hopefully not as broken so that we don't need these
656 // workarounds.
657 if (CheckEquivalentExceptionSpec(
658 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
659 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
660 New->setInvalidDecl();
661 }
662}
663
Chris Lattner3d1cee32008-04-08 05:04:30 +0000664/// CheckCXXDefaultArguments - Verify that the default arguments for a
665/// function declaration are well-formed according to C++
666/// [dcl.fct.default].
667void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
668 unsigned NumParams = FD->getNumParams();
669 unsigned p;
670
671 // Find first parameter with a default argument
672 for (p = 0; p < NumParams; ++p) {
673 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000674 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000675 break;
676 }
677
678 // C++ [dcl.fct.default]p4:
679 // In a given function declaration, all parameters
680 // subsequent to a parameter with a default argument shall
681 // have default arguments supplied in this or previous
682 // declarations. A default argument shall not be redefined
683 // by a later declaration (not even to the same value).
684 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000685 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000686 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000687 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000688 if (Param->isInvalidDecl())
689 /* We already complained about this parameter. */;
690 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000691 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000692 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000693 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000694 else
Mike Stump1eb44332009-09-09 15:08:12 +0000695 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000696 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000697
Chris Lattner3d1cee32008-04-08 05:04:30 +0000698 LastMissingDefaultArg = p;
699 }
700 }
701
702 if (LastMissingDefaultArg > 0) {
703 // Some default arguments were missing. Clear out all of the
704 // default arguments up to (and including) the last missing
705 // default argument, so that we leave the function parameters
706 // in a semantically valid state.
707 for (p = 0; p <= LastMissingDefaultArg; ++p) {
708 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000709 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000710 Param->setDefaultArg(0);
711 }
712 }
713 }
714}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000715
Richard Smith9f569cc2011-10-01 02:31:28 +0000716// CheckConstexprParameterTypes - Check whether a function's parameter types
717// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000718// diagnostic and return false.
719static bool CheckConstexprParameterTypes(Sema &SemaRef,
720 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000721 unsigned ArgIndex = 0;
722 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -0700723 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
724 e = FT->param_type_end();
725 i != e; ++i, ++ArgIndex) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000726 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
727 SourceLocation ParamLoc = PD->getLocation();
728 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000729 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000730 diag::err_constexpr_non_literal_param,
731 ArgIndex+1, PD->getSourceRange(),
732 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000733 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000734 }
Joao Matos17d35c32012-08-31 22:18:20 +0000735 return true;
736}
737
738/// \brief Get diagnostic %select index for tag kind for
739/// record diagnostic message.
740/// WARNING: Indexes apply to particular diagnostics only!
741///
742/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000743static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000744 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000745 case TTK_Struct: return 0;
746 case TTK_Interface: return 1;
747 case TTK_Class: return 2;
748 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000749 }
Joao Matos17d35c32012-08-31 22:18:20 +0000750}
751
752// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
753// the requirements of a constexpr function definition or a constexpr
754// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000755// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000756//
Richard Smith86c3ae42012-02-13 03:54:03 +0000757// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
758bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000759 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
760 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000761 // C++11 [dcl.constexpr]p4:
762 // The definition of a constexpr constructor shall satisfy the following
763 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000764 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000765 const CXXRecordDecl *RD = MD->getParent();
766 if (RD->getNumVBases()) {
767 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
768 << isa<CXXConstructorDecl>(NewFD)
769 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Stephen Hines651f13c2014-04-23 16:59:28 -0700770 for (const auto &I : RD->vbases())
771 Diag(I.getLocStart(),
772 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000773 return false;
774 }
Richard Smith35340502012-01-13 04:54:00 +0000775 }
776
777 if (!isa<CXXConstructorDecl>(NewFD)) {
778 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000779 // The definition of a constexpr function shall satisfy the following
780 // constraints:
781 // - it shall not be virtual;
782 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
783 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000784 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000785
Richard Smith86c3ae42012-02-13 03:54:03 +0000786 // If it's not obvious why this function is virtual, find an overridden
787 // function which uses the 'virtual' keyword.
788 const CXXMethodDecl *WrittenVirtual = Method;
789 while (!WrittenVirtual->isVirtualAsWritten())
790 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
791 if (WrittenVirtual != Method)
792 Diag(WrittenVirtual->getLocation(),
793 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000794 return false;
795 }
796
797 // - its return type shall be a literal type;
Stephen Hines651f13c2014-04-23 16:59:28 -0700798 QualType RT = NewFD->getReturnType();
Richard Smith9f569cc2011-10-01 02:31:28 +0000799 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000800 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000801 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000802 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000803 }
804
Richard Smith35340502012-01-13 04:54:00 +0000805 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000806 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000807 return false;
808
Richard Smith9f569cc2011-10-01 02:31:28 +0000809 return true;
810}
811
812/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000813/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000814///
Richard Smitha10b9782013-04-22 15:31:51 +0000815/// \return true if the body is OK (maybe only as an extension), false if we
816/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000817static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000818 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
819 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000820 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
821 // contain only
Stephen Hines651f13c2014-04-23 16:59:28 -0700822 for (const auto *DclIt : DS->decls()) {
823 switch (DclIt->getKind()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000824 case Decl::StaticAssert:
825 case Decl::Using:
826 case Decl::UsingShadow:
827 case Decl::UsingDirective:
828 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000829 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000830 // - static_assert-declarations
831 // - using-declarations,
832 // - using-directives,
833 continue;
834
835 case Decl::Typedef:
836 case Decl::TypeAlias: {
837 // - typedef declarations and alias-declarations that do not define
838 // classes or enumerations,
Stephen Hines651f13c2014-04-23 16:59:28 -0700839 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smith9f569cc2011-10-01 02:31:28 +0000840 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
841 // Don't allow variably-modified types in constexpr functions.
842 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
843 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
844 << TL.getSourceRange() << TL.getType()
845 << isa<CXXConstructorDecl>(Dcl);
846 return false;
847 }
848 continue;
849 }
850
851 case Decl::Enum:
852 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000853 // C++1y allows types to be defined, not just declared.
Stephen Hines651f13c2014-04-23 16:59:28 -0700854 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smitha10b9782013-04-22 15:31:51 +0000855 SemaRef.Diag(DS->getLocStart(),
856 SemaRef.getLangOpts().CPlusPlus1y
857 ? diag::warn_cxx11_compat_constexpr_type_definition
858 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000859 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000860 continue;
861
Richard Smitha10b9782013-04-22 15:31:51 +0000862 case Decl::EnumConstant:
863 case Decl::IndirectField:
864 case Decl::ParmVar:
865 // These can only appear with other declarations which are banned in
866 // C++11 and permitted in C++1y, so ignore them.
867 continue;
868
869 case Decl::Var: {
870 // C++1y [dcl.constexpr]p3 allows anything except:
871 // a definition of a variable of non-literal type or of static or
872 // thread storage duration or for which no initialization is performed.
Stephen Hines651f13c2014-04-23 16:59:28 -0700873 const auto *VD = cast<VarDecl>(DclIt);
Richard Smitha10b9782013-04-22 15:31:51 +0000874 if (VD->isThisDeclarationADefinition()) {
875 if (VD->isStaticLocal()) {
876 SemaRef.Diag(VD->getLocation(),
877 diag::err_constexpr_local_var_static)
878 << isa<CXXConstructorDecl>(Dcl)
879 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
880 return false;
881 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000882 if (!VD->getType()->isDependentType() &&
883 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000884 VD->getLocation(), VD->getType(),
885 diag::err_constexpr_local_var_non_literal_type,
886 isa<CXXConstructorDecl>(Dcl)))
887 return false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700888 if (!VD->getType()->isDependentType() &&
889 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smitha10b9782013-04-22 15:31:51 +0000890 SemaRef.Diag(VD->getLocation(),
891 diag::err_constexpr_local_var_no_init)
892 << isa<CXXConstructorDecl>(Dcl);
893 return false;
894 }
895 }
896 SemaRef.Diag(VD->getLocation(),
897 SemaRef.getLangOpts().CPlusPlus1y
898 ? diag::warn_cxx11_compat_constexpr_local_var
899 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000900 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000901 continue;
902 }
903
904 case Decl::NamespaceAlias:
905 case Decl::Function:
906 // These are disallowed in C++11 and permitted in C++1y. Allow them
907 // everywhere as an extension.
908 if (!Cxx1yLoc.isValid())
909 Cxx1yLoc = DS->getLocStart();
910 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000911
912 default:
913 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
914 << isa<CXXConstructorDecl>(Dcl);
915 return false;
916 }
917 }
918
919 return true;
920}
921
922/// Check that the given field is initialized within a constexpr constructor.
923///
924/// \param Dcl The constexpr constructor being checked.
925/// \param Field The field being checked. This may be a member of an anonymous
926/// struct or union nested within the class being checked.
927/// \param Inits All declarations, including anonymous struct/union members and
928/// indirect members, for which any initialization was provided.
929/// \param Diagnosed Set to true if an error is produced.
930static void CheckConstexprCtorInitializer(Sema &SemaRef,
931 const FunctionDecl *Dcl,
932 FieldDecl *Field,
933 llvm::SmallSet<Decl*, 16> &Inits,
934 bool &Diagnosed) {
Eli Friedman5fb478b2013-06-28 21:07:41 +0000935 if (Field->isInvalidDecl())
936 return;
937
Douglas Gregord61db332011-10-10 17:22:13 +0000938 if (Field->isUnnamedBitfield())
939 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000940
Stephen Hines651f13c2014-04-23 16:59:28 -0700941 // Anonymous unions with no variant members and empty anonymous structs do not
942 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
943 // indirect fields don't need initializing.
Richard Smith30ecfad2012-02-09 06:40:58 +0000944 if (Field->isAnonymousStructOrUnion() &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700945 (Field->getType()->isUnionType()
946 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
947 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith30ecfad2012-02-09 06:40:58 +0000948 return;
949
Richard Smith9f569cc2011-10-01 02:31:28 +0000950 if (!Inits.count(Field)) {
951 if (!Diagnosed) {
952 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
953 Diagnosed = true;
954 }
955 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
956 } else if (Field->isAnonymousStructOrUnion()) {
957 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Stephen Hines651f13c2014-04-23 16:59:28 -0700958 for (auto *I : RD->fields())
Richard Smith9f569cc2011-10-01 02:31:28 +0000959 // If an anonymous union contains an anonymous struct of which any member
960 // is initialized, all members must be initialized.
Stephen Hines651f13c2014-04-23 16:59:28 -0700961 if (!RD->isUnion() || Inits.count(I))
962 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000963 }
964}
965
Richard Smitha10b9782013-04-22 15:31:51 +0000966/// Check the provided statement is allowed in a constexpr function
967/// definition.
968static bool
969CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelme7205c02013-08-10 12:33:24 +0000970 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smitha10b9782013-04-22 15:31:51 +0000971 SourceLocation &Cxx1yLoc) {
972 // - its function-body shall be [...] a compound-statement that contains only
973 switch (S->getStmtClass()) {
974 case Stmt::NullStmtClass:
975 // - null statements,
976 return true;
977
978 case Stmt::DeclStmtClass:
979 // - static_assert-declarations
980 // - using-declarations,
981 // - using-directives,
982 // - typedef declarations and alias-declarations that do not define
983 // classes or enumerations,
984 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
985 return false;
986 return true;
987
988 case Stmt::ReturnStmtClass:
989 // - and exactly one return statement;
990 if (isa<CXXConstructorDecl>(Dcl)) {
991 // C++1y allows return statements in constexpr constructors.
992 if (!Cxx1yLoc.isValid())
993 Cxx1yLoc = S->getLocStart();
994 return true;
995 }
996
997 ReturnStmts.push_back(S->getLocStart());
998 return true;
999
1000 case Stmt::CompoundStmtClass: {
1001 // C++1y allows compound-statements.
1002 if (!Cxx1yLoc.isValid())
1003 Cxx1yLoc = S->getLocStart();
1004
1005 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Stephen Hines651f13c2014-04-23 16:59:28 -07001006 for (auto *BodyIt : CompStmt->body()) {
1007 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smitha10b9782013-04-22 15:31:51 +00001008 Cxx1yLoc))
1009 return false;
1010 }
1011 return true;
1012 }
1013
1014 case Stmt::AttributedStmtClass:
1015 if (!Cxx1yLoc.isValid())
1016 Cxx1yLoc = S->getLocStart();
1017 return true;
1018
1019 case Stmt::IfStmtClass: {
1020 // C++1y allows if-statements.
1021 if (!Cxx1yLoc.isValid())
1022 Cxx1yLoc = S->getLocStart();
1023
1024 IfStmt *If = cast<IfStmt>(S);
1025 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1026 Cxx1yLoc))
1027 return false;
1028 if (If->getElse() &&
1029 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1030 Cxx1yLoc))
1031 return false;
1032 return true;
1033 }
1034
1035 case Stmt::WhileStmtClass:
1036 case Stmt::DoStmtClass:
1037 case Stmt::ForStmtClass:
1038 case Stmt::CXXForRangeStmtClass:
1039 case Stmt::ContinueStmtClass:
1040 // C++1y allows all of these. We don't allow them as extensions in C++11,
1041 // because they don't make sense without variable mutation.
1042 if (!SemaRef.getLangOpts().CPlusPlus1y)
1043 break;
1044 if (!Cxx1yLoc.isValid())
1045 Cxx1yLoc = S->getLocStart();
1046 for (Stmt::child_range Children = S->children(); Children; ++Children)
1047 if (*Children &&
1048 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1049 Cxx1yLoc))
1050 return false;
1051 return true;
1052
1053 case Stmt::SwitchStmtClass:
1054 case Stmt::CaseStmtClass:
1055 case Stmt::DefaultStmtClass:
1056 case Stmt::BreakStmtClass:
1057 // C++1y allows switch-statements, and since they don't need variable
1058 // mutation, we can reasonably allow them in C++11 as an extension.
1059 if (!Cxx1yLoc.isValid())
1060 Cxx1yLoc = S->getLocStart();
1061 for (Stmt::child_range Children = S->children(); Children; ++Children)
1062 if (*Children &&
1063 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1064 Cxx1yLoc))
1065 return false;
1066 return true;
1067
1068 default:
1069 if (!isa<Expr>(S))
1070 break;
1071
1072 // C++1y allows expression-statements.
1073 if (!Cxx1yLoc.isValid())
1074 Cxx1yLoc = S->getLocStart();
1075 return true;
1076 }
1077
1078 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1079 << isa<CXXConstructorDecl>(Dcl);
1080 return false;
1081}
1082
Richard Smith9f569cc2011-10-01 02:31:28 +00001083/// Check the body for the given constexpr function declaration only contains
1084/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1085///
1086/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001087bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001088 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001089 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001090 // The definition of a constexpr function shall satisfy the following
1091 // constraints: [...]
1092 // - its function-body shall be = delete, = default, or a
1093 // compound-statement
1094 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001095 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001096 // In the definition of a constexpr constructor, [...]
1097 // - its function-body shall not be a function-try-block;
1098 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1099 << isa<CXXConstructorDecl>(Dcl);
1100 return false;
1101 }
1102
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001103 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001104
1105 // - its function-body shall be [...] a compound-statement that contains only
1106 // [... list of cases ...]
1107 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1108 SourceLocation Cxx1yLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -07001109 for (auto *BodyIt : CompBody->body()) {
1110 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smitha10b9782013-04-22 15:31:51 +00001111 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001112 }
1113
Richard Smitha10b9782013-04-22 15:31:51 +00001114 if (Cxx1yLoc.isValid())
1115 Diag(Cxx1yLoc,
1116 getLangOpts().CPlusPlus1y
1117 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1118 : diag::ext_constexpr_body_invalid_stmt)
1119 << isa<CXXConstructorDecl>(Dcl);
1120
Richard Smith9f569cc2011-10-01 02:31:28 +00001121 if (const CXXConstructorDecl *Constructor
1122 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1123 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001124 // DR1359:
1125 // - every non-variant non-static data member and base class sub-object
1126 // shall be initialized;
Stephen Hines651f13c2014-04-23 16:59:28 -07001127 // DR1460:
1128 // - if the class is a union having variant members, exactly one of them
Richard Smith30ecfad2012-02-09 06:40:58 +00001129 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001130 if (RD->isUnion()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001131 if (Constructor->getNumCtorInitializers() == 0 &&
1132 RD->hasVariantMembers()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001133 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1134 return false;
1135 }
Richard Smith6e433752011-10-10 16:38:04 +00001136 } else if (!Constructor->isDependentContext() &&
1137 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001138 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1139
1140 // Skip detailed checking if we have enough initializers, and we would
1141 // allow at most one initializer per member.
1142 bool AnyAnonStructUnionMembers = false;
1143 unsigned Fields = 0;
1144 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1145 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001146 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001147 AnyAnonStructUnionMembers = true;
1148 break;
1149 }
1150 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001151 // DR1460:
1152 // - if the class is a union-like class, but is not a union, for each of
1153 // its anonymous union members having variant members, exactly one of
1154 // them shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001155 if (AnyAnonStructUnionMembers ||
1156 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1157 // Check initialization of non-static data members. Base classes are
1158 // always initialized so do not need to be checked. Dependent bases
1159 // might not have initializers in the member initializer list.
1160 llvm::SmallSet<Decl*, 16> Inits;
Stephen Hines651f13c2014-04-23 16:59:28 -07001161 for (const auto *I: Constructor->inits()) {
1162 if (FieldDecl *FD = I->getMember())
Richard Smith9f569cc2011-10-01 02:31:28 +00001163 Inits.insert(FD);
Stephen Hines651f13c2014-04-23 16:59:28 -07001164 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smith9f569cc2011-10-01 02:31:28 +00001165 Inits.insert(ID->chain_begin(), ID->chain_end());
1166 }
1167
1168 bool Diagnosed = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07001169 for (auto *I : RD->fields())
1170 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001171 if (Diagnosed)
1172 return false;
1173 }
1174 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001175 } else {
1176 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001177 // C++1y doesn't require constexpr functions to contain a 'return'
1178 // statement. We still do, unless the return type is void, because
1179 // otherwise if there's no return statement, the function cannot
1180 // be used in a core constant expression.
Stephen Hines651f13c2014-04-23 16:59:28 -07001181 bool OK = getLangOpts().CPlusPlus1y && Dcl->getReturnType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001182 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001183 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1184 : diag::err_constexpr_body_no_return);
1185 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001186 }
1187 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001188 Diag(ReturnStmts.back(),
1189 getLangOpts().CPlusPlus1y
1190 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1191 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001192 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1193 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001194 }
1195 }
1196
Richard Smith5ba73e12012-02-04 00:33:54 +00001197 // C++11 [dcl.constexpr]p5:
1198 // if no function argument values exist such that the function invocation
1199 // substitution would produce a constant expression, the program is
1200 // ill-formed; no diagnostic required.
1201 // C++11 [dcl.constexpr]p3:
1202 // - every constructor call and implicit conversion used in initializing the
1203 // return value shall be one of those allowed in a constant expression.
1204 // C++11 [dcl.constexpr]p4:
1205 // - every constructor involved in initializing non-static data members and
1206 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001207 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001208 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001209 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001210 << isa<CXXConstructorDecl>(Dcl);
1211 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1212 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001213 // Don't return false here: we allow this for compatibility in
1214 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001215 }
1216
Richard Smith9f569cc2011-10-01 02:31:28 +00001217 return true;
1218}
1219
Douglas Gregorb48fe382008-10-31 09:07:45 +00001220/// isCurrentClassName - Determine whether the identifier II is the
1221/// name of the class type currently being defined. In the case of
1222/// nested classes, this will only return true if II is the name of
1223/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001224bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1225 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001226 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001227
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001228 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001229 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001230 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001231 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1232 } else
1233 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1234
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001235 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001236 return &II == CurDecl->getIdentifier();
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00001237 return false;
Douglas Gregorb48fe382008-10-31 09:07:45 +00001238}
1239
Richard Smithb79b17b2013-10-15 00:00:26 +00001240/// \brief Determine whether the identifier II is a typo for the name of
1241/// the class type currently being defined. If so, update it to the identifier
1242/// that should have been used.
1243bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1244 assert(getLangOpts().CPlusPlus && "No class names in C!");
1245
1246 if (!getLangOpts().SpellChecking)
1247 return false;
1248
1249 CXXRecordDecl *CurDecl;
1250 if (SS && SS->isSet() && !SS->isInvalid()) {
1251 DeclContext *DC = computeDeclContext(*SS, true);
1252 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1253 } else
1254 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1255
1256 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1257 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1258 < II->getLength()) {
1259 II = CurDecl->getIdentifier();
1260 return true;
1261 }
1262
1263 return false;
1264}
1265
Douglas Gregor229d47a2012-11-10 07:24:09 +00001266/// \brief Determine whether the given class is a base class of the given
1267/// class, including looking at dependent bases.
1268static bool findCircularInheritance(const CXXRecordDecl *Class,
1269 const CXXRecordDecl *Current) {
1270 SmallVector<const CXXRecordDecl*, 8> Queue;
1271
1272 Class = Class->getCanonicalDecl();
1273 while (true) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001274 for (const auto &I : Current->bases()) {
1275 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregor229d47a2012-11-10 07:24:09 +00001276 if (!Base)
1277 continue;
1278
1279 Base = Base->getDefinition();
1280 if (!Base)
1281 continue;
1282
1283 if (Base->getCanonicalDecl() == Class)
1284 return true;
1285
1286 Queue.push_back(Base);
1287 }
1288
1289 if (Queue.empty())
1290 return false;
1291
Robert Wilhelm344472e2013-08-23 16:11:15 +00001292 Current = Queue.pop_back_val();
Douglas Gregor229d47a2012-11-10 07:24:09 +00001293 }
1294
1295 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001296}
1297
Mike Stump1eb44332009-09-09 15:08:12 +00001298/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001299///
1300/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1301/// and returns NULL otherwise.
1302CXXBaseSpecifier *
1303Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1304 SourceRange SpecifierRange,
1305 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001306 TypeSourceInfo *TInfo,
1307 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001308 QualType BaseType = TInfo->getType();
1309
Douglas Gregor2943aed2009-03-03 04:44:36 +00001310 // C++ [class.union]p1:
1311 // A union shall not have base classes.
1312 if (Class->isUnion()) {
1313 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1314 << SpecifierRange;
1315 return 0;
1316 }
1317
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001318 if (EllipsisLoc.isValid() &&
1319 !TInfo->getType()->containsUnexpandedParameterPack()) {
1320 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1321 << TInfo->getTypeLoc().getSourceRange();
1322 EllipsisLoc = SourceLocation();
1323 }
Douglas Gregord777e282012-11-10 01:18:17 +00001324
1325 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1326
1327 if (BaseType->isDependentType()) {
1328 // Make sure that we don't have circular inheritance among our dependent
1329 // bases. For non-dependent bases, the check for completeness below handles
1330 // this.
1331 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1332 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1333 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001334 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001335 Diag(BaseLoc, diag::err_circular_inheritance)
1336 << BaseType << Context.getTypeDeclType(Class);
1337
1338 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1339 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1340 << BaseType;
1341
1342 return 0;
1343 }
1344 }
1345
Mike Stump1eb44332009-09-09 15:08:12 +00001346 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001347 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001348 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001349 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001350
1351 // Base specifiers must be record types.
1352 if (!BaseType->isRecordType()) {
1353 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1354 return 0;
1355 }
1356
1357 // C++ [class.union]p1:
1358 // A union shall not be used as a base class.
1359 if (BaseType->isUnionType()) {
1360 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1361 return 0;
1362 }
1363
1364 // C++ [class.derived]p2:
1365 // The class-name in a base-specifier shall not be an incompletely
1366 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001367 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001368 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001369 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001370 return 0;
John McCall572fc622010-08-17 07:23:57 +00001371 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001372
Eli Friedman1d954f62009-08-15 21:55:26 +00001373 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001374 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001375 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001376 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001377 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001378 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001379 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001380
David Majnemer28165b72013-11-02 12:00:36 +00001381 // A class which contains a flexible array member is not suitable for use as a
1382 // base class:
1383 // - If the layout determines that a base comes before another base,
1384 // the flexible array member would index into the subsequent base.
1385 // - If the layout determines that base comes before the derived class,
1386 // the flexible array member would index into the derived class.
1387 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1388 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1389 << CXXBaseDecl->getDeclName();
1390 return 0;
1391 }
1392
Anders Carlsson1d209272011-03-25 14:55:14 +00001393 // C++ [class]p3:
David Majnemer7041fcc2013-11-02 11:24:41 +00001394 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson1d209272011-03-25 14:55:14 +00001395 // base-clause, the program is ill-formed.
David Majnemer7121bdb2013-10-18 00:33:31 +00001396 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer7041fcc2013-11-02 11:24:41 +00001397 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemer7121bdb2013-10-18 00:33:31 +00001398 << CXXBaseDecl->getDeclName()
1399 << FA->isSpelledAsSealed();
Anders Carlssondfc2f102011-01-22 17:51:53 +00001400 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1401 << CXXBaseDecl->getDeclName();
1402 return 0;
1403 }
1404
John McCall572fc622010-08-17 07:23:57 +00001405 if (BaseDecl->isInvalidDecl())
1406 Class->setInvalidDecl();
David Majnemer7041fcc2013-11-02 11:24:41 +00001407
Anders Carlsson51f94042009-12-03 17:49:57 +00001408 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001409 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001410 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001411 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001412}
1413
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001414/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1415/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001416/// example:
1417/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001418/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001419BaseResult
John McCalld226f652010-08-21 09:40:31 +00001420Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001421 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001422 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001423 ParsedType basetype, SourceLocation BaseLoc,
1424 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001425 if (!classdecl)
1426 return true;
1427
Douglas Gregor40808ce2009-03-09 23:48:35 +00001428 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001429 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001430 if (!Class)
1431 return true;
1432
Richard Smith05321402013-02-19 23:47:15 +00001433 // We do not support any C++11 attributes on base-specifiers yet.
1434 // Diagnose any attributes we see.
1435 if (!Attributes.empty()) {
1436 for (AttributeList *Attr = Attributes.getList(); Attr;
1437 Attr = Attr->getNext()) {
1438 if (Attr->isInvalid() ||
1439 Attr->getKind() == AttributeList::IgnoredAttribute)
1440 continue;
1441 Diag(Attr->getLoc(),
1442 Attr->getKind() == AttributeList::UnknownAttribute
1443 ? diag::warn_unknown_attribute_ignored
1444 : diag::err_base_specifier_attribute)
1445 << Attr->getName();
1446 }
1447 }
1448
Nick Lewycky56062202010-07-26 16:56:01 +00001449 TypeSourceInfo *TInfo = 0;
1450 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001451
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001452 if (EllipsisLoc.isInvalid() &&
1453 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001454 UPPC_BaseType))
1455 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001456
Douglas Gregor2943aed2009-03-03 04:44:36 +00001457 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001458 Virtual, Access, TInfo,
1459 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001460 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001461 else
1462 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Douglas Gregor2943aed2009-03-03 04:44:36 +00001464 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001465}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001466
Douglas Gregor2943aed2009-03-03 04:44:36 +00001467/// \brief Performs the actual work of attaching the given base class
1468/// specifiers to a C++ class.
1469bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1470 unsigned NumBases) {
1471 if (NumBases == 0)
1472 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001473
1474 // Used to keep track of which base types we have already seen, so
1475 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001476 // that the key is always the unqualified canonical type of the base
1477 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001478 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1479
1480 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001481 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001482 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001483 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001484 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001485 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001486 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001487
1488 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1489 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001490 // C++ [class.mi]p3:
1491 // A class shall not be specified as a direct base class of a
1492 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001493 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001494 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001495 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001496 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001497
1498 // Delete the duplicate base class specifier; we're going to
1499 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001500 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001501
1502 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001503 } else {
1504 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001505 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001506 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001507 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1508 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1509 if (Class->isInterface() &&
1510 (!RD->isInterface() ||
1511 KnownBase->getAccessSpecifier() != AS_public)) {
1512 // The Microsoft extension __interface does not permit bases that
1513 // are not themselves public interfaces.
1514 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1515 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1516 << RD->getSourceRange();
1517 Invalid = true;
1518 }
1519 if (RD->hasAttr<WeakAttr>())
Stephen Hines651f13c2014-04-23 16:59:28 -07001520 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalle402e722012-09-25 07:32:39 +00001521 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001522 }
1523 }
1524
1525 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001526 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001527
1528 // Delete the remaining (good) base class specifiers, since their
1529 // data has been copied into the CXXRecordDecl.
1530 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001531 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001532
1533 return Invalid;
1534}
1535
1536/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1537/// class, after checking whether there are any duplicate base
1538/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001539void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001540 unsigned NumBases) {
1541 if (!ClassDecl || !Bases || !NumBases)
1542 return;
1543
1544 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelm0d317a02013-07-22 05:04:01 +00001545 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001546}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001547
Douglas Gregora8f32e02009-10-06 17:59:45 +00001548/// \brief Determine whether the type \p Derived is a C++ class that is
1549/// derived from the type \p Base.
1550bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001551 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001552 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001553
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001554 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001555 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001556 return false;
1557
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001558 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001559 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001560 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001561
1562 // If either the base or the derived type is invalid, don't try to
1563 // check whether one is derived from the other.
1564 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1565 return false;
1566
John McCall86ff3082010-02-04 22:26:26 +00001567 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1568 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001569}
1570
1571/// \brief Determine whether the type \p Derived is a C++ class that is
1572/// derived from the type \p Base.
1573bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001574 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001575 return false;
1576
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001577 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001578 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001579 return false;
1580
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001581 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001582 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001583 return false;
1584
Douglas Gregora8f32e02009-10-06 17:59:45 +00001585 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1586}
1587
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001588void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001589 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001590 assert(BasePathArray.empty() && "Base path array must be empty!");
1591 assert(Paths.isRecordingPaths() && "Must record paths!");
1592
1593 const CXXBasePath &Path = Paths.front();
1594
1595 // We first go backward and check if we have a virtual base.
1596 // FIXME: It would be better if CXXBasePath had the base specifier for
1597 // the nearest virtual base.
1598 unsigned Start = 0;
1599 for (unsigned I = Path.size(); I != 0; --I) {
1600 if (Path[I - 1].Base->isVirtual()) {
1601 Start = I - 1;
1602 break;
1603 }
1604 }
1605
1606 // Now add all bases.
1607 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001608 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001609}
1610
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001611/// \brief Determine whether the given base path includes a virtual
1612/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001613bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1614 for (CXXCastPath::const_iterator B = BasePath.begin(),
1615 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001616 B != BEnd; ++B)
1617 if ((*B)->isVirtual())
1618 return true;
1619
1620 return false;
1621}
1622
Douglas Gregora8f32e02009-10-06 17:59:45 +00001623/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1624/// conversion (where Derived and Base are class types) is
1625/// well-formed, meaning that the conversion is unambiguous (and
1626/// that all of the base classes are accessible). Returns true
1627/// and emits a diagnostic if the code is ill-formed, returns false
1628/// otherwise. Loc is the location where this routine should point to
1629/// if there is an error, and Range is the source range to highlight
1630/// if there is an error.
1631bool
1632Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001633 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001634 unsigned AmbigiousBaseConvID,
1635 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001636 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001637 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001638 // First, determine whether the path from Derived to Base is
1639 // ambiguous. This is slightly more expensive than checking whether
1640 // the Derived to Base conversion exists, because here we need to
1641 // explore multiple paths to determine if there is an ambiguity.
1642 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1643 /*DetectVirtual=*/false);
1644 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1645 assert(DerivationOkay &&
1646 "Can only be used with a derived-to-base conversion");
1647 (void)DerivationOkay;
1648
1649 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001650 if (InaccessibleBaseID) {
1651 // Check that the base class can be accessed.
1652 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1653 InaccessibleBaseID)) {
1654 case AR_inaccessible:
1655 return true;
1656 case AR_accessible:
1657 case AR_dependent:
1658 case AR_delayed:
1659 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001660 }
John McCall6b2accb2010-02-10 09:31:12 +00001661 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001662
1663 // Build a base path if necessary.
1664 if (BasePath)
1665 BuildBasePathArray(Paths, *BasePath);
1666 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001667 }
1668
David Majnemer2f686692013-06-22 06:43:58 +00001669 if (AmbigiousBaseConvID) {
1670 // We know that the derived-to-base conversion is ambiguous, and
1671 // we're going to produce a diagnostic. Perform the derived-to-base
1672 // search just one more time to compute all of the possible paths so
1673 // that we can print them out. This is more expensive than any of
1674 // the previous derived-to-base checks we've done, but at this point
1675 // performance isn't as much of an issue.
1676 Paths.clear();
1677 Paths.setRecordingPaths(true);
1678 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1679 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1680 (void)StillOkay;
1681
1682 // Build up a textual representation of the ambiguous paths, e.g.,
1683 // D -> B -> A, that will be used to illustrate the ambiguous
1684 // conversions in the diagnostic. We only print one of the paths
1685 // to each base class subobject.
1686 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1687
1688 Diag(Loc, AmbigiousBaseConvID)
1689 << Derived << Base << PathDisplayStr << Range << Name;
1690 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001691 return true;
1692}
1693
1694bool
1695Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001696 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001697 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001698 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001699 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001700 IgnoreAccess ? 0
1701 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001702 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001703 Loc, Range, DeclarationName(),
1704 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001705}
1706
1707
1708/// @brief Builds a string representing ambiguous paths from a
1709/// specific derived class to different subobjects of the same base
1710/// class.
1711///
1712/// This function builds a string that can be used in error messages
1713/// to show the different paths that one can take through the
1714/// inheritance hierarchy to go from the derived class to different
1715/// subobjects of a base class. The result looks something like this:
1716/// @code
1717/// struct D -> struct B -> struct A
1718/// struct D -> struct C -> struct A
1719/// @endcode
1720std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1721 std::string PathDisplayStr;
1722 std::set<unsigned> DisplayedPaths;
1723 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1724 Path != Paths.end(); ++Path) {
1725 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1726 // We haven't displayed a path to this particular base
1727 // class subobject yet.
1728 PathDisplayStr += "\n ";
1729 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1730 for (CXXBasePath::const_iterator Element = Path->begin();
1731 Element != Path->end(); ++Element)
1732 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1733 }
1734 }
1735
1736 return PathDisplayStr;
1737}
1738
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001739//===----------------------------------------------------------------------===//
1740// C++ class member Handling
1741//===----------------------------------------------------------------------===//
1742
Abramo Bagnara6206d532010-06-05 05:09:32 +00001743/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001744bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1745 SourceLocation ASLoc,
1746 SourceLocation ColonLoc,
1747 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001748 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001749 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001750 ASLoc, ColonLoc);
1751 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001752 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001753}
1754
Richard Smitha4b39652012-08-06 03:25:17 +00001755/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmandae92712013-09-05 23:51:03 +00001756void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001757 if (D->isInvalidDecl())
1758 return;
1759
Eli Friedmandae92712013-09-05 23:51:03 +00001760 // We only care about "override" and "final" declarations.
1761 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1762 return;
Anders Carlsson9e682d92011-01-20 05:57:14 +00001763
Eli Friedmandae92712013-09-05 23:51:03 +00001764 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001765
Eli Friedmandae92712013-09-05 23:51:03 +00001766 // We can't check dependent instance methods.
1767 if (MD && MD->isInstance() &&
1768 (MD->getParent()->hasAnyDependentBases() ||
1769 MD->getType()->isDependentType()))
1770 return;
1771
1772 if (MD && !MD->isVirtual()) {
1773 // If we have a non-virtual method, check if if hides a virtual method.
1774 // (In that case, it's most likely the method has the wrong type.)
1775 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1776 FindHiddenVirtualMethods(MD, OverloadedMethods);
1777
1778 if (!OverloadedMethods.empty()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001779 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1780 Diag(OA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001781 diag::override_keyword_hides_virtual_member_function)
1782 << "override" << (OverloadedMethods.size() > 1);
1783 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001784 Diag(FA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001785 diag::override_keyword_hides_virtual_member_function)
David Majnemer7121bdb2013-10-18 00:33:31 +00001786 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1787 << (OverloadedMethods.size() > 1);
Richard Smitha4b39652012-08-06 03:25:17 +00001788 }
Eli Friedmandae92712013-09-05 23:51:03 +00001789 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1790 MD->setInvalidDecl();
1791 return;
1792 }
1793 // Fall through into the general case diagnostic.
1794 // FIXME: We might want to attempt typo correction here.
1795 }
1796
1797 if (!MD || !MD->isVirtual()) {
1798 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1799 Diag(OA->getLocation(),
1800 diag::override_keyword_only_allowed_on_virtual_member_functions)
1801 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1802 D->dropAttr<OverrideAttr>();
1803 }
1804 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1805 Diag(FA->getLocation(),
1806 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemer7121bdb2013-10-18 00:33:31 +00001807 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1808 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmandae92712013-09-05 23:51:03 +00001809 D->dropAttr<FinalAttr>();
Richard Smitha4b39652012-08-06 03:25:17 +00001810 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001811 return;
1812 }
Richard Smitha4b39652012-08-06 03:25:17 +00001813
Richard Smitha4b39652012-08-06 03:25:17 +00001814 // C++11 [class.virtual]p5:
1815 // If a virtual function is marked with the virt-specifier override and
1816 // does not override a member function of a base class, the program is
1817 // ill-formed.
1818 bool HasOverriddenMethods =
1819 MD->begin_overridden_methods() != MD->end_overridden_methods();
1820 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1821 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1822 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001823}
1824
Richard Smitha4b39652012-08-06 03:25:17 +00001825/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001826/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001827/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001828bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1829 const CXXMethodDecl *Old) {
David Majnemer7121bdb2013-10-18 00:33:31 +00001830 FinalAttr *FA = Old->getAttr<FinalAttr>();
1831 if (!FA)
Anders Carlssonf89e0422011-01-23 21:07:30 +00001832 return false;
1833
1834 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemer7121bdb2013-10-18 00:33:31 +00001835 << New->getDeclName()
1836 << FA->isSpelledAsSealed();
Anders Carlssonf89e0422011-01-23 21:07:30 +00001837 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1838 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001839}
1840
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001841static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001842 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1843 // FIXME: Destruction of ObjC lifetime types has side-effects.
1844 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1845 return !RD->isCompleteDefinition() ||
1846 !RD->hasTrivialDefaultConstructor() ||
1847 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001848 return false;
1849}
1850
John McCall76da55d2013-04-16 07:28:30 +00001851static AttributeList *getMSPropertyAttr(AttributeList *list) {
1852 for (AttributeList* it = list; it != 0; it = it->getNext())
1853 if (it->isDeclspecPropertyAttribute())
1854 return it;
1855 return 0;
1856}
1857
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001858/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1859/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001860/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001861/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1862/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001863NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001864Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001865 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001866 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001867 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001868 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001869 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1870 DeclarationName Name = NameInfo.getName();
1871 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001872
1873 // For anonymous bitfields, the location should point to the type.
1874 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001875 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001876
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001877 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001878
John McCall4bde1e12010-06-04 08:34:12 +00001879 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001880 assert(!DS.isFriendSpecified());
1881
Richard Smith1ab0d902011-06-25 02:28:38 +00001882 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001883
John McCalle402e722012-09-25 07:32:39 +00001884 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1885 // The Microsoft extension __interface only permits public member functions
1886 // and prohibits constructors, destructors, operators, non-public member
1887 // functions, static methods and data members.
1888 unsigned InvalidDecl;
1889 bool ShowDeclName = true;
1890 if (!isFunc)
1891 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1892 else if (AS != AS_public)
1893 InvalidDecl = 2;
1894 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1895 InvalidDecl = 3;
1896 else switch (Name.getNameKind()) {
1897 case DeclarationName::CXXConstructorName:
1898 InvalidDecl = 4;
1899 ShowDeclName = false;
1900 break;
1901
1902 case DeclarationName::CXXDestructorName:
1903 InvalidDecl = 5;
1904 ShowDeclName = false;
1905 break;
1906
1907 case DeclarationName::CXXOperatorName:
1908 case DeclarationName::CXXConversionFunctionName:
1909 InvalidDecl = 6;
1910 break;
1911
1912 default:
1913 InvalidDecl = 0;
1914 break;
1915 }
1916
1917 if (InvalidDecl) {
1918 if (ShowDeclName)
1919 Diag(Loc, diag::err_invalid_member_in_interface)
1920 << (InvalidDecl-1) << Name;
1921 else
1922 Diag(Loc, diag::err_invalid_member_in_interface)
1923 << (InvalidDecl-1) << "";
1924 return 0;
1925 }
1926 }
1927
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001928 // C++ 9.2p6: A member shall not be declared to have automatic storage
1929 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001930 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1931 // data members and cannot be applied to names declared const or static,
1932 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001933 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001934 case DeclSpec::SCS_unspecified:
1935 case DeclSpec::SCS_typedef:
1936 case DeclSpec::SCS_static:
1937 break;
1938 case DeclSpec::SCS_mutable:
1939 if (isFunc) {
1940 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Richard Smithec642442013-04-12 22:46:28 +00001942 // FIXME: It would be nicer if the keyword was ignored only for this
1943 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001944 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001945 }
1946 break;
1947 default:
1948 Diag(DS.getStorageClassSpecLoc(),
1949 diag::err_storageclass_invalid_for_member);
1950 D.getMutableDeclSpec().ClearStorageClassSpecs();
1951 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001952 }
1953
Sebastian Redl669d5d72008-11-14 23:42:31 +00001954 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1955 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001956 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001957
David Blaikie1d87fba2013-01-30 01:22:18 +00001958 if (DS.isConstexprSpecified() && isInstField) {
1959 SemaDiagnosticBuilder B =
1960 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1961 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1962 if (InitStyle == ICIS_NoInit) {
1963 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1964 D.getMutableDeclSpec().ClearConstexprSpec();
1965 const char *PrevSpec;
1966 unsigned DiagID;
1967 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1968 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001969 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001970 assert(!Failed && "Making a constexpr member const shouldn't fail");
1971 } else {
1972 B << 1;
1973 const char *PrevSpec;
1974 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001975 if (D.getMutableDeclSpec().SetStorageClassSpec(
Stephen Hines651f13c2014-04-23 16:59:28 -07001976 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
1977 Context.getPrintingPolicy())) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001978 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001979 "This is the only DeclSpec that should fail to be applied");
1980 B << 1;
1981 } else {
1982 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1983 isInstField = false;
1984 }
1985 }
1986 }
1987
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001988 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001989 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001990 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001991
1992 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001993 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001994 Diag(Loc, diag::err_bad_variable_name)
1995 << Name;
1996 return 0;
1997 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001998
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001999 IdentifierInfo *II = Name.getAsIdentifierInfo();
2000
Douglas Gregorf2503652011-09-21 14:40:46 +00002001 // Member field could not be with "template" keyword.
2002 // So TemplateParameterLists should be empty in this case.
2003 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002004 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00002005 if (TemplateParams->size()) {
2006 // There is no such thing as a member field template.
2007 Diag(D.getIdentifierLoc(), diag::err_template_member)
2008 << II
2009 << SourceRange(TemplateParams->getTemplateLoc(),
2010 TemplateParams->getRAngleLoc());
2011 } else {
2012 // There is an extraneous 'template<>' for this member.
2013 Diag(TemplateParams->getTemplateLoc(),
2014 diag::err_template_member_noparams)
2015 << II
2016 << SourceRange(TemplateParams->getTemplateLoc(),
2017 TemplateParams->getRAngleLoc());
2018 }
2019 return 0;
2020 }
2021
Douglas Gregor922fff22010-10-13 22:19:53 +00002022 if (SS.isSet() && !SS.isInvalid()) {
2023 // The user provided a superfluous scope specifier inside a class
2024 // definition:
2025 //
2026 // class X {
2027 // int X::member;
2028 // };
Douglas Gregor69605872012-03-28 16:01:27 +00002029 if (DeclContext *DC = computeDeclContext(SS, false))
2030 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00002031 else
2032 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2033 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00002034
Douglas Gregor922fff22010-10-13 22:19:53 +00002035 SS.clear();
2036 }
Douglas Gregorf2503652011-09-21 14:40:46 +00002037
John McCall76da55d2013-04-16 07:28:30 +00002038 AttributeList *MSPropertyAttr =
2039 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00002040 if (MSPropertyAttr) {
2041 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2042 BitWidth, InitStyle, AS, MSPropertyAttr);
2043 if (!Member)
2044 return 0;
2045 isInstField = false;
2046 } else {
2047 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2048 BitWidth, InitStyle, AS);
2049 assert(Member && "HandleField never returns null");
2050 }
2051 } else {
2052 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2053
2054 Member = HandleDeclarator(S, D, TemplateParameterLists);
2055 if (!Member)
2056 return 0;
2057
2058 // Non-instance-fields can't have a bitfield.
2059 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002060 if (Member->isInvalidDecl()) {
2061 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00002062 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002063 // C++ 9.6p3: A bit-field shall not be a static member.
2064 // "static member 'A' cannot be a bit-field"
2065 Diag(Loc, diag::err_static_not_bitfield)
2066 << Name << BitWidth->getSourceRange();
2067 } else if (isa<TypedefDecl>(Member)) {
2068 // "typedef member 'x' cannot be a bit-field"
2069 Diag(Loc, diag::err_typedef_not_bitfield)
2070 << Name << BitWidth->getSourceRange();
2071 } else {
2072 // A function typedef ("typedef int f(); f a;").
2073 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2074 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00002075 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00002076 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00002077 }
Mike Stump1eb44332009-09-09 15:08:12 +00002078
Chris Lattner8b963ef2009-03-05 23:01:03 +00002079 BitWidth = 0;
2080 Member->setInvalidDecl();
2081 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00002082
2083 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Larisse Voufoef4579c2013-08-06 01:03:05 +00002085 // If we have declared a member function template or static data member
2086 // template, set the access of the templated declaration as well.
Douglas Gregor37b372b2009-08-20 22:52:58 +00002087 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2088 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002089 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2090 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002091 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002092
Richard Smitha4b39652012-08-06 03:25:17 +00002093 if (VS.isOverrideSpecified())
Stephen Hines651f13c2014-04-23 16:59:28 -07002094 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smitha4b39652012-08-06 03:25:17 +00002095 if (VS.isFinalSpecified())
David Majnemer7121bdb2013-10-18 00:33:31 +00002096 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2097 VS.isFinalSpelledSealed()));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002098
Douglas Gregorf5251602011-03-08 17:10:18 +00002099 if (VS.getLastLocation().isValid()) {
2100 // Update the end location of a method that has a virt-specifiers.
2101 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2102 MD->setRangeEnd(VS.getLastLocation());
2103 }
Richard Smitha4b39652012-08-06 03:25:17 +00002104
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002105 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002106
Douglas Gregor10bd3682008-11-17 22:58:34 +00002107 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002108
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002109 if (isInstField) {
2110 FieldDecl *FD = cast<FieldDecl>(Member);
2111 FieldCollector->Add(FD);
2112
2113 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2114 FD->getLocation())
2115 != DiagnosticsEngine::Ignored) {
2116 // Remember all explicit private FieldDecls that have a name, no side
2117 // effects and are not part of a dependent type declaration.
2118 if (!FD->isImplicit() && FD->getDeclName() &&
2119 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002120 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002121 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002122 !InitializationHasSideEffects(*FD))
2123 UnusedPrivateFields.insert(FD);
2124 }
2125 }
2126
John McCalld226f652010-08-21 09:40:31 +00002127 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002128}
2129
Hans Wennborg471f9852012-09-18 15:58:06 +00002130namespace {
2131 class UninitializedFieldVisitor
2132 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2133 Sema &S;
Richard Trieu858d2ba2013-10-25 00:56:00 +00002134 // List of Decls to generate a warning on. Also remove Decls that become
2135 // initialized.
Richard Trieuef8f90c2013-09-20 03:03:06 +00002136 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002137 // If non-null, add a note to the warning pointing back to the constructor.
2138 const CXXConstructorDecl *Constructor;
Hans Wennborg471f9852012-09-18 15:58:06 +00002139 public:
2140 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieu858d2ba2013-10-25 00:56:00 +00002141 UninitializedFieldVisitor(Sema &S,
Richard Trieuef8f90c2013-09-20 03:03:06 +00002142 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
Richard Trieuef8f90c2013-09-20 03:03:06 +00002143 const CXXConstructorDecl *Constructor)
Richard Trieu858d2ba2013-10-25 00:56:00 +00002144 : Inherited(S.Context), S(S), Decls(Decls),
2145 Constructor(Constructor) { }
Hans Wennborg471f9852012-09-18 15:58:06 +00002146
Richard Trieu3ddec882013-09-16 20:46:50 +00002147 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieufbb08b52013-09-13 03:20:53 +00002148 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2149 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002150
Richard Trieufbb08b52013-09-13 03:20:53 +00002151 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2152 // or union.
2153 MemberExpr *FieldME = ME;
2154
2155 Expr *Base = ME;
2156 while (isa<MemberExpr>(Base)) {
2157 ME = cast<MemberExpr>(Base);
2158
2159 if (isa<VarDecl>(ME->getMemberDecl()))
2160 return;
2161
2162 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2163 if (!FD->isAnonymousStructOrUnion())
2164 FieldME = ME;
2165
2166 Base = ME->getBase();
2167 }
2168
Richard Trieu3ddec882013-09-16 20:46:50 +00002169 if (!isa<CXXThisExpr>(Base))
2170 return;
2171
Richard Trieuef8f90c2013-09-20 03:03:06 +00002172 ValueDecl* FoundVD = FieldME->getMemberDecl();
2173
Richard Trieu858d2ba2013-10-25 00:56:00 +00002174 if (!Decls.count(FoundVD))
Richard Trieuef8f90c2013-09-20 03:03:06 +00002175 return;
2176
Richard Trieu858d2ba2013-10-25 00:56:00 +00002177 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieuef8f90c2013-09-20 03:03:06 +00002178
Richard Trieu858d2ba2013-10-25 00:56:00 +00002179 // Prevent double warnings on use of unbounded references.
2180 if (IsReference != CheckReferenceOnly)
2181 return;
2182
2183 unsigned diag = IsReference
2184 ? diag::warn_reference_field_is_uninit
2185 : diag::warn_field_is_uninit;
2186 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2187 if (Constructor)
2188 S.Diag(Constructor->getLocation(),
2189 diag::note_uninit_in_this_constructor)
2190 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2191
Hans Wennborg471f9852012-09-18 15:58:06 +00002192 }
2193
2194 void HandleValue(Expr *E) {
2195 E = E->IgnoreParens();
2196
2197 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu3ddec882013-09-16 20:46:50 +00002198 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002199 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002200 }
2201
2202 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2203 HandleValue(CO->getTrueExpr());
2204 HandleValue(CO->getFalseExpr());
2205 return;
2206 }
2207
2208 if (BinaryConditionalOperator *BCO =
2209 dyn_cast<BinaryConditionalOperator>(E)) {
2210 HandleValue(BCO->getCommon());
2211 HandleValue(BCO->getFalseExpr());
2212 return;
2213 }
2214
2215 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2216 switch (BO->getOpcode()) {
2217 default:
2218 return;
2219 case(BO_PtrMemD):
2220 case(BO_PtrMemI):
2221 HandleValue(BO->getLHS());
2222 return;
2223 case(BO_Comma):
2224 HandleValue(BO->getRHS());
2225 return;
2226 }
2227 }
2228 }
2229
Richard Trieufbb08b52013-09-13 03:20:53 +00002230 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieu858d2ba2013-10-25 00:56:00 +00002231 // All uses of unbounded reference fields will warn.
Richard Trieu3ddec882013-09-16 20:46:50 +00002232 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002233
2234 Inherited::VisitMemberExpr(ME);
2235 }
2236
Hans Wennborg471f9852012-09-18 15:58:06 +00002237 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2238 if (E->getCastKind() == CK_LValueToRValue)
2239 HandleValue(E->getSubExpr());
2240
2241 Inherited::VisitImplicitCastExpr(E);
2242 }
2243
Richard Trieufbb08b52013-09-13 03:20:53 +00002244 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieuef8f90c2013-09-20 03:03:06 +00002245 if (E->getConstructor()->isCopyConstructor())
Richard Trieufbb08b52013-09-13 03:20:53 +00002246 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2247 if (ICE->getCastKind() == CK_NoOp)
2248 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieu3ddec882013-09-16 20:46:50 +00002249 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002250
2251 Inherited::VisitCXXConstructExpr(E);
2252 }
2253
Hans Wennborg471f9852012-09-18 15:58:06 +00002254 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2255 Expr *Callee = E->getCallee();
2256 if (isa<MemberExpr>(Callee))
2257 HandleValue(Callee);
2258
2259 Inherited::VisitCXXMemberCallExpr(E);
2260 }
Richard Trieuef8f90c2013-09-20 03:03:06 +00002261
2262 void VisitBinaryOperator(BinaryOperator *E) {
2263 // If a field assignment is detected, remove the field from the
2264 // uninitiailized field set.
2265 if (E->getOpcode() == BO_Assign)
2266 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2267 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieu858d2ba2013-10-25 00:56:00 +00002268 if (!FD->getType()->isReferenceType())
2269 Decls.erase(FD);
Richard Trieuef8f90c2013-09-20 03:03:06 +00002270
2271 Inherited::VisitBinaryOperator(E);
2272 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002273 };
Richard Trieuef8f90c2013-09-20 03:03:06 +00002274 static void CheckInitExprContainsUninitializedFields(
Richard Trieu858d2ba2013-10-25 00:56:00 +00002275 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2276 const CXXConstructorDecl *Constructor) {
2277 if (Decls.size() == 0)
Richard Trieuef8f90c2013-09-20 03:03:06 +00002278 return;
2279
Richard Trieu858d2ba2013-10-25 00:56:00 +00002280 if (!E)
2281 return;
2282
2283 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2284 E = Default->getExpr();
2285 if (!E)
2286 return;
2287 // In class initializers will point to the constructor.
2288 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2289 } else {
2290 UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2291 }
2292 }
2293
2294 // Diagnose value-uses of fields to initialize themselves, e.g.
2295 // foo(foo)
2296 // where foo is not also a parameter to the constructor.
2297 // Also diagnose across field uninitialized use such as
2298 // x(y), y(x)
2299 // TODO: implement -Wuninitialized and fold this into that framework.
2300 static void DiagnoseUninitializedFields(
2301 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2302
2303 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2304 Constructor->getLocation())
2305 == DiagnosticsEngine::Ignored) {
2306 return;
2307 }
2308
2309 if (Constructor->isInvalidDecl())
2310 return;
2311
2312 const CXXRecordDecl *RD = Constructor->getParent();
2313
2314 // Holds fields that are uninitialized.
2315 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2316
2317 // At the beginning, all fields are uninitialized.
Stephen Hines651f13c2014-04-23 16:59:28 -07002318 for (auto *I : RD->decls()) {
2319 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieu858d2ba2013-10-25 00:56:00 +00002320 UninitializedFields.insert(FD);
Stephen Hines651f13c2014-04-23 16:59:28 -07002321 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieu858d2ba2013-10-25 00:56:00 +00002322 UninitializedFields.insert(IFD->getAnonField());
2323 }
2324 }
2325
Stephen Hines651f13c2014-04-23 16:59:28 -07002326 for (const auto *FieldInit : Constructor->inits()) {
2327 Expr *InitExpr = FieldInit->getInit();
Richard Trieu858d2ba2013-10-25 00:56:00 +00002328
2329 CheckInitExprContainsUninitializedFields(
2330 SemaRef, InitExpr, UninitializedFields, Constructor);
2331
Stephen Hines651f13c2014-04-23 16:59:28 -07002332 if (FieldDecl *Field = FieldInit->getAnyMember())
Richard Trieu858d2ba2013-10-25 00:56:00 +00002333 UninitializedFields.erase(Field);
2334 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002335 }
2336} // namespace
2337
Stephen Hines651f13c2014-04-23 16:59:28 -07002338/// \brief Enter a new C++ default initializer scope. After calling this, the
2339/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2340/// parsing or instantiating the initializer failed.
2341void Sema::ActOnStartCXXInClassMemberInitializer() {
2342 // Create a synthetic function scope to represent the call to the constructor
2343 // that notionally surrounds a use of this initializer.
2344 PushFunctionScope();
2345}
2346
2347/// \brief This is invoked after parsing an in-class initializer for a
2348/// non-static C++ class member, and after instantiating an in-class initializer
2349/// in a class template. Such actions are deferred until the class is complete.
2350void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2351 SourceLocation InitLoc,
2352 Expr *InitExpr) {
2353 // Pop the notional constructor scope we created earlier.
2354 PopFunctionScopeInfo(0, D);
2355
Richard Smith7a614d82011-06-11 17:19:42 +00002356 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002357 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2358 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002359
2360 if (!InitExpr) {
2361 FD->setInvalidDecl();
2362 FD->removeInClassInitializer();
2363 return;
2364 }
2365
Peter Collingbournefef21892011-10-23 18:59:44 +00002366 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2367 FD->setInvalidDecl();
2368 FD->removeInClassInitializer();
2369 return;
2370 }
2371
Richard Smith7a614d82011-06-11 17:19:42 +00002372 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002373 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002374 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002375 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002376 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002377 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002378 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2379 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002380 if (Init.isInvalid()) {
2381 FD->setInvalidDecl();
2382 return;
2383 }
Richard Smith7a614d82011-06-11 17:19:42 +00002384 }
2385
Richard Smith41956372013-01-14 22:39:08 +00002386 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002387 // The initialization of each base and member constitutes a
2388 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002389 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002390 if (Init.isInvalid()) {
2391 FD->setInvalidDecl();
2392 return;
2393 }
2394
2395 InitExpr = Init.release();
2396
2397 FD->setInClassInitializer(InitExpr);
2398}
2399
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002400/// \brief Find the direct and/or virtual base specifiers that
2401/// correspond to the given base type, for use in base initialization
2402/// within a constructor.
2403static bool FindBaseInitializer(Sema &SemaRef,
2404 CXXRecordDecl *ClassDecl,
2405 QualType BaseType,
2406 const CXXBaseSpecifier *&DirectBaseSpec,
2407 const CXXBaseSpecifier *&VirtualBaseSpec) {
2408 // First, check for a direct base class.
2409 DirectBaseSpec = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -07002410 for (const auto &Base : ClassDecl->bases()) {
2411 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002412 // We found a direct base of this type. That's what we're
2413 // initializing.
Stephen Hines651f13c2014-04-23 16:59:28 -07002414 DirectBaseSpec = &Base;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002415 break;
2416 }
2417 }
2418
2419 // Check for a virtual base class.
2420 // FIXME: We might be able to short-circuit this if we know in advance that
2421 // there are no virtual bases.
2422 VirtualBaseSpec = 0;
2423 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2424 // We haven't found a base yet; search the class hierarchy for a
2425 // virtual base class.
2426 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2427 /*DetectVirtual=*/false);
2428 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2429 BaseType, Paths)) {
2430 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2431 Path != Paths.end(); ++Path) {
2432 if (Path->back().Base->isVirtual()) {
2433 VirtualBaseSpec = Path->back().Base;
2434 break;
2435 }
2436 }
2437 }
2438 }
2439
2440 return DirectBaseSpec || VirtualBaseSpec;
2441}
2442
Sebastian Redl6df65482011-09-24 17:48:25 +00002443/// \brief Handle a C++ member initializer using braced-init-list syntax.
2444MemInitResult
2445Sema::ActOnMemInitializer(Decl *ConstructorD,
2446 Scope *S,
2447 CXXScopeSpec &SS,
2448 IdentifierInfo *MemberOrBase,
2449 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002450 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002451 SourceLocation IdLoc,
2452 Expr *InitList,
2453 SourceLocation EllipsisLoc) {
2454 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002455 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002456 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002457}
2458
2459/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002460MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002461Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002462 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002463 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002464 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002465 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002466 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002467 SourceLocation IdLoc,
2468 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002469 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002470 SourceLocation RParenLoc,
2471 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002472 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002473 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002474 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002475 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002476}
2477
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002478namespace {
2479
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002480// Callback to only accept typo corrections that can be a valid C++ member
2481// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002482class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002483public:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002484 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2485 : ClassDecl(ClassDecl) {}
2486
Stephen Hines651f13c2014-04-23 16:59:28 -07002487 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002488 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2489 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2490 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002491 return isa<TypeDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002492 }
2493 return false;
2494 }
2495
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002496private:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002497 CXXRecordDecl *ClassDecl;
2498};
2499
2500}
2501
Sebastian Redl6df65482011-09-24 17:48:25 +00002502/// \brief Handle a C++ member initializer.
2503MemInitResult
2504Sema::BuildMemInitializer(Decl *ConstructorD,
2505 Scope *S,
2506 CXXScopeSpec &SS,
2507 IdentifierInfo *MemberOrBase,
2508 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002509 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002510 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002511 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002512 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002513 if (!ConstructorD)
2514 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002515
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002516 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002517
2518 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002519 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002520 if (!Constructor) {
2521 // The user wrote a constructor initializer on a function that is
2522 // not a C++ constructor. Ignore the error for now, because we may
2523 // have more member initializers coming; we'll diagnose it just
2524 // once in ActOnMemInitializers.
2525 return true;
2526 }
2527
2528 CXXRecordDecl *ClassDecl = Constructor->getParent();
2529
2530 // C++ [class.base.init]p2:
2531 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002532 // constructor's class and, if not found in that scope, are looked
2533 // up in the scope containing the constructor's definition.
2534 // [Note: if the constructor's class contains a member with the
2535 // same name as a direct or virtual base class of the class, a
2536 // mem-initializer-id naming the member or base class and composed
2537 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002538 // mem-initializer-id for the hidden base class may be specified
2539 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002540 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002541 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002542 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002543 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002544 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002545 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002546 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2547 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002548 if (EllipsisLoc.isValid())
2549 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002550 << MemberOrBase
2551 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002552
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002553 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002554 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002555 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002556 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002557 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002558 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002559 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002560
2561 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002562 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002563 } else if (DS.getTypeSpecType() == TST_decltype) {
2564 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002565 } else {
2566 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2567 LookupParsedName(R, S, &SS);
2568
2569 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2570 if (!TyD) {
2571 if (R.isAmbiguous()) return true;
2572
John McCallfd225442010-04-09 19:01:14 +00002573 // We don't want access-control diagnostics here.
2574 R.suppressDiagnostics();
2575
Douglas Gregor7a886e12010-01-19 06:46:48 +00002576 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2577 bool NotUnknownSpecialization = false;
2578 DeclContext *DC = computeDeclContext(SS, false);
2579 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2580 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2581
2582 if (!NotUnknownSpecialization) {
2583 // When the scope specifier can refer to a member of an unknown
2584 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002585 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2586 SS.getWithLocInContext(Context),
2587 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002588 if (BaseType.isNull())
2589 return true;
2590
Douglas Gregor7a886e12010-01-19 06:46:48 +00002591 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002592 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002593 }
2594 }
2595
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002596 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002597 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002598 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002599 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002600 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002601 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002602 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002603 // We have found a non-static data member with a similar
2604 // name to what was typed; complain and initialize that
2605 // member.
Richard Smith2d670972013-08-17 00:46:16 +00002606 diagnoseTypo(Corr,
2607 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2608 << MemberOrBase << true);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002609 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002610 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002611 const CXXBaseSpecifier *DirectBaseSpec;
2612 const CXXBaseSpecifier *VirtualBaseSpec;
2613 if (FindBaseInitializer(*this, ClassDecl,
2614 Context.getTypeDeclType(Type),
2615 DirectBaseSpec, VirtualBaseSpec)) {
2616 // We have found a direct or virtual base class with a
2617 // similar name to what was typed; complain and initialize
2618 // that base class.
Richard Smith2d670972013-08-17 00:46:16 +00002619 diagnoseTypo(Corr,
2620 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2621 << MemberOrBase << false,
2622 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002623
Richard Smith2d670972013-08-17 00:46:16 +00002624 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2625 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002626 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002627 diag::note_base_class_specified_here)
2628 << BaseSpec->getType()
2629 << BaseSpec->getSourceRange();
2630
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002631 TyD = Type;
2632 }
2633 }
2634 }
2635
Douglas Gregor7a886e12010-01-19 06:46:48 +00002636 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002637 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002638 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002639 return true;
2640 }
John McCall2b194412009-12-21 10:41:20 +00002641 }
2642
Douglas Gregor7a886e12010-01-19 06:46:48 +00002643 if (BaseType.isNull()) {
2644 BaseType = Context.getTypeDeclType(TyD);
Stephen Hines651f13c2014-04-23 16:59:28 -07002645 if (SS.isSet())
Douglas Gregor7a886e12010-01-19 06:46:48 +00002646 // FIXME: preserve source range information
Stephen Hines651f13c2014-04-23 16:59:28 -07002647 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2648 BaseType);
John McCall2b194412009-12-21 10:41:20 +00002649 }
2650 }
Mike Stump1eb44332009-09-09 15:08:12 +00002651
John McCalla93c9342009-12-07 02:54:59 +00002652 if (!TInfo)
2653 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002654
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002655 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002656}
2657
Chandler Carruth81c64772011-09-03 01:14:15 +00002658/// Checks a member initializer expression for cases where reference (or
2659/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002660static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2661 Expr *Init,
2662 SourceLocation IdLoc) {
2663 QualType MemberTy = Member->getType();
2664
2665 // We only handle pointers and references currently.
2666 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2667 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2668 return;
2669
2670 const bool IsPointer = MemberTy->isPointerType();
2671 if (IsPointer) {
2672 if (const UnaryOperator *Op
2673 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2674 // The only case we're worried about with pointers requires taking the
2675 // address.
2676 if (Op->getOpcode() != UO_AddrOf)
2677 return;
2678
2679 Init = Op->getSubExpr();
2680 } else {
2681 // We only handle address-of expression initializers for pointers.
2682 return;
2683 }
2684 }
2685
Richard Smitha4bb99c2013-06-12 21:51:50 +00002686 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002687 // We only warn when referring to a non-reference parameter declaration.
2688 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2689 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002690 return;
2691
2692 S.Diag(Init->getExprLoc(),
2693 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2694 : diag::warn_bind_ref_member_to_parameter)
2695 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002696 } else {
2697 // Other initializers are fine.
2698 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002699 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002700
2701 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2702 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002703}
2704
John McCallf312b1e2010-08-26 23:41:50 +00002705MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002706Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002707 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002708 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2709 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2710 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002711 "Member must be a FieldDecl or IndirectFieldDecl");
2712
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002713 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002714 return true;
2715
Douglas Gregor464b2f02010-11-05 22:21:31 +00002716 if (Member->isInvalidDecl())
2717 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002718
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002719 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002720 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002721 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002722 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002723 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002724 } else {
2725 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002726 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002727 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002728
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002729 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002730
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002731 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002732 // Can't check initialization for a member of dependent type or when
2733 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002734 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002735 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002736 bool InitList = false;
2737 if (isa<InitListExpr>(Init)) {
2738 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002739 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002740 }
2741
Chandler Carruth894aed92010-12-06 09:23:57 +00002742 // Initialize the member.
2743 InitializedEntity MemberEntity =
2744 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2745 : InitializedEntity::InitializeMember(IndirectMember, 0);
2746 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002747 InitList ? InitializationKind::CreateDirectList(IdLoc)
2748 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2749 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002750
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002751 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2752 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002753 if (MemberInit.isInvalid())
2754 return true;
2755
Richard Smith8a07cd32013-06-12 20:42:33 +00002756 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2757
Richard Smith41956372013-01-14 22:39:08 +00002758 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002759 // The initialization of each base and member constitutes a
2760 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002761 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002762 if (MemberInit.isInvalid())
2763 return true;
2764
Richard Smithc83c2302012-12-19 01:39:02 +00002765 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002766 }
2767
Chandler Carruth894aed92010-12-06 09:23:57 +00002768 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002769 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2770 InitRange.getBegin(), Init,
2771 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002772 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002773 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2774 InitRange.getBegin(), Init,
2775 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002776 }
Eli Friedman59c04372009-07-29 19:44:27 +00002777}
2778
John McCallf312b1e2010-08-26 23:41:50 +00002779MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002780Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002781 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002782 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002783 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002784 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002785 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002786 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002787
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002788 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002789 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002790 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2791 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002792 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002793 }
2794
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002795 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002796 // Initialize the object.
2797 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2798 QualType(ClassDecl->getTypeForDecl(), 0));
2799 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002800 InitList ? InitializationKind::CreateDirectList(NameLoc)
2801 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2802 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002803 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002804 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002805 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002806 if (DelegationInit.isInvalid())
2807 return true;
2808
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002809 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2810 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002811
Richard Smith41956372013-01-14 22:39:08 +00002812 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002813 // The initialization of each base and member constitutes a
2814 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002815 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2816 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002817 if (DelegationInit.isInvalid())
2818 return true;
2819
Eli Friedmand21016f2012-05-19 23:35:23 +00002820 // If we are in a dependent context, template instantiation will
2821 // perform this type-checking again. Just save the arguments that we
2822 // received in a ParenListExpr.
2823 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2824 // of the information that we have about the base
2825 // initializer. However, deconstructing the ASTs is a dicey process,
2826 // and this approach is far more likely to get the corner cases right.
2827 if (CurContext->isDependentContext())
2828 DelegationInit = Owned(Init);
2829
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002830 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002831 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002832 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002833}
2834
2835MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002836Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002837 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002838 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002839 SourceLocation BaseLoc
2840 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002841
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002842 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2843 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2844 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2845
2846 // C++ [class.base.init]p2:
2847 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002848 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002849 // of that class, the mem-initializer is ill-formed. A
2850 // mem-initializer-list can initialize a base class using any
2851 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002852 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002853
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002854 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002855 if (EllipsisLoc.isValid()) {
2856 // This is a pack expansion.
2857 if (!BaseType->containsUnexpandedParameterPack()) {
2858 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002859 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002860
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002861 EllipsisLoc = SourceLocation();
2862 }
2863 } else {
2864 // Check for any unexpanded parameter packs.
2865 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2866 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002867
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002868 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002869 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002870 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002871
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002872 // Check for direct and virtual base classes.
2873 const CXXBaseSpecifier *DirectBaseSpec = 0;
2874 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2875 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002876 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2877 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002878 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002879
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002880 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2881 VirtualBaseSpec);
2882
2883 // C++ [base.class.init]p2:
2884 // Unless the mem-initializer-id names a nonstatic data member of the
2885 // constructor's class or a direct or virtual base of that class, the
2886 // mem-initializer is ill-formed.
2887 if (!DirectBaseSpec && !VirtualBaseSpec) {
2888 // If the class has any dependent bases, then it's possible that
2889 // one of those types will resolve to the same type as
2890 // BaseType. Therefore, just treat this as a dependent base
2891 // class initialization. FIXME: Should we try to check the
2892 // initialization anyway? It seems odd.
2893 if (ClassDecl->hasAnyDependentBases())
2894 Dependent = true;
2895 else
2896 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2897 << BaseType << Context.getTypeDeclType(ClassDecl)
2898 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2899 }
2900 }
2901
2902 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002903 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002904
Sebastian Redl6df65482011-09-24 17:48:25 +00002905 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2906 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002907 InitRange.getBegin(), Init,
2908 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002909 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002910
2911 // C++ [base.class.init]p2:
2912 // If a mem-initializer-id is ambiguous because it designates both
2913 // a direct non-virtual base class and an inherited virtual base
2914 // class, the mem-initializer is ill-formed.
2915 if (DirectBaseSpec && VirtualBaseSpec)
2916 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002917 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002918
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002919 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002920 if (!BaseSpec)
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002921 BaseSpec = VirtualBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002922
2923 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002924 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002925 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002926 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002927 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002928 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002929 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002930
2931 InitializedEntity BaseEntity =
2932 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2933 InitializationKind Kind =
2934 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2935 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2936 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002937 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2938 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002939 if (BaseInit.isInvalid())
2940 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002941
Richard Smith41956372013-01-14 22:39:08 +00002942 // C++11 [class.base.init]p7:
2943 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002944 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002945 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002946 if (BaseInit.isInvalid())
2947 return true;
2948
2949 // If we are in a dependent context, template instantiation will
2950 // perform this type-checking again. Just save the arguments that we
2951 // received in a ParenListExpr.
2952 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2953 // of the information that we have about the base
2954 // initializer. However, deconstructing the ASTs is a dicey process,
2955 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002956 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002957 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002958
Sean Huntcbb67482011-01-08 20:30:50 +00002959 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002960 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002961 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002962 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002963 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002964}
2965
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002966// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002967static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2968 if (T.isNull()) T = E->getType();
2969 QualType TargetType = SemaRef.BuildReferenceType(
2970 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002971 SourceLocation ExprLoc = E->getLocStart();
2972 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2973 TargetType, ExprLoc);
2974
2975 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2976 SourceRange(ExprLoc, ExprLoc),
2977 E->getSourceRange()).take();
2978}
2979
Anders Carlssone5ef7402010-04-23 03:10:23 +00002980/// ImplicitInitializerKind - How an implicit base or member initializer should
2981/// initialize its base or member.
2982enum ImplicitInitializerKind {
2983 IIK_Default,
2984 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002985 IIK_Move,
2986 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002987};
2988
Anders Carlssondefefd22010-04-23 02:00:02 +00002989static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002990BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002991 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002992 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002993 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002994 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002995 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002996 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2997 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002998
John McCall60d7b3a2010-08-24 06:29:42 +00002999 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00003000
3001 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00003002 case IIK_Inherit: {
3003 const CXXRecordDecl *Inherited =
3004 Constructor->getInheritedConstructor()->getParent();
3005 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3006 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3007 // C++11 [class.inhctor]p8:
3008 // Each expression in the expression-list is of the form
3009 // static_cast<T&&>(p), where p is the name of the corresponding
3010 // constructor parameter and T is the declared type of p.
3011 SmallVector<Expr*, 16> Args;
3012 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3013 ParmVarDecl *PD = Constructor->getParamDecl(I);
3014 ExprResult ArgExpr =
3015 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3016 VK_LValue, SourceLocation());
3017 if (ArgExpr.isInvalid())
3018 return true;
3019 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3020 }
3021
3022 InitializationKind InitKind = InitializationKind::CreateDirect(
3023 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003024 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00003025 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3026 break;
3027 }
3028 }
3029 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00003030 case IIK_Default: {
3031 InitializationKind InitKind
3032 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003033 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3034 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003035 break;
3036 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003037
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003038 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00003039 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003040 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00003041 ParmVarDecl *Param = Constructor->getParamDecl(0);
3042 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00003043
Anders Carlssone5ef7402010-04-23 03:10:23 +00003044 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003045 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00003046 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00003047 Constructor->getLocation(), ParamType,
3048 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003049
Eli Friedman5f2987c2012-02-02 03:46:19 +00003050 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3051
Anders Carlssonc7957502010-04-24 22:02:54 +00003052 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00003053 QualType ArgTy =
3054 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3055 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00003056
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003057 if (Moving) {
3058 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3059 }
3060
John McCallf871d0c2010-08-07 06:22:56 +00003061 CXXCastPath BasePath;
3062 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00003063 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3064 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003065 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003066 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00003067
Anders Carlssone5ef7402010-04-23 03:10:23 +00003068 InitializationKind InitKind
3069 = InitializationKind::CreateDirect(Constructor->getLocation(),
3070 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003071 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3072 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003073 break;
3074 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00003075 }
John McCall9ae2f072010-08-23 23:25:46 +00003076
Douglas Gregor53c374f2010-12-07 00:41:46 +00003077 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00003078 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00003079 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00003080
Anders Carlssondefefd22010-04-23 02:00:02 +00003081 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00003082 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00003083 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3084 SourceLocation()),
3085 BaseSpec->isVirtual(),
3086 SourceLocation(),
3087 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003088 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00003089 SourceLocation());
3090
Anders Carlssondefefd22010-04-23 02:00:02 +00003091 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00003092}
3093
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003094static bool RefersToRValueRef(Expr *MemRef) {
3095 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3096 return Referenced->getType()->isRValueReferenceType();
3097}
3098
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003099static bool
3100BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003101 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003102 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00003103 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003104 if (Field->isInvalidDecl())
3105 return true;
3106
Chandler Carruthf186b542010-06-29 23:50:44 +00003107 SourceLocation Loc = Constructor->getLocation();
3108
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003109 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3110 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003111 ParmVarDecl *Param = Constructor->getParamDecl(0);
3112 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00003113
3114 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003115 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3116 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00003117
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003118 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003119 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00003120 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00003121 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003122
Eli Friedman5f2987c2012-02-02 03:46:19 +00003123 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3124
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003125 if (Moving) {
3126 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3127 }
3128
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003129 // Build a reference to this field within the parameter.
3130 CXXScopeSpec SS;
3131 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3132 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003133 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3134 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003135 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00003136 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00003137 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003138 ParamType, Loc,
3139 /*IsArrow=*/false,
3140 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003141 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003142 /*FirstQualifierInScope=*/0,
3143 MemberLookup,
3144 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003145 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003146 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003147
3148 // C++11 [class.copy]p15:
3149 // - if a member m has rvalue reference type T&&, it is direct-initialized
3150 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003151 if (RefersToRValueRef(CtorArg.get())) {
3152 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003153 }
3154
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003155 // When the field we are copying is an array, create index variables for
3156 // each dimension of the array. We use these index variables to subscript
3157 // the source array, and other clients (e.g., CodeGen) will perform the
3158 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003159 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003160 QualType BaseType = Field->getType();
3161 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003162 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003163 while (const ConstantArrayType *Array
3164 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003165 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003166 // Create the iteration variable for this array index.
3167 IdentifierInfo *IterationVarName = 0;
3168 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003169 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003170 llvm::raw_svector_ostream OS(Str);
3171 OS << "__i" << IndexVariables.size();
3172 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3173 }
3174 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003175 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003176 IterationVarName, SizeType,
3177 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003178 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003179 IndexVariables.push_back(IterationVar);
3180
3181 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003182 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003183 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003184 assert(!IterationVarRef.isInvalid() &&
3185 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003186 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3187 assert(!IterationVarRef.isInvalid() &&
3188 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003189
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003190 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003191 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003192 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003193 Loc);
3194 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003195 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003196
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003197 BaseType = Array->getElementType();
3198 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003199
3200 // The array subscript expression is an lvalue, which is wrong for moving.
3201 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003202 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003203
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003204 // Construct the entity that we will be initializing. For an array, this
3205 // will be first element in the array, which may require several levels
3206 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003207 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003208 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003209 if (Indirect)
3210 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3211 else
3212 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003213 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3214 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3215 0,
3216 Entities.back()));
3217
3218 // Direct-initialize to use the copy constructor.
3219 InitializationKind InitKind =
3220 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3221
Sebastian Redl74e611a2011-09-04 18:14:28 +00003222 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003223 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003224
John McCall60d7b3a2010-08-24 06:29:42 +00003225 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003226 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003227 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003228 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003229 if (MemberInit.isInvalid())
3230 return true;
3231
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003232 if (Indirect) {
3233 assert(IndexVariables.size() == 0 &&
3234 "Indirect field improperly initialized");
3235 CXXMemberInit
3236 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3237 Loc, Loc,
3238 MemberInit.takeAs<Expr>(),
3239 Loc);
3240 } else
3241 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3242 Loc, MemberInit.takeAs<Expr>(),
3243 Loc,
3244 IndexVariables.data(),
3245 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003246 return false;
3247 }
3248
Richard Smith07b0fdc2013-03-18 21:12:30 +00003249 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3250 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003251
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003252 QualType FieldBaseElementType =
3253 SemaRef.Context.getBaseElementType(Field->getType());
3254
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003255 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003256 InitializedEntity InitEntity
3257 = Indirect? InitializedEntity::InitializeMember(Indirect)
3258 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003259 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003260 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003261
3262 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3263 ExprResult MemberInit =
3264 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003265
Douglas Gregor53c374f2010-12-07 00:41:46 +00003266 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003267 if (MemberInit.isInvalid())
3268 return true;
3269
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003270 if (Indirect)
3271 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3272 Indirect, Loc,
3273 Loc,
3274 MemberInit.get(),
3275 Loc);
3276 else
3277 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3278 Field, Loc, Loc,
3279 MemberInit.get(),
3280 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003281 return false;
3282 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003283
Sean Hunt1f2f3842011-05-17 00:19:05 +00003284 if (!Field->getParent()->isUnion()) {
3285 if (FieldBaseElementType->isReferenceType()) {
3286 SemaRef.Diag(Constructor->getLocation(),
3287 diag::err_uninitialized_member_in_ctor)
3288 << (int)Constructor->isImplicit()
3289 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3290 << 0 << Field->getDeclName();
3291 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3292 return true;
3293 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003294
Sean Hunt1f2f3842011-05-17 00:19:05 +00003295 if (FieldBaseElementType.isConstQualified()) {
3296 SemaRef.Diag(Constructor->getLocation(),
3297 diag::err_uninitialized_member_in_ctor)
3298 << (int)Constructor->isImplicit()
3299 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3300 << 1 << Field->getDeclName();
3301 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3302 return true;
3303 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003304 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003305
David Blaikie4e4d0842012-03-11 07:00:24 +00003306 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003307 FieldBaseElementType->isObjCRetainableType() &&
3308 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3309 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003310 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003311 // Default-initialize Objective-C pointers to NULL.
3312 CXXMemberInit
3313 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3314 Loc, Loc,
3315 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3316 Loc);
3317 return false;
3318 }
3319
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003320 // Nothing to initialize.
3321 CXXMemberInit = 0;
3322 return false;
3323}
John McCallf1860e52010-05-20 23:23:51 +00003324
3325namespace {
3326struct BaseAndFieldInfo {
3327 Sema &S;
3328 CXXConstructorDecl *Ctor;
3329 bool AnyErrorsInInits;
3330 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003331 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003332 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Stephen Hines651f13c2014-04-23 16:59:28 -07003333 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallf1860e52010-05-20 23:23:51 +00003334
3335 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3336 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003337 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3338 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003339 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003340 else if (Generated && Ctor->isMoveConstructor())
3341 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003342 else if (Ctor->getInheritedConstructor())
3343 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003344 else
3345 IIK = IIK_Default;
3346 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003347
3348 bool isImplicitCopyOrMove() const {
3349 switch (IIK) {
3350 case IIK_Copy:
3351 case IIK_Move:
3352 return true;
3353
3354 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003355 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003356 return false;
3357 }
David Blaikie30263482012-01-20 21:50:17 +00003358
3359 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003360 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003361
3362 bool addFieldInitializer(CXXCtorInitializer *Init) {
3363 AllToInit.push_back(Init);
3364
3365 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003366 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003367 S.UnusedPrivateFields.remove(Init->getAnyMember());
3368
3369 return false;
3370 }
John McCallf1860e52010-05-20 23:23:51 +00003371
Stephen Hines651f13c2014-04-23 16:59:28 -07003372 bool isInactiveUnionMember(FieldDecl *Field) {
3373 RecordDecl *Record = Field->getParent();
3374 if (!Record->isUnion())
3375 return false;
3376
3377 if (FieldDecl *Active =
3378 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3379 return Active != Field->getCanonicalDecl();
3380
3381 // In an implicit copy or move constructor, ignore any in-class initializer.
3382 if (isImplicitCopyOrMove())
3383 return true;
3384
3385 // If there's no explicit initialization, the field is active only if it
3386 // has an in-class initializer...
3387 if (Field->hasInClassInitializer())
3388 return false;
3389 // ... or it's an anonymous struct or union whose class has an in-class
3390 // initializer.
3391 if (!Field->isAnonymousStructOrUnion())
3392 return true;
3393 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3394 return !FieldRD->hasInClassInitializer();
3395 }
3396
3397 /// \brief Determine whether the given field is, or is within, a union member
3398 /// that is inactive (because there was an initializer given for a different
3399 /// member of the union, or because the union was not initialized at all).
3400 bool isWithinInactiveUnionMember(FieldDecl *Field,
3401 IndirectFieldDecl *Indirect) {
3402 if (!Indirect)
3403 return isInactiveUnionMember(Field);
3404
3405 for (auto *C : Indirect->chain()) {
3406 FieldDecl *Field = dyn_cast<FieldDecl>(C);
3407 if (Field && isInactiveUnionMember(Field))
Richard Smitha4950662011-09-19 13:34:43 +00003408 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07003409 }
3410 return false;
3411 }
3412};
Richard Smitha4950662011-09-19 13:34:43 +00003413}
3414
Douglas Gregorddb21472011-11-02 23:04:16 +00003415/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3416/// array type.
3417static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3418 if (T->isIncompleteArrayType())
3419 return true;
3420
3421 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3422 if (!ArrayT->getSize())
3423 return true;
3424
3425 T = ArrayT->getElementType();
3426 }
3427
3428 return false;
3429}
3430
Richard Smith7a614d82011-06-11 17:19:42 +00003431static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003432 FieldDecl *Field,
3433 IndirectFieldDecl *Indirect = 0) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003434 if (Field->isInvalidDecl())
3435 return false;
John McCallf1860e52010-05-20 23:23:51 +00003436
Chandler Carruthe861c602010-06-30 02:59:29 +00003437 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003438 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3439 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003440
Stephen Hines651f13c2014-04-23 16:59:28 -07003441 // C++11 [class.base.init]p8:
3442 // if the entity is a non-static data member that has a
3443 // brace-or-equal-initializer and either
3444 // -- the constructor's class is a union and no other variant member of that
3445 // union is designated by a mem-initializer-id or
3446 // -- the constructor's class is not a union, and, if the entity is a member
3447 // of an anonymous union, no other member of that union is designated by
3448 // a mem-initializer-id,
3449 // the entity is initialized as specified in [dcl.init].
3450 //
3451 // We also apply the same rules to handle anonymous structs within anonymous
3452 // unions.
3453 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3454 return false;
3455
Douglas Gregorf4853882011-11-28 20:03:15 +00003456 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003457 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3458 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003459 CXXCtorInitializer *Init;
3460 if (Indirect)
3461 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3462 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003463 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003464 SourceLocation());
3465 else
3466 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3467 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003468 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003469 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003470 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003471 }
3472
Douglas Gregorddb21472011-11-02 23:04:16 +00003473 // Don't initialize incomplete or zero-length arrays.
3474 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3475 return false;
3476
John McCallf1860e52010-05-20 23:23:51 +00003477 // Don't try to build an implicit initializer if there were semantic
3478 // errors in any of the initializers (and therefore we might be
3479 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003480 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003481 return false;
3482
Sean Huntcbb67482011-01-08 20:30:50 +00003483 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003484 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3485 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003486 return true;
John McCallf1860e52010-05-20 23:23:51 +00003487
Richard Smith0b8220a2012-08-07 21:30:42 +00003488 if (!Init)
3489 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003490
Richard Smith0b8220a2012-08-07 21:30:42 +00003491 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003492}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003493
3494bool
3495Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3496 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003497 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003498 Constructor->setNumCtorInitializers(1);
3499 CXXCtorInitializer **initializer =
3500 new (Context) CXXCtorInitializer*[1];
3501 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3502 Constructor->setCtorInitializers(initializer);
3503
Sean Huntb76af9c2011-05-03 23:05:34 +00003504 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003505 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003506 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3507 }
3508
Sean Huntc1598702011-05-05 00:05:47 +00003509 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003510
Sean Hunt059ce0d2011-05-01 07:04:31 +00003511 return false;
3512}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003513
David Blaikie93c86172013-01-17 05:26:25 +00003514bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3515 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003516 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003517 // Just store the initializers as written, they will be checked during
3518 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003519 if (!Initializers.empty()) {
3520 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003521 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003522 new (Context) CXXCtorInitializer*[Initializers.size()];
3523 memcpy(baseOrMemberInitializers, Initializers.data(),
3524 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003525 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003526 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003527
3528 // Let template instantiation know whether we had errors.
3529 if (AnyErrors)
3530 Constructor->setInvalidDecl();
3531
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003532 return false;
3533 }
3534
John McCallf1860e52010-05-20 23:23:51 +00003535 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003536
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003537 // We need to build the initializer AST according to order of construction
3538 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003539 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003540 if (!ClassDecl)
3541 return true;
3542
Eli Friedman80c30da2009-11-09 19:20:36 +00003543 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003544
David Blaikie93c86172013-01-17 05:26:25 +00003545 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003546 CXXCtorInitializer *Member = Initializers[i];
Richard Smithcbc820a2013-07-22 02:56:56 +00003547
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003548 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003549 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Stephen Hines651f13c2014-04-23 16:59:28 -07003550 else {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003551 Info.AllBaseFields[Member->getAnyMember()] = Member;
Stephen Hines651f13c2014-04-23 16:59:28 -07003552
3553 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3554 for (auto *C : F->chain()) {
3555 FieldDecl *FD = dyn_cast<FieldDecl>(C);
3556 if (FD && FD->getParent()->isUnion())
3557 Info.ActiveUnionMember.insert(std::make_pair(
3558 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3559 }
3560 } else if (FieldDecl *FD = Member->getMember()) {
3561 if (FD->getParent()->isUnion())
3562 Info.ActiveUnionMember.insert(std::make_pair(
3563 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3564 }
3565 }
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003566 }
3567
Anders Carlsson711f34a2010-04-21 19:52:01 +00003568 // Keep track of the direct virtual bases.
3569 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Stephen Hines651f13c2014-04-23 16:59:28 -07003570 for (auto &I : ClassDecl->bases()) {
3571 if (I.isVirtual())
3572 DirectVBases.insert(&I);
Anders Carlsson711f34a2010-04-21 19:52:01 +00003573 }
3574
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003575 // Push virtual bases before others.
Stephen Hines651f13c2014-04-23 16:59:28 -07003576 for (auto &VBase : ClassDecl->vbases()) {
Sean Huntcbb67482011-01-08 20:30:50 +00003577 if (CXXCtorInitializer *Value
Stephen Hines651f13c2014-04-23 16:59:28 -07003578 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithcbc820a2013-07-22 02:56:56 +00003579 // [class.base.init]p7, per DR257:
3580 // A mem-initializer where the mem-initializer-id names a virtual base
3581 // class is ignored during execution of a constructor of any class that
3582 // is not the most derived class.
3583 if (ClassDecl->isAbstract()) {
3584 // FIXME: Provide a fixit to remove the base specifier. This requires
3585 // tracking the location of the associated comma for a base specifier.
3586 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Stephen Hines651f13c2014-04-23 16:59:28 -07003587 << VBase.getType() << ClassDecl;
Richard Smithcbc820a2013-07-22 02:56:56 +00003588 DiagnoseAbstractType(ClassDecl);
3589 }
3590
John McCallf1860e52010-05-20 23:23:51 +00003591 Info.AllToInit.push_back(Value);
Richard Smithcbc820a2013-07-22 02:56:56 +00003592 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3593 // [class.base.init]p8, per DR257:
3594 // If a given [...] base class is not named by a mem-initializer-id
3595 // [...] and the entity is not a virtual base class of an abstract
3596 // class, then [...] the entity is default-initialized.
Stephen Hines651f13c2014-04-23 16:59:28 -07003597 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003598 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003599 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Stephen Hines651f13c2014-04-23 16:59:28 -07003600 &VBase, IsInheritedVirtualBase,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003601 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003602 HadError = true;
3603 continue;
3604 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003605
John McCallf1860e52010-05-20 23:23:51 +00003606 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003607 }
3608 }
Mike Stump1eb44332009-09-09 15:08:12 +00003609
John McCallf1860e52010-05-20 23:23:51 +00003610 // Non-virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07003611 for (auto &Base : ClassDecl->bases()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003612 // Virtuals are in the virtual base list and already constructed.
Stephen Hines651f13c2014-04-23 16:59:28 -07003613 if (Base.isVirtual())
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003614 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003615
Sean Huntcbb67482011-01-08 20:30:50 +00003616 if (CXXCtorInitializer *Value
Stephen Hines651f13c2014-04-23 16:59:28 -07003617 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallf1860e52010-05-20 23:23:51 +00003618 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003619 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003620 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003621 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Stephen Hines651f13c2014-04-23 16:59:28 -07003622 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003623 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003624 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003625 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003626 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003627
John McCallf1860e52010-05-20 23:23:51 +00003628 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003629 }
3630 }
Mike Stump1eb44332009-09-09 15:08:12 +00003631
John McCallf1860e52010-05-20 23:23:51 +00003632 // Fields.
Stephen Hines651f13c2014-04-23 16:59:28 -07003633 for (auto *Mem : ClassDecl->decls()) {
3634 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003635 // C++ [class.bit]p2:
3636 // A declaration for a bit-field that omits the identifier declares an
3637 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3638 // initialized.
3639 if (F->isUnnamedBitfield())
3640 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003641
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003642 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003643 // handle anonymous struct/union fields based on their individual
3644 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003645 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003646 continue;
3647
3648 if (CollectFieldInitializer(*this, Info, F))
3649 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003650 continue;
3651 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003652
3653 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003654 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003655 continue;
3656
Stephen Hines651f13c2014-04-23 16:59:28 -07003657 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003658 if (F->getType()->isIncompleteArrayType()) {
3659 assert(ClassDecl->hasFlexibleArrayMember() &&
3660 "Incomplete array type is not valid");
3661 continue;
3662 }
3663
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003664 // Initialize each field of an anonymous struct individually.
3665 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3666 HadError = true;
3667
3668 continue;
3669 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003670 }
Mike Stump1eb44332009-09-09 15:08:12 +00003671
David Blaikie93c86172013-01-17 05:26:25 +00003672 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003673 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003674 Constructor->setNumCtorInitializers(NumInitializers);
3675 CXXCtorInitializer **baseOrMemberInitializers =
3676 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003677 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003678 NumInitializers * sizeof(CXXCtorInitializer*));
3679 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003680
John McCallef027fe2010-03-16 21:39:52 +00003681 // Constructors implicitly reference the base and member
3682 // destructors.
3683 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3684 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003685 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003686
3687 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003688}
3689
David Blaikieee000bb2013-01-17 08:49:22 +00003690static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003691 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003692 const RecordDecl *RD = RT->getDecl();
3693 if (RD->isAnonymousStructOrUnion()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003694 for (auto *Field : RD->fields())
3695 PopulateKeysForFields(Field, IdealInits);
David Blaikieee000bb2013-01-17 08:49:22 +00003696 return;
3697 }
Eli Friedman6347f422009-07-21 19:28:10 +00003698 }
David Blaikieee000bb2013-01-17 08:49:22 +00003699 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003700}
3701
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003702static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3703 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003704}
3705
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003706static const void *GetKeyForMember(ASTContext &Context,
3707 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003708 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003709 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003710
David Blaikieee000bb2013-01-17 08:49:22 +00003711 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003712}
3713
David Blaikie93c86172013-01-17 05:26:25 +00003714static void DiagnoseBaseOrMemInitializerOrder(
3715 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3716 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003717 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003718 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003719
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003720 // Don't check initializers order unless the warning is enabled at the
3721 // location of at least one initializer.
3722 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003723 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003724 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003725 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3726 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003727 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003728 ShouldCheckOrder = true;
3729 break;
3730 }
3731 }
3732 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003733 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003734
John McCalld6ca8da2010-04-10 07:37:23 +00003735 // Build the list of bases and members in the order that they'll
3736 // actually be initialized. The explicit initializers should be in
3737 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003738 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003739
Anders Carlsson071d6102010-04-02 03:38:04 +00003740 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3741
John McCalld6ca8da2010-04-10 07:37:23 +00003742 // 1. Virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07003743 for (const auto &VBase : ClassDecl->vbases())
3744 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003745
John McCalld6ca8da2010-04-10 07:37:23 +00003746 // 2. Non-virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07003747 for (const auto &Base : ClassDecl->bases()) {
3748 if (Base.isVirtual())
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003749 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07003750 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003751 }
Mike Stump1eb44332009-09-09 15:08:12 +00003752
John McCalld6ca8da2010-04-10 07:37:23 +00003753 // 3. Direct fields.
Stephen Hines651f13c2014-04-23 16:59:28 -07003754 for (auto *Field : ClassDecl->fields()) {
Douglas Gregord61db332011-10-10 17:22:13 +00003755 if (Field->isUnnamedBitfield())
3756 continue;
3757
Stephen Hines651f13c2014-04-23 16:59:28 -07003758 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003759 }
3760
John McCalld6ca8da2010-04-10 07:37:23 +00003761 unsigned NumIdealInits = IdealInitKeys.size();
3762 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003763
Sean Huntcbb67482011-01-08 20:30:50 +00003764 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003765 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003766 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003767 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003768
3769 // Scan forward to try to find this initializer in the idealized
3770 // initializers list.
3771 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3772 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003773 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003774
3775 // If we didn't find this initializer, it must be because we
3776 // scanned past it on a previous iteration. That can only
3777 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003778 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003779 Sema::SemaDiagnosticBuilder D =
3780 SemaRef.Diag(PrevInit->getSourceLocation(),
3781 diag::warn_initializer_out_of_order);
3782
Francois Pichet00eb3f92010-12-04 09:14:42 +00003783 if (PrevInit->isAnyMemberInitializer())
3784 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003785 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003786 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003787
Francois Pichet00eb3f92010-12-04 09:14:42 +00003788 if (Init->isAnyMemberInitializer())
3789 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003790 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003791 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003792
3793 // Move back to the initializer's location in the ideal list.
3794 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3795 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003796 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003797
3798 assert(IdealIndex != NumIdealInits &&
3799 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003800 }
John McCalld6ca8da2010-04-10 07:37:23 +00003801
3802 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003803 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003804}
3805
John McCall3c3ccdb2010-04-10 09:28:51 +00003806namespace {
3807bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003808 CXXCtorInitializer *Init,
3809 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003810 if (!PrevInit) {
3811 PrevInit = Init;
3812 return false;
3813 }
3814
Douglas Gregordc392c12013-03-25 23:28:23 +00003815 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003816 S.Diag(Init->getSourceLocation(),
3817 diag::err_multiple_mem_initialization)
3818 << Field->getDeclName()
3819 << Init->getSourceRange();
3820 else {
John McCallf4c73712011-01-19 06:33:43 +00003821 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003822 assert(BaseClass && "neither field nor base");
3823 S.Diag(Init->getSourceLocation(),
3824 diag::err_multiple_base_initialization)
3825 << QualType(BaseClass, 0)
3826 << Init->getSourceRange();
3827 }
3828 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3829 << 0 << PrevInit->getSourceRange();
3830
3831 return true;
3832}
3833
Sean Huntcbb67482011-01-08 20:30:50 +00003834typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003835typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3836
3837bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003838 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003839 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003840 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003841 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003842 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003843
3844 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003845 if (Parent->isUnion()) {
3846 UnionEntry &En = Unions[Parent];
3847 if (En.first && En.first != Child) {
3848 S.Diag(Init->getSourceLocation(),
3849 diag::err_multiple_mem_union_initialization)
3850 << Field->getDeclName()
3851 << Init->getSourceRange();
3852 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3853 << 0 << En.second->getSourceRange();
3854 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003855 }
3856 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003857 En.first = Child;
3858 En.second = Init;
3859 }
David Blaikie6fe29652011-11-17 06:01:57 +00003860 if (!Parent->isAnonymousStructOrUnion())
3861 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003862 }
3863
3864 Child = Parent;
3865 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003866 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003867
3868 return false;
3869}
3870}
3871
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003872/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003873void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003874 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003875 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003876 bool AnyErrors) {
3877 if (!ConstructorDecl)
3878 return;
3879
3880 AdjustDeclIfTemplate(ConstructorDecl);
3881
3882 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003883 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003884
3885 if (!Constructor) {
3886 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3887 return;
3888 }
3889
John McCall3c3ccdb2010-04-10 09:28:51 +00003890 // Mapping for the duplicate initializers check.
3891 // For member initializers, this is keyed with a FieldDecl*.
3892 // For base initializers, this is keyed with a Type*.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003893 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003894
3895 // Mapping for the inconsistent anonymous-union initializers check.
3896 RedundantUnionMap MemberUnions;
3897
Anders Carlssonea356fb2010-04-02 05:42:15 +00003898 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003899 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003900 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003901
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003902 // Set the source order index.
3903 Init->setSourceOrder(i);
3904
Francois Pichet00eb3f92010-12-04 09:14:42 +00003905 if (Init->isAnyMemberInitializer()) {
3906 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003907 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3908 CheckRedundantUnionInit(*this, Init, MemberUnions))
3909 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003910 } else if (Init->isBaseInitializer()) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003911 const void *Key =
3912 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall3c3ccdb2010-04-10 09:28:51 +00003913 if (CheckRedundantInit(*this, Init, Members[Key]))
3914 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003915 } else {
3916 assert(Init->isDelegatingInitializer());
3917 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003918 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003919 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003920 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003921 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003922 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003923 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003924 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003925 // Return immediately as the initializer is set.
3926 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003927 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003928 }
3929
Anders Carlssonea356fb2010-04-02 05:42:15 +00003930 if (HadError)
3931 return;
3932
David Blaikie93c86172013-01-17 05:26:25 +00003933 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003934
David Blaikie93c86172013-01-17 05:26:25 +00003935 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu225e9822013-09-16 21:54:53 +00003936
Richard Trieu858d2ba2013-10-25 00:56:00 +00003937 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003938}
3939
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003940void
John McCallef027fe2010-03-16 21:39:52 +00003941Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3942 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003943 // Ignore dependent contexts. Also ignore unions, since their members never
3944 // have destructors implicitly called.
3945 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003946 return;
John McCall58e6f342010-03-16 05:22:47 +00003947
3948 // FIXME: all the access-control diagnostics are positioned on the
3949 // field/base declaration. That's probably good; that said, the
3950 // user might reasonably want to know why the destructor is being
3951 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003952
Anders Carlsson9f853df2009-11-17 04:44:12 +00003953 // Non-static data members.
Stephen Hines651f13c2014-04-23 16:59:28 -07003954 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003955 if (Field->isInvalidDecl())
3956 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003957
3958 // Don't destroy incomplete or zero-length arrays.
3959 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3960 continue;
3961
Anders Carlsson9f853df2009-11-17 04:44:12 +00003962 QualType FieldType = Context.getBaseElementType(Field->getType());
3963
3964 const RecordType* RT = FieldType->getAs<RecordType>();
3965 if (!RT)
3966 continue;
3967
3968 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003969 if (FieldClassDecl->isInvalidDecl())
3970 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003971 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003972 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003973 // The destructor for an implicit anonymous union member is never invoked.
3974 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3975 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003976
Douglas Gregordb89f282010-07-01 22:47:18 +00003977 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003978 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003979 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003980 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003981 << Field->getDeclName()
3982 << FieldType);
3983
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003984 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003985 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003986 }
3987
John McCall58e6f342010-03-16 05:22:47 +00003988 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3989
Anders Carlsson9f853df2009-11-17 04:44:12 +00003990 // Bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07003991 for (const auto &Base : ClassDecl->bases()) {
John McCall58e6f342010-03-16 05:22:47 +00003992 // Bases are always records in a well-formed non-dependent class.
Stephen Hines651f13c2014-04-23 16:59:28 -07003993 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003994
3995 // Remember direct virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07003996 if (Base.isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003997 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003998
John McCall58e6f342010-03-16 05:22:47 +00003999 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004000 // If our base class is invalid, we probably can't get its dtor anyway.
4001 if (BaseClassDecl->isInvalidDecl())
4002 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00004003 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00004004 continue;
John McCall58e6f342010-03-16 05:22:47 +00004005
Douglas Gregordb89f282010-07-01 22:47:18 +00004006 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004007 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00004008
4009 // FIXME: caret should be on the start of the class name
Stephen Hines651f13c2014-04-23 16:59:28 -07004010 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004011 PDiag(diag::err_access_dtor_base)
Stephen Hines651f13c2014-04-23 16:59:28 -07004012 << Base.getType()
4013 << Base.getSourceRange(),
John McCallb9abd8722012-04-07 03:04:20 +00004014 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00004015
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004016 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00004017 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00004018 }
4019
4020 // Virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07004021 for (const auto &VBase : ClassDecl->vbases()) {
John McCall58e6f342010-03-16 05:22:47 +00004022 // Bases are always records in a well-formed non-dependent class.
Stephen Hines651f13c2014-04-23 16:59:28 -07004023 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00004024
4025 // Ignore direct virtual bases.
4026 if (DirectVirtualBases.count(RT))
4027 continue;
4028
John McCall58e6f342010-03-16 05:22:47 +00004029 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004030 // If our base class is invalid, we probably can't get its dtor anyway.
4031 if (BaseClassDecl->isInvalidDecl())
4032 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00004033 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004034 continue;
John McCall58e6f342010-03-16 05:22:47 +00004035
Douglas Gregordb89f282010-07-01 22:47:18 +00004036 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004037 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00004038 if (CheckDestructorAccess(
4039 ClassDecl->getLocation(), Dtor,
4040 PDiag(diag::err_access_dtor_vbase)
Stephen Hines651f13c2014-04-23 16:59:28 -07004041 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer2f686692013-06-22 06:43:58 +00004042 Context.getTypeDeclType(ClassDecl)) ==
4043 AR_accessible) {
4044 CheckDerivedToBaseConversion(
Stephen Hines651f13c2014-04-23 16:59:28 -07004045 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer2f686692013-06-22 06:43:58 +00004046 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4047 SourceRange(), DeclarationName(), 0);
4048 }
John McCall58e6f342010-03-16 05:22:47 +00004049
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004050 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00004051 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004052 }
4053}
4054
John McCalld226f652010-08-21 09:40:31 +00004055void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00004056 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004057 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004058
Mike Stump1eb44332009-09-09 15:08:12 +00004059 if (CXXConstructorDecl *Constructor
Richard Trieu858d2ba2013-10-25 00:56:00 +00004060 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie93c86172013-01-17 05:26:25 +00004061 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieu858d2ba2013-10-25 00:56:00 +00004062 DiagnoseUninitializedFields(*this, Constructor);
4063 }
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004064}
4065
Mike Stump1eb44332009-09-09 15:08:12 +00004066bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00004067 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004068 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4069 unsigned DiagID;
4070 AbstractDiagSelID SelID;
4071
4072 public:
4073 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4074 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004075
Stephen Hines651f13c2014-04-23 16:59:28 -07004076 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman2217f852012-08-14 02:06:07 +00004077 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004078 if (SelID == -1)
4079 S.Diag(Loc, DiagID) << T;
4080 else
4081 S.Diag(Loc, DiagID) << SelID << T;
4082 }
4083 } Diagnoser(DiagID, SelID);
4084
4085 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004086}
4087
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00004088bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004089 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004090 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004091 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004092
Anders Carlsson11f21a02009-03-23 19:10:31 +00004093 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004094 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004095
Ted Kremenek6217b802009-07-29 21:53:49 +00004096 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004097 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004098 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004099 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00004100
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004101 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004102 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004103 }
Mike Stump1eb44332009-09-09 15:08:12 +00004104
Ted Kremenek6217b802009-07-29 21:53:49 +00004105 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004106 if (!RT)
4107 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004108
John McCall86ff3082010-02-04 22:26:26 +00004109 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004110
John McCall94c3b562010-08-18 09:41:07 +00004111 // We can't answer whether something is abstract until it has a
4112 // definition. If it's currently being defined, we'll walk back
4113 // over all the declarations when we have a full definition.
4114 const CXXRecordDecl *Def = RD->getDefinition();
4115 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00004116 return false;
4117
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004118 if (!RD->isAbstract())
4119 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004120
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004121 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00004122 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00004123
John McCall94c3b562010-08-18 09:41:07 +00004124 return true;
4125}
4126
4127void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4128 // Check if we've already emitted the list of pure virtual functions
4129 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004130 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00004131 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004132
Richard Smithcbc820a2013-07-22 02:56:56 +00004133 // If the diagnostic is suppressed, don't emit the notes. We're only
4134 // going to emit them once, so try to attach them to a diagnostic we're
4135 // actually going to show.
4136 if (Diags.isLastDiagnosticIgnored())
4137 return;
4138
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004139 CXXFinalOverriderMap FinalOverriders;
4140 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00004141
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004142 // Keep a set of seen pure methods so we won't diagnose the same method
4143 // more than once.
4144 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4145
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004146 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4147 MEnd = FinalOverriders.end();
4148 M != MEnd;
4149 ++M) {
4150 for (OverridingMethods::iterator SO = M->second.begin(),
4151 SOEnd = M->second.end();
4152 SO != SOEnd; ++SO) {
4153 // C++ [class.abstract]p4:
4154 // A class is abstract if it contains or inherits at least one
4155 // pure virtual function for which the final overrider is pure
4156 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00004157
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004158 //
4159 if (SO->second.size() != 1)
4160 continue;
4161
4162 if (!SO->second.front().Method->isPure())
4163 continue;
4164
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004165 if (!SeenPureMethods.insert(SO->second.front().Method))
4166 continue;
4167
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004168 Diag(SO->second.front().Method->getLocation(),
4169 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00004170 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004171 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004172 }
4173
4174 if (!PureVirtualClassDiagSet)
4175 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4176 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004177}
4178
Anders Carlsson8211eff2009-03-24 01:19:16 +00004179namespace {
John McCall94c3b562010-08-18 09:41:07 +00004180struct AbstractUsageInfo {
4181 Sema &S;
4182 CXXRecordDecl *Record;
4183 CanQualType AbstractType;
4184 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00004185
John McCall94c3b562010-08-18 09:41:07 +00004186 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4187 : S(S), Record(Record),
4188 AbstractType(S.Context.getCanonicalType(
4189 S.Context.getTypeDeclType(Record))),
4190 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00004191
John McCall94c3b562010-08-18 09:41:07 +00004192 void DiagnoseAbstractType() {
4193 if (Invalid) return;
4194 S.DiagnoseAbstractType(Record);
4195 Invalid = true;
4196 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00004197
John McCall94c3b562010-08-18 09:41:07 +00004198 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4199};
4200
4201struct CheckAbstractUsage {
4202 AbstractUsageInfo &Info;
4203 const NamedDecl *Ctx;
4204
4205 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4206 : Info(Info), Ctx(Ctx) {}
4207
4208 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4209 switch (TL.getTypeLocClass()) {
4210#define ABSTRACT_TYPELOC(CLASS, PARENT)
4211#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00004212 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00004213#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00004214 }
John McCall94c3b562010-08-18 09:41:07 +00004215 }
Mike Stump1eb44332009-09-09 15:08:12 +00004216
John McCall94c3b562010-08-18 09:41:07 +00004217 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004218 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4219 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4220 if (!TL.getParam(I))
Douglas Gregor70191862011-02-22 23:21:06 +00004221 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07004222
4223 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall94c3b562010-08-18 09:41:07 +00004224 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004225 }
John McCall94c3b562010-08-18 09:41:07 +00004226 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004227
John McCall94c3b562010-08-18 09:41:07 +00004228 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4229 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4230 }
Mike Stump1eb44332009-09-09 15:08:12 +00004231
John McCall94c3b562010-08-18 09:41:07 +00004232 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4233 // Visit the type parameters from a permissive context.
4234 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4235 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4236 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4237 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4238 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4239 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004240 }
John McCall94c3b562010-08-18 09:41:07 +00004241 }
Mike Stump1eb44332009-09-09 15:08:12 +00004242
John McCall94c3b562010-08-18 09:41:07 +00004243 // Visit pointee types from a permissive context.
4244#define CheckPolymorphic(Type) \
4245 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4246 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4247 }
4248 CheckPolymorphic(PointerTypeLoc)
4249 CheckPolymorphic(ReferenceTypeLoc)
4250 CheckPolymorphic(MemberPointerTypeLoc)
4251 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004252 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004253
John McCall94c3b562010-08-18 09:41:07 +00004254 /// Handle all the types we haven't given a more specific
4255 /// implementation for above.
4256 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4257 // Every other kind of type that we haven't called out already
4258 // that has an inner type is either (1) sugar or (2) contains that
4259 // inner type in some way as a subobject.
4260 if (TypeLoc Next = TL.getNextTypeLoc())
4261 return Visit(Next, Sel);
4262
4263 // If there's no inner type and we're in a permissive context,
4264 // don't diagnose.
4265 if (Sel == Sema::AbstractNone) return;
4266
4267 // Check whether the type matches the abstract type.
4268 QualType T = TL.getType();
4269 if (T->isArrayType()) {
4270 Sel = Sema::AbstractArrayType;
4271 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004272 }
John McCall94c3b562010-08-18 09:41:07 +00004273 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4274 if (CT != Info.AbstractType) return;
4275
4276 // It matched; do some magic.
4277 if (Sel == Sema::AbstractArrayType) {
4278 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4279 << T << TL.getSourceRange();
4280 } else {
4281 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4282 << Sel << T << TL.getSourceRange();
4283 }
4284 Info.DiagnoseAbstractType();
4285 }
4286};
4287
4288void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4289 Sema::AbstractDiagSelID Sel) {
4290 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4291}
4292
4293}
4294
4295/// Check for invalid uses of an abstract type in a method declaration.
4296static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4297 CXXMethodDecl *MD) {
4298 // No need to do the check on definitions, which require that
4299 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004300 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004301 return;
4302
4303 // For safety's sake, just ignore it if we don't have type source
4304 // information. This should never happen for non-implicit methods,
4305 // but...
4306 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4307 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4308}
4309
4310/// Check for invalid uses of an abstract type within a class definition.
4311static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4312 CXXRecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004313 for (auto *D : RD->decls()) {
John McCall94c3b562010-08-18 09:41:07 +00004314 if (D->isImplicit()) continue;
4315
4316 // Methods and method templates.
4317 if (isa<CXXMethodDecl>(D)) {
4318 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4319 } else if (isa<FunctionTemplateDecl>(D)) {
4320 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4321 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4322
4323 // Fields and static variables.
4324 } else if (isa<FieldDecl>(D)) {
4325 FieldDecl *FD = cast<FieldDecl>(D);
4326 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4327 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4328 } else if (isa<VarDecl>(D)) {
4329 VarDecl *VD = cast<VarDecl>(D);
4330 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4331 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4332
4333 // Nested classes and class templates.
4334 } else if (isa<CXXRecordDecl>(D)) {
4335 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4336 } else if (isa<ClassTemplateDecl>(D)) {
4337 CheckAbstractClassUsage(Info,
4338 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4339 }
4340 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004341}
4342
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004343/// \brief Perform semantic checks on a class definition that has been
4344/// completing, introducing implicitly-declared members, checking for
4345/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004346void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004347 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004348 return;
4349
John McCall94c3b562010-08-18 09:41:07 +00004350 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4351 AbstractUsageInfo Info(*this, Record);
4352 CheckAbstractClassUsage(Info, Record);
4353 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004354
4355 // If this is not an aggregate type and has no user-declared constructor,
4356 // complain about any non-static data members of reference or const scalar
4357 // type, since they will never get initializers.
4358 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004359 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4360 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004361 bool Complained = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07004362 for (const auto *F : Record->fields()) {
Douglas Gregord61db332011-10-10 17:22:13 +00004363 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004364 continue;
4365
Douglas Gregor325e5932010-04-15 00:00:53 +00004366 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004367 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004368 if (!Complained) {
4369 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4370 << Record->getTagKind() << Record;
4371 Complained = true;
4372 }
4373
4374 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4375 << F->getType()->isReferenceType()
4376 << F->getDeclName();
4377 }
4378 }
4379 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004380
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004381 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004382 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004383
4384 if (Record->getIdentifier()) {
4385 // C++ [class.mem]p13:
4386 // If T is the name of a class, then each of the following shall have a
4387 // name different from T:
4388 // - every member of every anonymous union that is a member of class T.
4389 //
4390 // C++ [class.mem]p14:
4391 // In addition, if class T has a user-declared constructor (12.1), every
4392 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004393 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4394 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4395 ++I) {
4396 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004397 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4398 isa<IndirectFieldDecl>(D)) {
4399 Diag(D->getLocation(), diag::err_member_name_of_class)
4400 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004401 break;
4402 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004403 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004404 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004405
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004406 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004407 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004408 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004409 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004410 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4411 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4412 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004413
David Majnemer7121bdb2013-10-18 00:33:31 +00004414 if (Record->isAbstract()) {
4415 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4416 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4417 << FA->isSpelledAsSealed();
4418 DiagnoseAbstractType(Record);
4419 }
David Blaikieb6b5b972012-09-21 03:21:07 +00004420 }
4421
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004422 if (!Record->isDependentType()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004423 for (auto *M : Record->methods()) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004424 // See if a method overloads virtual methods in a base
4425 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004426 if (!M->isStatic())
Stephen Hines651f13c2014-04-23 16:59:28 -07004427 DiagnoseHiddenVirtualMethods(M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004428
4429 // Check whether the explicitly-defaulted special members are valid.
4430 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Stephen Hines651f13c2014-04-23 16:59:28 -07004431 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004432
4433 // For an explicitly defaulted or deleted special member, we defer
4434 // determining triviality until the class is complete. That time is now!
4435 if (!M->isImplicit() && !M->isUserProvided()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004436 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004437 if (CSM != CXXInvalid) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004438 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smith1d28caf2012-12-11 01:14:52 +00004439
4440 // Inform the class that we've finished declaring this member.
Stephen Hines651f13c2014-04-23 16:59:28 -07004441 Record->finishedDefaultedOrDeletedMember(M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004442 }
4443 }
4444 }
4445 }
4446
4447 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4448 // function that is not a constructor declares that member function to be
4449 // const. [...] The class of which that function is a member shall be
4450 // a literal type.
4451 //
4452 // If the class has virtual bases, any constexpr members will already have
4453 // been diagnosed by the checks performed on the member declaration, so
4454 // suppress this (less useful) diagnostic.
4455 //
4456 // We delay this until we know whether an explicitly-defaulted (or deleted)
4457 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004458 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004459 !Record->isLiteral() && !Record->getNumVBases()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004460 for (const auto *M : Record->methods()) {
4461 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004462 switch (Record->getTemplateSpecializationKind()) {
4463 case TSK_ImplicitInstantiation:
4464 case TSK_ExplicitInstantiationDeclaration:
4465 case TSK_ExplicitInstantiationDefinition:
4466 // If a template instantiates to a non-literal type, but its members
4467 // instantiate to constexpr functions, the template is technically
4468 // ill-formed, but we allow it for sanity.
4469 continue;
4470
4471 case TSK_Undeclared:
4472 case TSK_ExplicitSpecialization:
4473 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4474 diag::err_constexpr_method_non_literal);
4475 break;
4476 }
4477
4478 // Only produce one error per class.
4479 break;
4480 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004481 }
4482 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004483
Stephen Hines651f13c2014-04-23 16:59:28 -07004484 // ms_struct is a request to use the same ABI rules as MSVC. Check
4485 // whether this class uses any C++ features that are implemented
4486 // completely differently in MSVC, and if so, emit a diagnostic.
4487 // That diagnostic defaults to an error, but we allow projects to
4488 // map it down to a warning (or ignore it). It's a fairly common
4489 // practice among users of the ms_struct pragma to mass-annotate
4490 // headers, sweeping up a bunch of types that the project doesn't
4491 // really rely on MSVC-compatible layout for. We must therefore
4492 // support "ms_struct except for C++ stuff" as a secondary ABI.
4493 if (Record->isMsStruct(Context) &&
4494 (Record->isPolymorphic() || Record->getNumBases())) {
4495 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Huntb2969b12013-10-11 20:19:00 +00004496 }
4497
Richard Smith07b0fdc2013-03-18 21:12:30 +00004498 // Declare inheriting constructors. We do this eagerly here because:
4499 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004500 // constructors from different classes.
4501 // - The lazy declaration of the other implicit constructors is so as to not
4502 // waste space and performance on classes that are not meant to be
4503 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004504 // have inheriting constructors.
4505 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004506}
4507
Stephen Hines651f13c2014-04-23 16:59:28 -07004508/// Look up the special member function that would be called by a special
4509/// member function for a subobject of class type.
4510///
4511/// \param Class The class type of the subobject.
4512/// \param CSM The kind of special member function.
4513/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4514/// \param ConstRHS True if this is a copy operation with a const object
4515/// on its RHS, that is, if the argument to the outer special member
4516/// function is 'const' and this is not a field marked 'mutable'.
4517static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4518 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4519 unsigned FieldQuals, bool ConstRHS) {
4520 unsigned LHSQuals = 0;
4521 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4522 LHSQuals = FieldQuals;
4523
4524 unsigned RHSQuals = FieldQuals;
4525 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4526 RHSQuals = 0;
4527 else if (ConstRHS)
4528 RHSQuals |= Qualifiers::Const;
4529
4530 return S.LookupSpecialMember(Class, CSM,
4531 RHSQuals & Qualifiers::Const,
4532 RHSQuals & Qualifiers::Volatile,
4533 false,
4534 LHSQuals & Qualifiers::Const,
4535 LHSQuals & Qualifiers::Volatile);
4536}
4537
Richard Smith7756afa2012-06-10 05:43:50 +00004538/// Is the special member function which would be selected to perform the
4539/// specified operation on the specified class type a constexpr constructor?
4540static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4541 Sema::CXXSpecialMember CSM,
Stephen Hines651f13c2014-04-23 16:59:28 -07004542 unsigned Quals, bool ConstRHS) {
Richard Smith7756afa2012-06-10 05:43:50 +00004543 Sema::SpecialMemberOverloadResult *SMOR =
Stephen Hines651f13c2014-04-23 16:59:28 -07004544 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smith7756afa2012-06-10 05:43:50 +00004545 if (!SMOR || !SMOR->getMethod())
4546 // A constructor we wouldn't select can't be "involved in initializing"
4547 // anything.
4548 return true;
4549 return SMOR->getMethod()->isConstexpr();
4550}
4551
4552/// Determine whether the specified special member function would be constexpr
4553/// if it were implicitly defined.
4554static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4555 Sema::CXXSpecialMember CSM,
4556 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004557 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004558 return false;
4559
4560 // C++11 [dcl.constexpr]p4:
4561 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004562 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004563 switch (CSM) {
4564 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004565 // Since default constructor lookup is essentially trivial (and cannot
4566 // involve, for instance, template instantiation), we compute whether a
4567 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4568 //
4569 // This is important for performance; we need to know whether the default
4570 // constructor is constexpr to determine whether the type is a literal type.
4571 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4572
Richard Smith7756afa2012-06-10 05:43:50 +00004573 case Sema::CXXCopyConstructor:
4574 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004575 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004576 break;
4577
4578 case Sema::CXXCopyAssignment:
4579 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004580 if (!S.getLangOpts().CPlusPlus1y)
4581 return false;
4582 // In C++1y, we need to perform overload resolution.
4583 Ctor = false;
4584 break;
4585
Richard Smith7756afa2012-06-10 05:43:50 +00004586 case Sema::CXXDestructor:
4587 case Sema::CXXInvalid:
4588 return false;
4589 }
4590
4591 // -- if the class is a non-empty union, or for each non-empty anonymous
4592 // union member of a non-union class, exactly one non-static data member
4593 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004594 //
4595 // If we squint, this is guaranteed, since exactly one non-static data member
4596 // will be initialized (if the constructor isn't deleted), we just don't know
4597 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004598 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004599 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004600
4601 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004602 if (Ctor && ClassDecl->getNumVBases())
4603 return false;
4604
4605 // C++1y [class.copy]p26:
4606 // -- [the class] is a literal type, and
4607 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004608 return false;
4609
4610 // -- every constructor involved in initializing [...] base class
4611 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004612 // -- the assignment operator selected to copy/move each direct base
4613 // class is a constexpr function, and
Stephen Hines651f13c2014-04-23 16:59:28 -07004614 for (const auto &B : ClassDecl->bases()) {
4615 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smith7756afa2012-06-10 05:43:50 +00004616 if (!BaseType) continue;
4617
4618 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -07004619 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smith7756afa2012-06-10 05:43:50 +00004620 return false;
4621 }
4622
4623 // -- every constructor involved in initializing non-static data members
4624 // [...] shall be a constexpr constructor;
4625 // -- every non-static data member and base class sub-object shall be
4626 // initialized
Stephen Hines651f13c2014-04-23 16:59:28 -07004627 // -- for each non-static data member of X that is of class type (or array
Richard Smitha8942d72013-05-07 03:19:20 +00004628 // thereof), the assignment operator selected to copy/move that member is
4629 // a constexpr function
Stephen Hines651f13c2014-04-23 16:59:28 -07004630 for (const auto *F : ClassDecl->fields()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004631 if (F->isInvalidDecl())
4632 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07004633 QualType BaseType = S.Context.getBaseElementType(F->getType());
4634 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004635 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -07004636 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4637 BaseType.getCVRQualifiers(),
4638 ConstArg && !F->isMutable()))
Richard Smith7756afa2012-06-10 05:43:50 +00004639 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004640 }
4641 }
4642
4643 // All OK, it's constexpr!
4644 return true;
4645}
4646
Richard Smithb9d0b762012-07-27 04:22:15 +00004647static Sema::ImplicitExceptionSpecification
4648computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4649 switch (S.getSpecialMember(MD)) {
4650 case Sema::CXXDefaultConstructor:
4651 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4652 case Sema::CXXCopyConstructor:
4653 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4654 case Sema::CXXCopyAssignment:
4655 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4656 case Sema::CXXMoveConstructor:
4657 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4658 case Sema::CXXMoveAssignment:
4659 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4660 case Sema::CXXDestructor:
4661 return S.ComputeDefaultedDtorExceptionSpec(MD);
4662 case Sema::CXXInvalid:
4663 break;
4664 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004665 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4666 "only special members have implicit exception specs");
4667 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004668}
4669
Reid Kleckneref072032013-08-27 23:08:25 +00004670static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4671 CXXMethodDecl *MD) {
4672 FunctionProtoType::ExtProtoInfo EPI;
4673
4674 // Build an exception specification pointing back at this member.
4675 EPI.ExceptionSpecType = EST_Unevaluated;
4676 EPI.ExceptionSpecDecl = MD;
4677
4678 // Set the calling convention to the default for C++ instance methods.
4679 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4680 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4681 /*IsCXXMethod=*/true));
4682 return EPI;
4683}
4684
Richard Smithb9d0b762012-07-27 04:22:15 +00004685void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4686 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4687 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4688 return;
4689
Richard Smithdd25e802012-07-30 23:48:14 +00004690 // Evaluate the exception specification.
4691 ImplicitExceptionSpecification ExceptSpec =
4692 computeImplicitExceptionSpec(*this, Loc, MD);
4693
Stephen Hines651f13c2014-04-23 16:59:28 -07004694 FunctionProtoType::ExtProtoInfo EPI;
4695 ExceptSpec.getEPI(EPI);
4696
Richard Smithdd25e802012-07-30 23:48:14 +00004697 // Update the type of the special member to use it.
Stephen Hines651f13c2014-04-23 16:59:28 -07004698 UpdateExceptionSpec(MD, EPI);
Richard Smithdd25e802012-07-30 23:48:14 +00004699
4700 // A user-provided destructor can be defined outside the class. When that
4701 // happens, be sure to update the exception specification on both
4702 // declarations.
4703 const FunctionProtoType *CanonicalFPT =
4704 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4705 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Stephen Hines651f13c2014-04-23 16:59:28 -07004706 UpdateExceptionSpec(MD->getCanonicalDecl(), EPI);
Richard Smithb9d0b762012-07-27 04:22:15 +00004707}
4708
Richard Smith3003e1d2012-05-15 04:39:51 +00004709void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4710 CXXRecordDecl *RD = MD->getParent();
4711 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004712
Richard Smith3003e1d2012-05-15 04:39:51 +00004713 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4714 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004715
4716 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004717 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004718 bool First = MD == MD->getCanonicalDecl();
4719
4720 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004721
4722 // C++11 [dcl.fct.def.default]p1:
4723 // A function that is explicitly defaulted shall
4724 // -- be a special member function (checked elsewhere),
4725 // -- have the same type (except for ref-qualifiers, and except that a
4726 // copy operation can take a non-const reference) as an implicit
4727 // declaration, and
4728 // -- not have default arguments.
4729 unsigned ExpectedParams = 1;
4730 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4731 ExpectedParams = 0;
4732 if (MD->getNumParams() != ExpectedParams) {
4733 // This also checks for default arguments: a copy or move constructor with a
4734 // default argument is classified as a default constructor, and assignment
4735 // operations and destructors can't have default arguments.
4736 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4737 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004738 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004739 } else if (MD->isVariadic()) {
4740 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4741 << CSM << MD->getSourceRange();
4742 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004743 }
4744
Richard Smith3003e1d2012-05-15 04:39:51 +00004745 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004746
Richard Smith7756afa2012-06-10 05:43:50 +00004747 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004748 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004749 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004750 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004751 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004752
Richard Smith3003e1d2012-05-15 04:39:51 +00004753 QualType ReturnType = Context.VoidTy;
4754 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4755 // Check for return type matching.
Stephen Hines651f13c2014-04-23 16:59:28 -07004756 ReturnType = Type->getReturnType();
Richard Smith3003e1d2012-05-15 04:39:51 +00004757 QualType ExpectedReturnType =
4758 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4759 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4760 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4761 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4762 HadError = true;
4763 }
4764
4765 // A defaulted special member cannot have cv-qualifiers.
4766 if (Type->getTypeQuals()) {
4767 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004768 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004769 HadError = true;
4770 }
4771 }
4772
4773 // Check for parameter type matching.
Stephen Hines651f13c2014-04-23 16:59:28 -07004774 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004775 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004776 if (ExpectedParams && ArgType->isReferenceType()) {
4777 // Argument must be reference to possibly-const T.
4778 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004779 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004780
4781 if (ReferentType.isVolatileQualified()) {
4782 Diag(MD->getLocation(),
4783 diag::err_defaulted_special_member_volatile_param) << CSM;
4784 HadError = true;
4785 }
4786
Richard Smith7756afa2012-06-10 05:43:50 +00004787 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004788 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4789 Diag(MD->getLocation(),
4790 diag::err_defaulted_special_member_copy_const_param)
4791 << (CSM == CXXCopyAssignment);
4792 // FIXME: Explain why this special member can't be const.
4793 } else {
4794 Diag(MD->getLocation(),
4795 diag::err_defaulted_special_member_move_const_param)
4796 << (CSM == CXXMoveAssignment);
4797 }
4798 HadError = true;
4799 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004800 } else if (ExpectedParams) {
4801 // A copy assignment operator can take its argument by value, but a
4802 // defaulted one cannot.
4803 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004804 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004805 HadError = true;
4806 }
Sean Huntbe631222011-05-17 20:44:43 +00004807
Richard Smith61802452011-12-22 02:22:31 +00004808 // C++11 [dcl.fct.def.default]p2:
4809 // An explicitly-defaulted function may be declared constexpr only if it
4810 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004811 // Do not apply this rule to members of class templates, since core issue 1358
4812 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004813 // functions which cannot be constexpr (for non-constructors in C++11 and for
4814 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004815 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4816 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004817 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4818 : isa<CXXConstructorDecl>(MD)) &&
4819 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004820 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4821 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004822 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004823 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004824 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004825
Richard Smith61802452011-12-22 02:22:31 +00004826 // and may have an explicit exception-specification only if it is compatible
4827 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004828 if (Type->hasExceptionSpec()) {
4829 // Delay the check if this is the first declaration of the special member,
4830 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004831 if (First) {
4832 // If the exception specification needs to be instantiated, do so now,
4833 // before we clobber it with an EST_Unevaluated specification below.
4834 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4835 InstantiateExceptionSpec(MD->getLocStart(), MD);
4836 Type = MD->getType()->getAs<FunctionProtoType>();
4837 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004838 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004839 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004840 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4841 }
Richard Smith61802452011-12-22 02:22:31 +00004842
4843 // If a function is explicitly defaulted on its first declaration,
4844 if (First) {
4845 // -- it is implicitly considered to be constexpr if the implicit
4846 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004847 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004848
Richard Smith3003e1d2012-05-15 04:39:51 +00004849 // -- it is implicitly considered to have the same exception-specification
4850 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004851 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4852 EPI.ExceptionSpecType = EST_Unevaluated;
4853 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004854 MD->setType(Context.getFunctionType(ReturnType,
4855 ArrayRef<QualType>(&ArgType,
4856 ExpectedParams),
4857 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004858 }
4859
Richard Smith3003e1d2012-05-15 04:39:51 +00004860 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004861 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004862 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004863 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004864 // C++11 [dcl.fct.def.default]p4:
4865 // [For a] user-provided explicitly-defaulted function [...] if such a
4866 // function is implicitly defined as deleted, the program is ill-formed.
4867 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Stephen Hines651f13c2014-04-23 16:59:28 -07004868 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smith3003e1d2012-05-15 04:39:51 +00004869 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004870 }
4871 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004872
Richard Smith3003e1d2012-05-15 04:39:51 +00004873 if (HadError)
4874 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004875}
4876
Richard Smith1d28caf2012-12-11 01:14:52 +00004877/// Check whether the exception specification provided for an
4878/// explicitly-defaulted special member matches the exception specification
4879/// that would have been generated for an implicit special member, per
4880/// C++11 [dcl.fct.def.default]p2.
4881void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4882 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4883 // Compute the implicit exception specification.
Reid Kleckneref072032013-08-27 23:08:25 +00004884 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4885 /*IsCXXMethod=*/true);
4886 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith1d28caf2012-12-11 01:14:52 +00004887 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4888 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004889 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004890
4891 // Ensure that it matches.
4892 CheckEquivalentExceptionSpec(
4893 PDiag(diag::err_incorrect_defaulted_exception_spec)
4894 << getSpecialMember(MD), PDiag(),
4895 ImplicitType, SourceLocation(),
4896 SpecifiedType, MD->getLocation());
4897}
4898
Alp Toker08235662013-10-18 05:54:19 +00004899void Sema::CheckDelayedMemberExceptionSpecs() {
4900 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4901 2> Checks;
4902 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smith1d28caf2012-12-11 01:14:52 +00004903
Alp Toker08235662013-10-18 05:54:19 +00004904 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4905 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4906
4907 // Perform any deferred checking of exception specifications for virtual
4908 // destructors.
4909 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4910 const CXXDestructorDecl *Dtor = Checks[i].first;
4911 assert(!Dtor->getParent()->isDependentType() &&
4912 "Should not ever add destructors of templates into the list.");
4913 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4914 }
4915
4916 // Check that any explicitly-defaulted methods have exception specifications
4917 // compatible with their implicit exception specifications.
4918 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4919 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4920 Specs[I].second);
Richard Smith1d28caf2012-12-11 01:14:52 +00004921}
4922
Richard Smith7d5088a2012-02-18 02:02:13 +00004923namespace {
4924struct SpecialMemberDeletionInfo {
4925 Sema &S;
4926 CXXMethodDecl *MD;
4927 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004928 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004929
4930 // Properties of the special member, computed for convenience.
Stephen Hines651f13c2014-04-23 16:59:28 -07004931 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smith7d5088a2012-02-18 02:02:13 +00004932 SourceLocation Loc;
4933
4934 bool AllFieldsAreConst;
4935
4936 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004937 Sema::CXXSpecialMember CSM, bool Diagnose)
4938 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004939 IsConstructor(false), IsAssignment(false), IsMove(false),
Stephen Hines651f13c2014-04-23 16:59:28 -07004940 ConstArg(false), Loc(MD->getLocation()),
Richard Smith7d5088a2012-02-18 02:02:13 +00004941 AllFieldsAreConst(true) {
4942 switch (CSM) {
4943 case Sema::CXXDefaultConstructor:
4944 case Sema::CXXCopyConstructor:
4945 IsConstructor = true;
4946 break;
4947 case Sema::CXXMoveConstructor:
4948 IsConstructor = true;
4949 IsMove = true;
4950 break;
4951 case Sema::CXXCopyAssignment:
4952 IsAssignment = true;
4953 break;
4954 case Sema::CXXMoveAssignment:
4955 IsAssignment = true;
4956 IsMove = true;
4957 break;
4958 case Sema::CXXDestructor:
4959 break;
4960 case Sema::CXXInvalid:
4961 llvm_unreachable("invalid special member kind");
4962 }
4963
4964 if (MD->getNumParams()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004965 if (const ReferenceType *RT =
4966 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
4967 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smith7d5088a2012-02-18 02:02:13 +00004968 }
4969 }
4970
4971 bool inUnion() const { return MD->getParent()->isUnion(); }
4972
4973 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004974 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Stephen Hines651f13c2014-04-23 16:59:28 -07004975 unsigned Quals, bool IsMutable) {
4976 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
4977 ConstArg && !IsMutable);
Richard Smith7d5088a2012-02-18 02:02:13 +00004978 }
4979
Richard Smith6c4c36c2012-03-30 20:53:28 +00004980 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004981
Richard Smith6c4c36c2012-03-30 20:53:28 +00004982 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004983 bool shouldDeleteForField(FieldDecl *FD);
4984 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004985
Richard Smith517bb842012-07-18 03:51:16 +00004986 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4987 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004988 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4989 Sema::SpecialMemberOverloadResult *SMOR,
4990 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004991
4992 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004993};
4994}
4995
John McCall12d8d802012-04-09 20:53:23 +00004996/// Is the given special member inaccessible when used on the given
4997/// sub-object.
4998bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4999 CXXMethodDecl *target) {
5000 /// If we're operating on a base class, the object type is the
5001 /// type of this special member.
5002 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00005003 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00005004 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5005 objectTy = S.Context.getTypeDeclType(MD->getParent());
5006 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5007
5008 // If we're operating on a field, the object type is the type of the field.
5009 } else {
5010 objectTy = S.Context.getTypeDeclType(target->getParent());
5011 }
5012
5013 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5014}
5015
Richard Smith6c4c36c2012-03-30 20:53:28 +00005016/// Check whether we should delete a special member due to the implicit
5017/// definition containing a call to a special member of a subobject.
5018bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5019 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5020 bool IsDtorCallInCtor) {
5021 CXXMethodDecl *Decl = SMOR->getMethod();
5022 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5023
5024 int DiagKind = -1;
5025
5026 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5027 DiagKind = !Decl ? 0 : 1;
5028 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5029 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00005030 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00005031 DiagKind = 3;
5032 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5033 !Decl->isTrivial()) {
5034 // A member of a union must have a trivial corresponding special member.
5035 // As a weird special case, a destructor call from a union's constructor
5036 // must be accessible and non-deleted, but need not be trivial. Such a
5037 // destructor is never actually called, but is semantically checked as
5038 // if it were.
5039 DiagKind = 4;
5040 }
5041
5042 if (DiagKind == -1)
5043 return false;
5044
5045 if (Diagnose) {
5046 if (Field) {
5047 S.Diag(Field->getLocation(),
5048 diag::note_deleted_special_member_class_subobject)
5049 << CSM << MD->getParent() << /*IsField*/true
5050 << Field << DiagKind << IsDtorCallInCtor;
5051 } else {
5052 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5053 S.Diag(Base->getLocStart(),
5054 diag::note_deleted_special_member_class_subobject)
5055 << CSM << MD->getParent() << /*IsField*/false
5056 << Base->getType() << DiagKind << IsDtorCallInCtor;
5057 }
5058
5059 if (DiagKind == 1)
5060 S.NoteDeletedFunction(Decl);
5061 // FIXME: Explain inaccessibility if DiagKind == 3.
5062 }
5063
5064 return true;
5065}
5066
Richard Smith9a561d52012-02-26 09:11:52 +00005067/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00005068/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00005069bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00005070 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005071 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Stephen Hines651f13c2014-04-23 16:59:28 -07005072 bool IsMutable = Field && Field->isMutable();
Richard Smith7d5088a2012-02-18 02:02:13 +00005073
5074 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00005075 // -- any direct or virtual base class, or non-static data member with no
5076 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00005077 // either M has no default constructor or overload resolution as applied
5078 // to M's default constructor results in an ambiguity or in a function
5079 // that is deleted or inaccessible
5080 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5081 // -- a direct or virtual base class B that cannot be copied/moved because
5082 // overload resolution, as applied to B's corresponding special member,
5083 // results in an ambiguity or a function that is deleted or inaccessible
5084 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00005085 // C++11 [class.dtor]p5:
5086 // -- any direct or virtual base class [...] has a type with a destructor
5087 // that is deleted or inaccessible
5088 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00005089 Field && Field->hasInClassInitializer()) &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005090 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5091 false))
Richard Smith1c931be2012-04-02 18:40:40 +00005092 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005093
Richard Smith6c4c36c2012-03-30 20:53:28 +00005094 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5095 // -- any direct or virtual base class or non-static data member has a
5096 // type with a destructor that is deleted or inaccessible
5097 if (IsConstructor) {
5098 Sema::SpecialMemberOverloadResult *SMOR =
5099 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5100 false, false, false, false, false);
5101 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5102 return true;
5103 }
5104
Richard Smith9a561d52012-02-26 09:11:52 +00005105 return false;
5106}
5107
5108/// Check whether we should delete a special member function due to the class
5109/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005110bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00005111 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00005112 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00005113}
5114
5115/// Check whether we should delete a special member function due to the class
5116/// having a particular non-static data member.
5117bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5118 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5119 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5120
5121 if (CSM == Sema::CXXDefaultConstructor) {
5122 // For a default constructor, all references must be initialized in-class
5123 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005124 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5125 if (Diagnose)
5126 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5127 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005128 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005129 }
Richard Smith79363f52012-02-27 06:07:25 +00005130 // C++11 [class.ctor]p5: any non-variant non-static data member of
5131 // const-qualified type (or array thereof) with no
5132 // brace-or-equal-initializer does not have a user-provided default
5133 // constructor.
5134 if (!inUnion() && FieldType.isConstQualified() &&
5135 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005136 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5137 if (Diagnose)
5138 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005139 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00005140 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005141 }
5142
5143 if (inUnion() && !FieldType.isConstQualified())
5144 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005145 } else if (CSM == Sema::CXXCopyConstructor) {
5146 // For a copy constructor, data members must not be of rvalue reference
5147 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005148 if (FieldType->isRValueReferenceType()) {
5149 if (Diagnose)
5150 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5151 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00005152 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005153 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005154 } else if (IsAssignment) {
5155 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005156 if (FieldType->isReferenceType()) {
5157 if (Diagnose)
5158 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5159 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005160 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005161 }
5162 if (!FieldRecord && FieldType.isConstQualified()) {
5163 // C++11 [class.copy]p23:
5164 // -- a non-static data member of const non-class type (or array thereof)
5165 if (Diagnose)
5166 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005167 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005168 return true;
5169 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005170 }
5171
5172 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00005173 // Some additional restrictions exist on the variant members.
5174 if (!inUnion() && FieldRecord->isUnion() &&
5175 FieldRecord->isAnonymousStructOrUnion()) {
5176 bool AllVariantFieldsAreConst = true;
5177
Richard Smithdf8dc862012-03-29 19:00:10 +00005178 // FIXME: Handle anonymous unions declared within anonymous unions.
Stephen Hines651f13c2014-04-23 16:59:28 -07005179 for (auto *UI : FieldRecord->fields()) {
Richard Smith7d5088a2012-02-18 02:02:13 +00005180 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00005181
5182 if (!UnionFieldType.isConstQualified())
5183 AllVariantFieldsAreConst = false;
5184
Richard Smith9a561d52012-02-26 09:11:52 +00005185 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5186 if (UnionFieldRecord &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005187 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smith517bb842012-07-18 03:51:16 +00005188 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00005189 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005190 }
5191
5192 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00005193 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005194 !FieldRecord->field_empty()) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005195 if (Diagnose)
5196 S.Diag(FieldRecord->getLocation(),
5197 diag::note_deleted_default_ctor_all_const)
5198 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00005199 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005200 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005201
Richard Smithdf8dc862012-03-29 19:00:10 +00005202 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00005203 // This is technically non-conformant, but sanity demands it.
5204 return false;
5205 }
5206
Richard Smith517bb842012-07-18 03:51:16 +00005207 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5208 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00005209 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005210 }
5211
5212 return false;
5213}
5214
5215/// C++11 [class.ctor] p5:
5216/// A defaulted default constructor for a class X is defined as deleted if
5217/// X is a union and all of its variant members are of const-qualified type.
5218bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00005219 // This is a silly definition, because it gives an empty union a deleted
5220 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005221 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005222 !MD->getParent()->field_empty()) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005223 if (Diagnose)
5224 S.Diag(MD->getParent()->getLocation(),
5225 diag::note_deleted_default_ctor_all_const)
5226 << MD->getParent() << /*not anonymous union*/0;
5227 return true;
5228 }
5229 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005230}
5231
5232/// Determine whether a defaulted special member function should be defined as
5233/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5234/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005235bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5236 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00005237 if (MD->isInvalidDecl())
5238 return false;
Sean Hunte16da072011-10-10 06:18:57 +00005239 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00005240 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00005241 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005242 return false;
5243
Richard Smith7d5088a2012-02-18 02:02:13 +00005244 // C++11 [expr.lambda.prim]p19:
5245 // The closure type associated with a lambda-expression has a
5246 // deleted (8.4.3) default constructor and a deleted copy
5247 // assignment operator.
5248 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005249 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5250 if (Diagnose)
5251 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00005252 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005253 }
5254
Richard Smith5bdaac52012-04-02 20:59:25 +00005255 // For an anonymous struct or union, the copy and assignment special members
5256 // will never be used, so skip the check. For an anonymous union declared at
5257 // namespace scope, the constructor and destructor are used.
5258 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5259 RD->isAnonymousStructOrUnion())
5260 return false;
5261
Richard Smith6c4c36c2012-03-30 20:53:28 +00005262 // C++11 [class.copy]p7, p18:
5263 // If the class definition declares a move constructor or move assignment
5264 // operator, an implicitly declared copy constructor or copy assignment
5265 // operator is defined as deleted.
5266 if (MD->isImplicit() &&
5267 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5268 CXXMethodDecl *UserDeclaredMove = 0;
5269
5270 // In Microsoft mode, a user-declared move only causes the deletion of the
5271 // corresponding copy operation, not both copy operations.
5272 if (RD->hasUserDeclaredMoveConstructor() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005273 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005274 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005275
5276 // Find any user-declared move constructor.
Stephen Hines651f13c2014-04-23 16:59:28 -07005277 for (auto *I : RD->ctors()) {
Richard Smith55798652012-12-08 04:10:18 +00005278 if (I->isMoveConstructor()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005279 UserDeclaredMove = I;
Richard Smith55798652012-12-08 04:10:18 +00005280 break;
5281 }
5282 }
Richard Smith1c931be2012-04-02 18:40:40 +00005283 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005284 } else if (RD->hasUserDeclaredMoveAssignment() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005285 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005286 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005287
5288 // Find any user-declared move assignment operator.
Stephen Hines651f13c2014-04-23 16:59:28 -07005289 for (auto *I : RD->methods()) {
Richard Smith55798652012-12-08 04:10:18 +00005290 if (I->isMoveAssignmentOperator()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005291 UserDeclaredMove = I;
Richard Smith55798652012-12-08 04:10:18 +00005292 break;
5293 }
5294 }
Richard Smith1c931be2012-04-02 18:40:40 +00005295 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005296 }
5297
5298 if (UserDeclaredMove) {
5299 Diag(UserDeclaredMove->getLocation(),
5300 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005301 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005302 << UserDeclaredMove->isMoveAssignmentOperator();
5303 return true;
5304 }
5305 }
Sean Hunte16da072011-10-10 06:18:57 +00005306
Richard Smith5bdaac52012-04-02 20:59:25 +00005307 // Do access control from the special member function
5308 ContextRAII MethodContext(*this, MD);
5309
Richard Smith9a561d52012-02-26 09:11:52 +00005310 // C++11 [class.dtor]p5:
5311 // -- for a virtual destructor, lookup of the non-array deallocation function
5312 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005313 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005314 FunctionDecl *OperatorDelete = 0;
5315 DeclarationName Name =
5316 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5317 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005318 OperatorDelete, false)) {
5319 if (Diagnose)
5320 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005321 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005322 }
Richard Smith9a561d52012-02-26 09:11:52 +00005323 }
5324
Richard Smith6c4c36c2012-03-30 20:53:28 +00005325 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005326
Stephen Hines651f13c2014-04-23 16:59:28 -07005327 for (auto &BI : RD->bases())
5328 if (!BI.isVirtual() &&
5329 SMI.shouldDeleteForBase(&BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005330 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005331
Richard Smithe0883602013-07-22 18:06:23 +00005332 // Per DR1611, do not consider virtual bases of constructors of abstract
5333 // classes, since we are not going to construct them.
Richard Smithcbc820a2013-07-22 02:56:56 +00005334 if (!RD->isAbstract() || !SMI.IsConstructor) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005335 for (auto &BI : RD->vbases())
5336 if (SMI.shouldDeleteForBase(&BI))
Richard Smithcbc820a2013-07-22 02:56:56 +00005337 return true;
5338 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00005339
Stephen Hines651f13c2014-04-23 16:59:28 -07005340 for (auto *FI : RD->fields())
Richard Smith7d5088a2012-02-18 02:02:13 +00005341 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005342 SMI.shouldDeleteForField(FI))
Sean Hunte3406822011-05-20 21:43:47 +00005343 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005344
Richard Smith7d5088a2012-02-18 02:02:13 +00005345 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005346 return true;
5347
5348 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005349}
5350
Richard Smithac713512012-12-08 02:53:02 +00005351/// Perform lookup for a special member of the specified kind, and determine
5352/// whether it is trivial. If the triviality can be determined without the
5353/// lookup, skip it. This is intended for use when determining whether a
5354/// special member of a containing object is trivial, and thus does not ever
5355/// perform overload resolution for default constructors.
5356///
5357/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5358/// member that was most likely to be intended to be trivial, if any.
5359static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5360 Sema::CXXSpecialMember CSM, unsigned Quals,
Stephen Hines651f13c2014-04-23 16:59:28 -07005361 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smithac713512012-12-08 02:53:02 +00005362 if (Selected)
5363 *Selected = 0;
5364
5365 switch (CSM) {
5366 case Sema::CXXInvalid:
5367 llvm_unreachable("not a special member");
5368
5369 case Sema::CXXDefaultConstructor:
5370 // C++11 [class.ctor]p5:
5371 // A default constructor is trivial if:
5372 // - all the [direct subobjects] have trivial default constructors
5373 //
5374 // Note, no overload resolution is performed in this case.
5375 if (RD->hasTrivialDefaultConstructor())
5376 return true;
5377
5378 if (Selected) {
5379 // If there's a default constructor which could have been trivial, dig it
5380 // out. Otherwise, if there's any user-provided default constructor, point
5381 // to that as an example of why there's not a trivial one.
5382 CXXConstructorDecl *DefCtor = 0;
5383 if (RD->needsImplicitDefaultConstructor())
5384 S.DeclareImplicitDefaultConstructor(RD);
Stephen Hines651f13c2014-04-23 16:59:28 -07005385 for (auto *CI : RD->ctors()) {
Richard Smithac713512012-12-08 02:53:02 +00005386 if (!CI->isDefaultConstructor())
5387 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07005388 DefCtor = CI;
Richard Smithac713512012-12-08 02:53:02 +00005389 if (!DefCtor->isUserProvided())
5390 break;
5391 }
5392
5393 *Selected = DefCtor;
5394 }
5395
5396 return false;
5397
5398 case Sema::CXXDestructor:
5399 // C++11 [class.dtor]p5:
5400 // A destructor is trivial if:
5401 // - all the direct [subobjects] have trivial destructors
5402 if (RD->hasTrivialDestructor())
5403 return true;
5404
5405 if (Selected) {
5406 if (RD->needsImplicitDestructor())
5407 S.DeclareImplicitDestructor(RD);
5408 *Selected = RD->getDestructor();
5409 }
5410
5411 return false;
5412
5413 case Sema::CXXCopyConstructor:
5414 // C++11 [class.copy]p12:
5415 // A copy constructor is trivial if:
5416 // - the constructor selected to copy each direct [subobject] is trivial
5417 if (RD->hasTrivialCopyConstructor()) {
5418 if (Quals == Qualifiers::Const)
5419 // We must either select the trivial copy constructor or reach an
5420 // ambiguity; no need to actually perform overload resolution.
5421 return true;
5422 } else if (!Selected) {
5423 return false;
5424 }
5425 // In C++98, we are not supposed to perform overload resolution here, but we
5426 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5427 // cases like B as having a non-trivial copy constructor:
5428 // struct A { template<typename T> A(T&); };
5429 // struct B { mutable A a; };
5430 goto NeedOverloadResolution;
5431
5432 case Sema::CXXCopyAssignment:
5433 // C++11 [class.copy]p25:
5434 // A copy assignment operator is trivial if:
5435 // - the assignment operator selected to copy each direct [subobject] is
5436 // trivial
5437 if (RD->hasTrivialCopyAssignment()) {
5438 if (Quals == Qualifiers::Const)
5439 return true;
5440 } else if (!Selected) {
5441 return false;
5442 }
5443 // In C++98, we are not supposed to perform overload resolution here, but we
5444 // treat that as a language defect.
5445 goto NeedOverloadResolution;
5446
5447 case Sema::CXXMoveConstructor:
5448 case Sema::CXXMoveAssignment:
5449 NeedOverloadResolution:
5450 Sema::SpecialMemberOverloadResult *SMOR =
Stephen Hines651f13c2014-04-23 16:59:28 -07005451 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smithac713512012-12-08 02:53:02 +00005452
5453 // The standard doesn't describe how to behave if the lookup is ambiguous.
5454 // We treat it as not making the member non-trivial, just like the standard
5455 // mandates for the default constructor. This should rarely matter, because
5456 // the member will also be deleted.
5457 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5458 return true;
5459
5460 if (!SMOR->getMethod()) {
5461 assert(SMOR->getKind() ==
5462 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5463 return false;
5464 }
5465
5466 // We deliberately don't check if we found a deleted special member. We're
5467 // not supposed to!
5468 if (Selected)
5469 *Selected = SMOR->getMethod();
5470 return SMOR->getMethod()->isTrivial();
5471 }
5472
5473 llvm_unreachable("unknown special method kind");
5474}
5475
Benjamin Kramera574c892013-02-15 12:30:38 +00005476static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005477 for (auto *CI : RD->ctors())
Richard Smithac713512012-12-08 02:53:02 +00005478 if (!CI->isImplicit())
Stephen Hines651f13c2014-04-23 16:59:28 -07005479 return CI;
Richard Smithac713512012-12-08 02:53:02 +00005480
5481 // Look for constructor templates.
5482 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5483 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5484 if (CXXConstructorDecl *CD =
5485 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5486 return CD;
5487 }
5488
5489 return 0;
5490}
5491
5492/// The kind of subobject we are checking for triviality. The values of this
5493/// enumeration are used in diagnostics.
5494enum TrivialSubobjectKind {
5495 /// The subobject is a base class.
5496 TSK_BaseClass,
5497 /// The subobject is a non-static data member.
5498 TSK_Field,
5499 /// The object is actually the complete object.
5500 TSK_CompleteObject
5501};
5502
5503/// Check whether the special member selected for a given type would be trivial.
5504static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Stephen Hines651f13c2014-04-23 16:59:28 -07005505 QualType SubType, bool ConstRHS,
Richard Smithac713512012-12-08 02:53:02 +00005506 Sema::CXXSpecialMember CSM,
5507 TrivialSubobjectKind Kind,
5508 bool Diagnose) {
5509 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5510 if (!SubRD)
5511 return true;
5512
5513 CXXMethodDecl *Selected;
5514 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Stephen Hines651f13c2014-04-23 16:59:28 -07005515 ConstRHS, Diagnose ? &Selected : 0))
Richard Smithac713512012-12-08 02:53:02 +00005516 return true;
5517
5518 if (Diagnose) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005519 if (ConstRHS)
5520 SubType.addConst();
5521
Richard Smithac713512012-12-08 02:53:02 +00005522 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5523 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5524 << Kind << SubType.getUnqualifiedType();
5525 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5526 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5527 } else if (!Selected)
5528 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5529 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5530 else if (Selected->isUserProvided()) {
5531 if (Kind == TSK_CompleteObject)
5532 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5533 << Kind << SubType.getUnqualifiedType() << CSM;
5534 else {
5535 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5536 << Kind << SubType.getUnqualifiedType() << CSM;
5537 S.Diag(Selected->getLocation(), diag::note_declared_at);
5538 }
5539 } else {
5540 if (Kind != TSK_CompleteObject)
5541 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5542 << Kind << SubType.getUnqualifiedType() << CSM;
5543
5544 // Explain why the defaulted or deleted special member isn't trivial.
5545 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5546 }
5547 }
5548
5549 return false;
5550}
5551
5552/// Check whether the members of a class type allow a special member to be
5553/// trivial.
5554static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5555 Sema::CXXSpecialMember CSM,
5556 bool ConstArg, bool Diagnose) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005557 for (const auto *FI : RD->fields()) {
Richard Smithac713512012-12-08 02:53:02 +00005558 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5559 continue;
5560
5561 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5562
5563 // Pretend anonymous struct or union members are members of this class.
5564 if (FI->isAnonymousStructOrUnion()) {
5565 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5566 CSM, ConstArg, Diagnose))
5567 return false;
5568 continue;
5569 }
5570
5571 // C++11 [class.ctor]p5:
5572 // A default constructor is trivial if [...]
5573 // -- no non-static data member of its class has a
5574 // brace-or-equal-initializer
5575 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5576 if (Diagnose)
Stephen Hines651f13c2014-04-23 16:59:28 -07005577 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smithac713512012-12-08 02:53:02 +00005578 return false;
5579 }
5580
5581 // Objective C ARC 4.3.5:
5582 // [...] nontrivally ownership-qualified types are [...] not trivially
5583 // default constructible, copy constructible, move constructible, copy
5584 // assignable, move assignable, or destructible [...]
5585 if (S.getLangOpts().ObjCAutoRefCount &&
5586 FieldType.hasNonTrivialObjCLifetime()) {
5587 if (Diagnose)
5588 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5589 << RD << FieldType.getObjCLifetime();
5590 return false;
5591 }
5592
Stephen Hines651f13c2014-04-23 16:59:28 -07005593 bool ConstRHS = ConstArg && !FI->isMutable();
5594 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5595 CSM, TSK_Field, Diagnose))
Richard Smithac713512012-12-08 02:53:02 +00005596 return false;
5597 }
5598
5599 return true;
5600}
5601
5602/// Diagnose why the specified class does not have a trivial special member of
5603/// the given kind.
5604void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5605 QualType Ty = Context.getRecordType(RD);
Richard Smithac713512012-12-08 02:53:02 +00005606
Stephen Hines651f13c2014-04-23 16:59:28 -07005607 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5608 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smithac713512012-12-08 02:53:02 +00005609 TSK_CompleteObject, /*Diagnose*/true);
5610}
5611
5612/// Determine whether a defaulted or deleted special member function is trivial,
5613/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5614/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5615bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5616 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005617 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5618
5619 CXXRecordDecl *RD = MD->getParent();
5620
5621 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005622
Richard Smitha8d478e2013-11-04 02:02:27 +00005623 // C++11 [class.copy]p12, p25: [DR1593]
5624 // A [special member] is trivial if [...] its parameter-type-list is
5625 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smithac713512012-12-08 02:53:02 +00005626 switch (CSM) {
5627 case CXXDefaultConstructor:
5628 case CXXDestructor:
5629 // Trivial default constructors and destructors cannot have parameters.
5630 break;
5631
5632 case CXXCopyConstructor:
5633 case CXXCopyAssignment: {
5634 // Trivial copy operations always have const, non-volatile parameter types.
5635 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005636 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005637 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5638 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5639 if (Diagnose)
5640 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5641 << Param0->getSourceRange() << Param0->getType()
5642 << Context.getLValueReferenceType(
5643 Context.getRecordType(RD).withConst());
5644 return false;
5645 }
5646 break;
5647 }
5648
5649 case CXXMoveConstructor:
5650 case CXXMoveAssignment: {
5651 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005652 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005653 const RValueReferenceType *RT =
5654 Param0->getType()->getAs<RValueReferenceType>();
5655 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5656 if (Diagnose)
5657 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5658 << Param0->getSourceRange() << Param0->getType()
5659 << Context.getRValueReferenceType(Context.getRecordType(RD));
5660 return false;
5661 }
5662 break;
5663 }
5664
5665 case CXXInvalid:
5666 llvm_unreachable("not a special member");
5667 }
5668
Richard Smithac713512012-12-08 02:53:02 +00005669 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5670 if (Diagnose)
5671 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5672 diag::note_nontrivial_default_arg)
5673 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5674 return false;
5675 }
5676 if (MD->isVariadic()) {
5677 if (Diagnose)
5678 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5679 return false;
5680 }
5681
5682 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5683 // A copy/move [constructor or assignment operator] is trivial if
5684 // -- the [member] selected to copy/move each direct base class subobject
5685 // is trivial
5686 //
5687 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5688 // A [default constructor or destructor] is trivial if
5689 // -- all the direct base classes have trivial [default constructors or
5690 // destructors]
Stephen Hines651f13c2014-04-23 16:59:28 -07005691 for (const auto &BI : RD->bases())
5692 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
5693 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smithac713512012-12-08 02:53:02 +00005694 return false;
5695
5696 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5697 // A copy/move [constructor or assignment operator] for a class X is
5698 // trivial if
5699 // -- for each non-static data member of X that is of class type (or array
5700 // thereof), the constructor selected to copy/move that member is
5701 // trivial
5702 //
5703 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5704 // A [default constructor or destructor] is trivial if
5705 // -- for all of the non-static data members of its class that are of class
5706 // type (or array thereof), each such class has a trivial [default
5707 // constructor or destructor]
5708 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5709 return false;
5710
5711 // C++11 [class.dtor]p5:
5712 // A destructor is trivial if [...]
5713 // -- the destructor is not virtual
5714 if (CSM == CXXDestructor && MD->isVirtual()) {
5715 if (Diagnose)
5716 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5717 return false;
5718 }
5719
5720 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5721 // A [special member] for class X is trivial if [...]
5722 // -- class X has no virtual functions and no virtual base classes
5723 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5724 if (!Diagnose)
5725 return false;
5726
5727 if (RD->getNumVBases()) {
5728 // Check for virtual bases. We already know that the corresponding
5729 // member in all bases is trivial, so vbases must all be direct.
5730 CXXBaseSpecifier &BS = *RD->vbases_begin();
5731 assert(BS.isVirtual());
5732 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5733 return false;
5734 }
5735
5736 // Must have a virtual method.
Stephen Hines651f13c2014-04-23 16:59:28 -07005737 for (const auto *MI : RD->methods()) {
Richard Smithac713512012-12-08 02:53:02 +00005738 if (MI->isVirtual()) {
5739 SourceLocation MLoc = MI->getLocStart();
5740 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5741 return false;
5742 }
5743 }
5744
5745 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5746 }
5747
5748 // Looks like it's trivial!
5749 return true;
5750}
5751
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005752/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005753namespace {
5754 struct FindHiddenVirtualMethodData {
5755 Sema *S;
5756 CXXMethodDecl *Method;
5757 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005758 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005759 };
5760}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005761
David Blaikie5f750682012-10-19 00:53:08 +00005762/// \brief Check whether any most overriden method from MD in Methods
5763static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5764 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5765 if (MD->size_overridden_methods() == 0)
5766 return Methods.count(MD->getCanonicalDecl());
5767 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5768 E = MD->end_overridden_methods();
5769 I != E; ++I)
5770 if (CheckMostOverridenMethods(*I, Methods))
5771 return true;
5772 return false;
5773}
5774
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005775/// \brief Member lookup function that determines whether a given C++
5776/// method overloads virtual methods in a base class without overriding any,
5777/// to be used with CXXRecordDecl::lookupInBases().
5778static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5779 CXXBasePath &Path,
5780 void *UserData) {
5781 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5782
5783 FindHiddenVirtualMethodData &Data
5784 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5785
5786 DeclarationName Name = Data.Method->getDeclName();
5787 assert(Name.getNameKind() == DeclarationName::Identifier);
5788
5789 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005790 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005791 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005792 !Path.Decls.empty();
5793 Path.Decls = Path.Decls.slice(1)) {
5794 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005795 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005796 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005797 foundSameNameMethod = true;
5798 // Interested only in hidden virtual methods.
5799 if (!MD->isVirtual())
5800 continue;
5801 // If the method we are checking overrides a method from its base
5802 // don't warn about the other overloaded methods.
5803 if (!Data.S->IsOverload(Data.Method, MD, false))
5804 return true;
5805 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005806 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005807 overloadedMethods.push_back(MD);
5808 }
5809 }
5810
5811 if (foundSameNameMethod)
5812 Data.OverloadedMethods.append(overloadedMethods.begin(),
5813 overloadedMethods.end());
5814 return foundSameNameMethod;
5815}
5816
David Blaikie5f750682012-10-19 00:53:08 +00005817/// \brief Add the most overriden methods from MD to Methods
5818static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5819 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5820 if (MD->size_overridden_methods() == 0)
5821 Methods.insert(MD->getCanonicalDecl());
5822 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5823 E = MD->end_overridden_methods();
5824 I != E; ++I)
5825 AddMostOverridenMethods(*I, Methods);
5826}
5827
Eli Friedmandae92712013-09-05 23:51:03 +00005828/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005829/// overriding any.
Eli Friedmandae92712013-09-05 23:51:03 +00005830void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5831 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramerc4704422012-05-19 16:03:58 +00005832 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005833 return;
5834
5835 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5836 /*bool RecordPaths=*/false,
5837 /*bool DetectVirtual=*/false);
5838 FindHiddenVirtualMethodData Data;
5839 Data.Method = MD;
5840 Data.S = this;
5841
5842 // Keep the base methods that were overriden or introduced in the subclass
5843 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmandae92712013-09-05 23:51:03 +00005844 CXXRecordDecl *DC = MD->getParent();
David Blaikie3bc93e32012-12-19 00:45:41 +00005845 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5846 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5847 NamedDecl *ND = *I;
5848 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005849 ND = shad->getTargetDecl();
5850 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5851 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005852 }
5853
Eli Friedmandae92712013-09-05 23:51:03 +00005854 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5855 OverloadedMethods = Data.OverloadedMethods;
5856}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005857
Eli Friedmandae92712013-09-05 23:51:03 +00005858void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5859 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5860 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5861 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5862 PartialDiagnostic PD = PDiag(
5863 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5864 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5865 Diag(overloadedMD->getLocation(), PD);
5866 }
5867}
5868
5869/// \brief Diagnose methods which overload virtual methods in a base class
5870/// without overriding any.
5871void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5872 if (MD->isInvalidDecl())
5873 return;
5874
5875 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5876 MD->getLocation()) == DiagnosticsEngine::Ignored)
5877 return;
5878
5879 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5880 FindHiddenVirtualMethods(MD, OverloadedMethods);
5881 if (!OverloadedMethods.empty()) {
5882 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5883 << MD << (OverloadedMethods.size() > 1);
5884
5885 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005886 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005887}
5888
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005889void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005890 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005891 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005892 SourceLocation RBrac,
5893 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005894 if (!TagDecl)
5895 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005896
Douglas Gregor42af25f2009-05-11 19:58:34 +00005897 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005898
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005899 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5900 if (l->getKind() != AttributeList::AT_Visibility)
5901 continue;
5902 l->setInvalid();
5903 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5904 l->getName();
5905 }
5906
David Blaikie77b6de02011-09-22 02:58:26 +00005907 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005908 // strict aliasing violation!
5909 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005910 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005911
Douglas Gregor23c94db2010-07-02 17:43:08 +00005912 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005913 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005914}
5915
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005916/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5917/// special functions, such as the default constructor, copy
5918/// constructor, or destructor, to the given C++ class (C++
5919/// [special]p1). This routine can only be executed just before the
5920/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005921void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005922 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005923 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005924
Richard Smithbc2a35d2012-12-08 08:32:28 +00005925 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005926 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005927
Richard Smithbc2a35d2012-12-08 08:32:28 +00005928 // If the properties or semantics of the copy constructor couldn't be
5929 // determined while the class was being declared, force a declaration
5930 // of it now.
5931 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5932 DeclareImplicitCopyConstructor(ClassDecl);
5933 }
5934
Richard Smith80ad52f2013-01-02 11:42:31 +00005935 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005936 ++ASTContext::NumImplicitMoveConstructors;
5937
Richard Smithbc2a35d2012-12-08 08:32:28 +00005938 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5939 DeclareImplicitMoveConstructor(ClassDecl);
5940 }
5941
Douglas Gregora376d102010-07-02 21:50:04 +00005942 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5943 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005944
5945 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005946 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005947 // it shows up in the right place in the vtable and that we diagnose
5948 // problems with the implicit exception specification.
5949 if (ClassDecl->isDynamicClass() ||
5950 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005951 DeclareImplicitCopyAssignment(ClassDecl);
5952 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005953
Richard Smith80ad52f2013-01-02 11:42:31 +00005954 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005955 ++ASTContext::NumImplicitMoveAssignmentOperators;
5956
5957 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005958 if (ClassDecl->isDynamicClass() ||
5959 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005960 DeclareImplicitMoveAssignment(ClassDecl);
5961 }
5962
Douglas Gregor4923aa22010-07-02 20:37:36 +00005963 if (!ClassDecl->hasUserDeclaredDestructor()) {
5964 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005965
5966 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005967 // have to declare the destructor immediately. This ensures that, e.g., it
5968 // shows up in the right place in the vtable and that we diagnose problems
5969 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005970 if (ClassDecl->isDynamicClass() ||
5971 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005972 DeclareImplicitDestructor(ClassDecl);
5973 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005974}
5975
Francois Pichet8387e2a2011-04-22 22:18:13 +00005976void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5977 if (!D)
5978 return;
5979
5980 int NumParamList = D->getNumTemplateParameterLists();
5981 for (int i = 0; i < NumParamList; i++) {
5982 TemplateParameterList* Params = D->getTemplateParameterList(i);
5983 for (TemplateParameterList::iterator Param = Params->begin(),
5984 ParamEnd = Params->end();
5985 Param != ParamEnd; ++Param) {
5986 NamedDecl *Named = cast<NamedDecl>(*Param);
5987 if (Named->getDeclName()) {
5988 S->AddDecl(Named);
5989 IdResolver.AddDecl(Named);
5990 }
5991 }
5992 }
5993}
5994
John McCalld226f652010-08-21 09:40:31 +00005995void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005996 if (!D)
5997 return;
5998
5999 TemplateParameterList *Params = 0;
6000 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
6001 Params = Template->getTemplateParameters();
6002 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
6003 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6004 Params = PartialSpec->getTemplateParameters();
6005 else
Douglas Gregor6569d682009-05-27 23:11:45 +00006006 return;
6007
Douglas Gregor6569d682009-05-27 23:11:45 +00006008 for (TemplateParameterList::iterator Param = Params->begin(),
6009 ParamEnd = Params->end();
6010 Param != ParamEnd; ++Param) {
6011 NamedDecl *Named = cast<NamedDecl>(*Param);
6012 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00006013 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00006014 IdResolver.AddDecl(Named);
6015 }
6016 }
6017}
6018
John McCalld226f652010-08-21 09:40:31 +00006019void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00006020 if (!RecordD) return;
6021 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00006022 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00006023 PushDeclContext(S, Record);
6024}
6025
John McCalld226f652010-08-21 09:40:31 +00006026void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00006027 if (!RecordD) return;
6028 PopDeclContext();
6029}
6030
Stephen Hines651f13c2014-04-23 16:59:28 -07006031/// This is used to implement the constant expression evaluation part of the
6032/// attribute enable_if extension. There is nothing in standard C++ which would
6033/// require reentering parameters.
6034void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6035 if (!Param)
6036 return;
6037
6038 S->AddDecl(Param);
6039 if (Param->getDeclName())
6040 IdResolver.AddDecl(Param);
6041}
6042
Douglas Gregor72b505b2008-12-16 21:30:33 +00006043/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6044/// parsing a top-level (non-nested) C++ class, and we are now
6045/// parsing those parts of the given Method declaration that could
6046/// not be parsed earlier (C++ [class.mem]p2), such as default
6047/// arguments. This action should enter the scope of the given
6048/// Method declaration as if we had just parsed the qualified method
6049/// name. However, it should not bring the parameters into scope;
6050/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00006051void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006052}
6053
6054/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6055/// C++ method declaration. We're (re-)introducing the given
6056/// function parameter into scope for use in parsing later parts of
6057/// the method declaration. For example, we could see an
6058/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00006059void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006060 if (!ParamD)
6061 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006062
John McCalld226f652010-08-21 09:40:31 +00006063 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00006064
6065 // If this parameter has an unparsed default argument, clear it out
6066 // to make way for the parsed default argument.
6067 if (Param->hasUnparsedDefaultArg())
6068 Param->setDefaultArg(0);
6069
John McCalld226f652010-08-21 09:40:31 +00006070 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006071 if (Param->getDeclName())
6072 IdResolver.AddDecl(Param);
6073}
6074
6075/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6076/// processing the delayed method declaration for Method. The method
6077/// declaration is now considered finished. There may be a separate
6078/// ActOnStartOfFunctionDef action later (not necessarily
6079/// immediately!) for this method, if it was also defined inside the
6080/// class body.
John McCalld226f652010-08-21 09:40:31 +00006081void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006082 if (!MethodD)
6083 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006084
Douglas Gregorefd5bda2009-08-24 11:57:43 +00006085 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00006086
John McCalld226f652010-08-21 09:40:31 +00006087 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006088
6089 // Now that we have our default arguments, check the constructor
6090 // again. It could produce additional diagnostics or affect whether
6091 // the class has implicitly-declared destructors, among other
6092 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00006093 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6094 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006095
6096 // Check the default arguments, which we may have added.
6097 if (!Method->isInvalidDecl())
6098 CheckCXXDefaultArguments(Method);
6099}
6100
Douglas Gregor42a552f2008-11-05 20:51:48 +00006101/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00006102/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00006103/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006104/// emit diagnostics and set the invalid bit to true. In any case, the type
6105/// will be updated to reflect a well-formed type for the constructor and
6106/// returned.
6107QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006108 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006109 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006110
6111 // C++ [class.ctor]p3:
6112 // A constructor shall not be virtual (10.3) or static (9.4). A
6113 // constructor can be invoked for a const, volatile or const
6114 // volatile object. A constructor shall not be declared const,
6115 // volatile, or const volatile (9.3.2).
6116 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00006117 if (!D.isInvalidType())
6118 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6119 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6120 << SourceRange(D.getIdentifierLoc());
6121 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006122 }
John McCalld931b082010-08-26 03:08:43 +00006123 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006124 if (!D.isInvalidType())
6125 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6126 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6127 << SourceRange(D.getIdentifierLoc());
6128 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006129 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006130 }
Mike Stump1eb44332009-09-09 15:08:12 +00006131
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006132 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006133 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00006134 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006135 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6136 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006137 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006138 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6139 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006140 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006141 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6142 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00006143 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006144 }
Mike Stump1eb44332009-09-09 15:08:12 +00006145
Douglas Gregorc938c162011-01-26 05:01:58 +00006146 // C++0x [class.ctor]p4:
6147 // A constructor shall not be declared with a ref-qualifier.
6148 if (FTI.hasRefQualifier()) {
6149 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6150 << FTI.RefQualifierIsLValueRef
6151 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6152 D.setInvalidType();
6153 }
6154
Douglas Gregor42a552f2008-11-05 20:51:48 +00006155 // Rebuild the function type "R" without any type qualifiers (in
6156 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00006157 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00006158 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07006159 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalle23cf432010-12-14 08:05:40 +00006160 return R;
6161
6162 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6163 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006164 EPI.RefQualifier = RQ_None;
Stephen Hines651f13c2014-04-23 16:59:28 -07006165
6166 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006167}
6168
Douglas Gregor72b505b2008-12-16 21:30:33 +00006169/// CheckConstructor - Checks a fully-formed constructor for
6170/// well-formedness, issuing any diagnostics required. Returns true if
6171/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00006172void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00006173 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00006174 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6175 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00006176 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006177
6178 // C++ [class.copy]p3:
6179 // A declaration of a constructor for a class X is ill-formed if
6180 // its first parameter is of type (optionally cv-qualified) X and
6181 // either there are no other parameters or else all other
6182 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00006183 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006184 ((Constructor->getNumParams() == 1) ||
6185 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00006186 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6187 Constructor->getTemplateSpecializationKind()
6188 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006189 QualType ParamType = Constructor->getParamDecl(0)->getType();
6190 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6191 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00006192 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006193 const char *ConstRef
6194 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6195 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00006196 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006197 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00006198
6199 // FIXME: Rather that making the constructor invalid, we should endeavor
6200 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00006201 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006202 }
6203 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00006204}
6205
John McCall15442822010-08-04 01:04:25 +00006206/// CheckDestructor - Checks a fully-formed destructor definition for
6207/// well-formedness, issuing any diagnostics required. Returns true
6208/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006209bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006210 CXXRecordDecl *RD = Destructor->getParent();
6211
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006212 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006213 SourceLocation Loc;
6214
6215 if (!Destructor->isImplicit())
6216 Loc = Destructor->getLocation();
6217 else
6218 Loc = RD->getLocation();
6219
6220 // If we have a virtual destructor, look up the deallocation function
6221 FunctionDecl *OperatorDelete = 0;
6222 DeclarationName Name =
6223 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006224 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00006225 return true;
Bill Wendlingc12b43a2013-12-07 23:53:50 +00006226 // If there's no class-specific operator delete, look up the global
6227 // non-array delete.
6228 if (!OperatorDelete)
6229 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall5efd91a2010-07-03 18:33:00 +00006230
Eli Friedman5f2987c2012-02-02 03:46:19 +00006231 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00006232
6233 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00006234 }
Anders Carlsson37909802009-11-30 21:24:50 +00006235
6236 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00006237}
6238
Mike Stump1eb44332009-09-09 15:08:12 +00006239static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006240FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
Stephen Hines651f13c2014-04-23 16:59:28 -07006241 return (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
6242 FTI.Params[0].Param &&
6243 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006244}
6245
Douglas Gregor42a552f2008-11-05 20:51:48 +00006246/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6247/// the well-formednes of the destructor declarator @p D with type @p
6248/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006249/// emit diagnostics and set the declarator to invalid. Even if this happens,
6250/// will be updated to reflect a well-formed type for the destructor and
6251/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00006252QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006253 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006254 // C++ [class.dtor]p1:
6255 // [...] A typedef-name that names a class is a class-name
6256 // (7.1.3); however, a typedef-name that names a class shall not
6257 // be used as the identifier in the declarator for a destructor
6258 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006259 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00006260 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00006261 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00006262 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00006263 else if (const TemplateSpecializationType *TST =
6264 DeclaratorType->getAs<TemplateSpecializationType>())
6265 if (TST->isTypeAlias())
6266 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6267 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006268
6269 // C++ [class.dtor]p2:
6270 // A destructor is used to destroy objects of its class type. A
6271 // destructor takes no parameters, and no return type can be
6272 // specified for it (not even void). The address of a destructor
6273 // shall not be taken. A destructor shall not be static. A
6274 // destructor can be invoked for a const, volatile or const
6275 // volatile object. A destructor shall not be declared const,
6276 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00006277 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006278 if (!D.isInvalidType())
6279 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6280 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00006281 << SourceRange(D.getIdentifierLoc())
6282 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6283
John McCalld931b082010-08-26 03:08:43 +00006284 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006285 }
Chris Lattner65401802009-04-25 08:28:21 +00006286 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006287 // Destructors don't have return types, but the parser will
6288 // happily parse something like:
6289 //
6290 // class X {
6291 // float ~X();
6292 // };
6293 //
6294 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006295 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6296 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6297 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00006298 }
Mike Stump1eb44332009-09-09 15:08:12 +00006299
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006300 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006301 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006302 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006303 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6304 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006305 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006306 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6307 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006308 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006309 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6310 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006311 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006312 }
6313
Douglas Gregorc938c162011-01-26 05:01:58 +00006314 // C++0x [class.dtor]p2:
6315 // A destructor shall not be declared with a ref-qualifier.
6316 if (FTI.hasRefQualifier()) {
6317 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6318 << FTI.RefQualifierIsLValueRef
6319 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6320 D.setInvalidType();
6321 }
6322
Douglas Gregor42a552f2008-11-05 20:51:48 +00006323 // Make sure we don't have any parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -07006324 if (FTI.NumParams > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006325 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6326
6327 // Delete the parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -07006328 FTI.freeParams();
Chris Lattner65401802009-04-25 08:28:21 +00006329 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006330 }
6331
Mike Stump1eb44332009-09-09 15:08:12 +00006332 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006333 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006334 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006335 D.setInvalidType();
6336 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006337
6338 // Rebuild the function type "R" without any type qualifiers or
6339 // parameters (in case any of the errors above fired) and with
6340 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006341 // types.
John McCalle23cf432010-12-14 08:05:40 +00006342 if (!D.isInvalidType())
6343 return R;
6344
Douglas Gregord92ec472010-07-01 05:10:53 +00006345 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006346 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6347 EPI.Variadic = false;
6348 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006349 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006350 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006351}
6352
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006353/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6354/// well-formednes of the conversion function declarator @p D with
6355/// type @p R. If there are any errors in the declarator, this routine
6356/// will emit diagnostics and return true. Otherwise, it will return
6357/// false. Either way, the type @p R will be updated to reflect a
6358/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006359void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006360 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006361 // C++ [class.conv.fct]p1:
6362 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006363 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006364 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006365 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006366 if (!D.isInvalidType())
6367 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006368 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6369 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006370 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006371 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006372 }
John McCalla3f81372010-04-13 00:04:31 +00006373
6374 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6375
Chris Lattner6e475012009-04-25 08:35:12 +00006376 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006377 // Conversion functions don't have return types, but the parser will
6378 // happily parse something like:
6379 //
6380 // class X {
6381 // float operator bool();
6382 // };
6383 //
6384 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006385 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6386 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6387 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006388 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006389 }
6390
John McCalla3f81372010-04-13 00:04:31 +00006391 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6392
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006393 // Make sure we don't have any parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -07006394 if (Proto->getNumParams() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006395 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6396
6397 // Delete the parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -07006398 D.getFunctionTypeInfo().freeParams();
Chris Lattner6e475012009-04-25 08:35:12 +00006399 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006400 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006401 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006402 D.setInvalidType();
6403 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006404
John McCalla3f81372010-04-13 00:04:31 +00006405 // Diagnose "&operator bool()" and other such nonsense. This
6406 // is actually a gcc extension which we don't support.
Stephen Hines651f13c2014-04-23 16:59:28 -07006407 if (Proto->getReturnType() != ConvType) {
John McCalla3f81372010-04-13 00:04:31 +00006408 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Stephen Hines651f13c2014-04-23 16:59:28 -07006409 << Proto->getReturnType();
John McCalla3f81372010-04-13 00:04:31 +00006410 D.setInvalidType();
Stephen Hines651f13c2014-04-23 16:59:28 -07006411 ConvType = Proto->getReturnType();
John McCalla3f81372010-04-13 00:04:31 +00006412 }
6413
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006414 // C++ [class.conv.fct]p4:
6415 // The conversion-type-id shall not represent a function type nor
6416 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006417 if (ConvType->isArrayType()) {
6418 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6419 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006420 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006421 } else if (ConvType->isFunctionType()) {
6422 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6423 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006424 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006425 }
6426
6427 // Rebuild the function type "R" without any parameters (in case any
6428 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006429 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006430 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006431 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006432
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006433 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006434 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006435 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006436 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006437 diag::warn_cxx98_compat_explicit_conversion_functions :
6438 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006439 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006440}
6441
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006442/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6443/// the declaration of the given C++ conversion function. This routine
6444/// is responsible for recording the conversion function in the C++
6445/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006446Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006447 assert(Conversion && "Expected to receive a conversion function declaration");
6448
Douglas Gregor9d350972008-12-12 08:25:50 +00006449 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006450
6451 // Make sure we aren't redeclaring the conversion function.
6452 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006453
6454 // C++ [class.conv.fct]p1:
6455 // [...] A conversion function is never used to convert a
6456 // (possibly cv-qualified) object to the (possibly cv-qualified)
6457 // same object type (or a reference to it), to a (possibly
6458 // cv-qualified) base class of that type (or a reference to it),
6459 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006460 // FIXME: Suppress this warning if the conversion function ends up being a
6461 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006462 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006463 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006464 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006465 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006466 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6467 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006468 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006469 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006470 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6471 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006472 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006473 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006474 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006475 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006476 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006477 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006478 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006479 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006480 }
6481
Douglas Gregore80622f2010-09-29 04:25:11 +00006482 if (FunctionTemplateDecl *ConversionTemplate
6483 = Conversion->getDescribedFunctionTemplate())
6484 return ConversionTemplate;
6485
John McCalld226f652010-08-21 09:40:31 +00006486 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006487}
6488
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006489//===----------------------------------------------------------------------===//
6490// Namespace Handling
6491//===----------------------------------------------------------------------===//
6492
Richard Smithd1a55a62012-10-04 22:13:39 +00006493/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6494/// reopened.
6495static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6496 SourceLocation Loc,
6497 IdentifierInfo *II, bool *IsInline,
6498 NamespaceDecl *PrevNS) {
6499 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006500
Richard Smithc969e6a2012-10-05 01:46:25 +00006501 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6502 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6503 // inline namespaces, with the intention of bringing names into namespace std.
6504 //
6505 // We support this just well enough to get that case working; this is not
6506 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006507 if (*IsInline && II && II->getName().startswith("__atomic") &&
6508 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006509 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006510 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6511 NS = NS->getPreviousDecl())
6512 NS->setInline(*IsInline);
6513 // Patch up the lookup table for the containing namespace. This isn't really
6514 // correct, but it's good enough for this particular case.
Stephen Hines651f13c2014-04-23 16:59:28 -07006515 for (auto *I : PrevNS->decls())
6516 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smithd1a55a62012-10-04 22:13:39 +00006517 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6518 return;
6519 }
6520
6521 if (PrevNS->isInline())
6522 // The user probably just forgot the 'inline', so suggest that it
6523 // be added back.
6524 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6525 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6526 else
Stephen Hines651f13c2014-04-23 16:59:28 -07006527 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smithd1a55a62012-10-04 22:13:39 +00006528
6529 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6530 *IsInline = PrevNS->isInline();
6531}
John McCallea318642010-08-26 09:15:37 +00006532
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006533/// ActOnStartNamespaceDef - This is called at the start of a namespace
6534/// definition.
John McCalld226f652010-08-21 09:40:31 +00006535Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006536 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006537 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006538 SourceLocation IdentLoc,
6539 IdentifierInfo *II,
6540 SourceLocation LBrace,
6541 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006542 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6543 // For anonymous namespace, take the location of the left brace.
6544 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006545 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006546 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006547 bool IsStd = false;
6548 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006549 Scope *DeclRegionScope = NamespcScope->getParent();
6550
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006551 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006552 if (II) {
6553 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006554 // The identifier in an original-namespace-definition shall not
6555 // have been previously defined in the declarative region in
6556 // which the original-namespace-definition appears. The
6557 // identifier in an original-namespace-definition is the name of
6558 // the namespace. Subsequently in that declarative region, it is
6559 // treated as an original-namespace-name.
6560 //
6561 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006562 // look through using directives, just look for any ordinary names.
6563
6564 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006565 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6566 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006567 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006568 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6569 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6570 ++I) {
6571 if ((*I)->getIdentifierNamespace() & IDNS) {
6572 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006573 break;
6574 }
6575 }
6576
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006577 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6578
6579 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006580 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006581 if (IsInline != PrevNS->isInline())
6582 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6583 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006584 } else if (PrevDecl) {
6585 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006586 Diag(Loc, diag::err_redefinition_different_kind)
6587 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006588 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006589 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006590 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006591 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006592 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006593 // This is the first "real" definition of the namespace "std", so update
6594 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006595 PrevNS = getStdNamespace();
6596 IsStd = true;
6597 AddToKnown = !IsInline;
6598 } else {
6599 // We've seen this namespace for the first time.
6600 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006601 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006602 } else {
John McCall9aeed322009-10-01 00:25:31 +00006603 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006604
6605 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006606 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006607 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006608 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006609 } else {
6610 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006611 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006612 }
6613
Richard Smithd1a55a62012-10-04 22:13:39 +00006614 if (PrevNS && IsInline != PrevNS->isInline())
6615 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6616 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006617 }
6618
6619 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6620 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006621 if (IsInvalid)
6622 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006623
6624 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006625
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006626 // FIXME: Should we be merging attributes?
6627 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006628 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006629
6630 if (IsStd)
6631 StdNamespace = Namespc;
6632 if (AddToKnown)
6633 KnownNamespaces[Namespc] = false;
6634
6635 if (II) {
6636 PushOnScopeChains(Namespc, DeclRegionScope);
6637 } else {
6638 // Link the anonymous namespace into its parent.
6639 DeclContext *Parent = CurContext->getRedeclContext();
6640 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6641 TU->setAnonymousNamespace(Namespc);
6642 } else {
6643 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006644 }
John McCall9aeed322009-10-01 00:25:31 +00006645
Douglas Gregora4181472010-03-24 00:46:35 +00006646 CurContext->addDecl(Namespc);
6647
John McCall9aeed322009-10-01 00:25:31 +00006648 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6649 // behaves as if it were replaced by
6650 // namespace unique { /* empty body */ }
6651 // using namespace unique;
6652 // namespace unique { namespace-body }
6653 // where all occurrences of 'unique' in a translation unit are
6654 // replaced by the same identifier and this identifier differs
6655 // from all other identifiers in the entire program.
6656
6657 // We just create the namespace with an empty name and then add an
6658 // implicit using declaration, just like the standard suggests.
6659 //
6660 // CodeGen enforces the "universally unique" aspect by giving all
6661 // declarations semantically contained within an anonymous
6662 // namespace internal linkage.
6663
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006664 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006665 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006666 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006667 /* 'using' */ LBrace,
6668 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006669 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006670 /* identifier */ SourceLocation(),
6671 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006672 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006673 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006674 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006675 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006676 }
6677
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006678 ActOnDocumentableDecl(Namespc);
6679
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006680 // Although we could have an invalid decl (i.e. the namespace name is a
6681 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006682 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6683 // for the namespace has the declarations that showed up in that particular
6684 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006685 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006686 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006687}
6688
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006689/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6690/// is a namespace alias, returns the namespace it points to.
6691static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6692 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6693 return AD->getNamespace();
6694 return dyn_cast_or_null<NamespaceDecl>(D);
6695}
6696
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006697/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6698/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006699void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006700 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6701 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006702 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006703 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006704 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006705 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006706}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006707
John McCall384aff82010-08-25 07:42:41 +00006708CXXRecordDecl *Sema::getStdBadAlloc() const {
6709 return cast_or_null<CXXRecordDecl>(
6710 StdBadAlloc.get(Context.getExternalSource()));
6711}
6712
6713NamespaceDecl *Sema::getStdNamespace() const {
6714 return cast_or_null<NamespaceDecl>(
6715 StdNamespace.get(Context.getExternalSource()));
6716}
6717
Douglas Gregor66992202010-06-29 17:53:46 +00006718/// \brief Retrieve the special "std" namespace, which may require us to
6719/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006720NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006721 if (!StdNamespace) {
6722 // The "std" namespace has not yet been defined, so build one implicitly.
6723 StdNamespace = NamespaceDecl::Create(Context,
6724 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006725 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006726 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006727 &PP.getIdentifierTable().get("std"),
6728 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006729 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006730 }
6731
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006732 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006733}
6734
Sebastian Redl395e04d2012-01-17 22:49:33 +00006735bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006736 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006737 "Looking for std::initializer_list outside of C++.");
6738
6739 // We're looking for implicit instantiations of
6740 // template <typename E> class std::initializer_list.
6741
6742 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6743 return false;
6744
Sebastian Redl84760e32012-01-17 22:49:58 +00006745 ClassTemplateDecl *Template = 0;
6746 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006747
Sebastian Redl84760e32012-01-17 22:49:58 +00006748 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006749
Sebastian Redl84760e32012-01-17 22:49:58 +00006750 ClassTemplateSpecializationDecl *Specialization =
6751 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6752 if (!Specialization)
6753 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006754
Sebastian Redl84760e32012-01-17 22:49:58 +00006755 Template = Specialization->getSpecializedTemplate();
6756 Arguments = Specialization->getTemplateArgs().data();
6757 } else if (const TemplateSpecializationType *TST =
6758 Ty->getAs<TemplateSpecializationType>()) {
6759 Template = dyn_cast_or_null<ClassTemplateDecl>(
6760 TST->getTemplateName().getAsTemplateDecl());
6761 Arguments = TST->getArgs();
6762 }
6763 if (!Template)
6764 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006765
6766 if (!StdInitializerList) {
6767 // Haven't recognized std::initializer_list yet, maybe this is it.
6768 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6769 if (TemplateClass->getIdentifier() !=
6770 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006771 !getStdNamespace()->InEnclosingNamespaceSetOf(
6772 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006773 return false;
6774 // This is a template called std::initializer_list, but is it the right
6775 // template?
6776 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006777 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006778 return false;
6779 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6780 return false;
6781
6782 // It's the right template.
6783 StdInitializerList = Template;
6784 }
6785
6786 if (Template != StdInitializerList)
6787 return false;
6788
6789 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006790 if (Element)
6791 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006792 return true;
6793}
6794
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006795static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6796 NamespaceDecl *Std = S.getStdNamespace();
6797 if (!Std) {
6798 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6799 return 0;
6800 }
6801
6802 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6803 Loc, Sema::LookupOrdinaryName);
6804 if (!S.LookupQualifiedName(Result, Std)) {
6805 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6806 return 0;
6807 }
6808 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6809 if (!Template) {
6810 Result.suppressDiagnostics();
6811 // We found something weird. Complain about the first thing we found.
6812 NamedDecl *Found = *Result.begin();
6813 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6814 return 0;
6815 }
6816
6817 // We found some template called std::initializer_list. Now verify that it's
6818 // correct.
6819 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006820 if (Params->getMinRequiredArguments() != 1 ||
6821 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006822 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6823 return 0;
6824 }
6825
6826 return Template;
6827}
6828
6829QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6830 if (!StdInitializerList) {
6831 StdInitializerList = LookupStdInitializerList(*this, Loc);
6832 if (!StdInitializerList)
6833 return QualType();
6834 }
6835
6836 TemplateArgumentListInfo Args(Loc, Loc);
6837 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6838 Context.getTrivialTypeSourceInfo(Element,
6839 Loc)));
6840 return Context.getCanonicalType(
6841 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6842}
6843
Sebastian Redl98d36062012-01-17 22:50:14 +00006844bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6845 // C++ [dcl.init.list]p2:
6846 // A constructor is an initializer-list constructor if its first parameter
6847 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6848 // std::initializer_list<E> for some type E, and either there are no other
6849 // parameters or else all other parameters have default arguments.
6850 if (Ctor->getNumParams() < 1 ||
6851 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6852 return false;
6853
6854 QualType ArgType = Ctor->getParamDecl(0)->getType();
6855 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6856 ArgType = RT->getPointeeType().getUnqualifiedType();
6857
6858 return isStdInitializerList(ArgType, 0);
6859}
6860
Douglas Gregor9172aa62011-03-26 22:25:30 +00006861/// \brief Determine whether a using statement is in a context where it will be
6862/// apply in all contexts.
6863static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6864 switch (CurContext->getDeclKind()) {
6865 case Decl::TranslationUnit:
6866 return true;
6867 case Decl::LinkageSpec:
6868 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6869 default:
6870 return false;
6871 }
6872}
6873
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006874namespace {
6875
6876// Callback to only accept typo corrections that are namespaces.
6877class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00006878public:
Stephen Hines651f13c2014-04-23 16:59:28 -07006879 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00006880 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006881 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006882 return false;
6883 }
6884};
6885
6886}
6887
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006888static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6889 CXXScopeSpec &SS,
6890 SourceLocation IdentLoc,
6891 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006892 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006893 R.clear();
6894 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006895 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006896 Validator)) {
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006897 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +00006898 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6899 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006900 Ident->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +00006901 S.diagnoseTypo(Corrected,
6902 S.PDiag(diag::err_using_directive_member_suggest)
6903 << Ident << DC << DroppedSpecifier << SS.getRange(),
6904 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006905 } else {
Richard Smith2d670972013-08-17 00:46:16 +00006906 S.diagnoseTypo(Corrected,
6907 S.PDiag(diag::err_using_directive_suggest) << Ident,
6908 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006909 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006910 R.addDecl(Corrected.getCorrectionDecl());
6911 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006912 }
6913 return false;
6914}
6915
John McCalld226f652010-08-21 09:40:31 +00006916Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006917 SourceLocation UsingLoc,
6918 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006919 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006920 SourceLocation IdentLoc,
6921 IdentifierInfo *NamespcName,
6922 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006923 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6924 assert(NamespcName && "Invalid NamespcName.");
6925 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006926
6927 // This can only happen along a recovery path.
6928 while (S->getFlags() & Scope::TemplateParamScope)
6929 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006930 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006931
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006932 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006933 NestedNameSpecifier *Qualifier = 0;
6934 if (SS.isSet())
Stephen Hines651f13c2014-04-23 16:59:28 -07006935 Qualifier = SS.getScopeRep();
Douglas Gregor66992202010-06-29 17:53:46 +00006936
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006937 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006938 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6939 LookupParsedName(R, S, &SS);
6940 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006941 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006942
Douglas Gregor66992202010-06-29 17:53:46 +00006943 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006944 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006945 // Allow "using namespace std;" or "using namespace ::std;" even if
6946 // "std" hasn't been defined yet, for GCC compatibility.
6947 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6948 NamespcName->isStr("std")) {
6949 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006950 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006951 R.resolveKind();
6952 }
6953 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006954 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006955 }
6956
John McCallf36e02d2009-10-09 21:13:30 +00006957 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006958 NamedDecl *Named = R.getFoundDecl();
6959 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6960 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006961 // C++ [namespace.udir]p1:
6962 // A using-directive specifies that the names in the nominated
6963 // namespace can be used in the scope in which the
6964 // using-directive appears after the using-directive. During
6965 // unqualified name lookup (3.4.1), the names appear as if they
6966 // were declared in the nearest enclosing namespace which
6967 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006968 // namespace. [Note: in this context, "contains" means "contains
6969 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006970
6971 // Find enclosing context containing both using-directive and
6972 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006973 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006974 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6975 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6976 CommonAncestor = CommonAncestor->getParent();
6977
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006978 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006979 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006980 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006981
Douglas Gregor9172aa62011-03-26 22:25:30 +00006982 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman24146972013-08-22 00:27:10 +00006983 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006984 Diag(IdentLoc, diag::warn_using_directive_in_header);
6985 }
6986
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006987 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006988 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006989 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006990 }
6991
Richard Smith6b3d3e52013-02-20 19:22:51 +00006992 if (UDir)
6993 ProcessDeclAttributeList(S, UDir, AttrList);
6994
John McCalld226f652010-08-21 09:40:31 +00006995 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006996}
6997
6998void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006999 // If the scope has an associated entity and the using directive is at
7000 // namespace or translation unit scope, add the UsingDirectiveDecl into
7001 // its lookup structure so qualified name lookup can find it.
Ted Kremenekf0d58612013-10-08 17:08:03 +00007002 DeclContext *Ctx = S->getEntity();
Richard Smith1b7f9cb2012-03-13 03:12:56 +00007003 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007004 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00007005 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00007006 // Otherwise, it is at block sope. The using-directives will affect lookup
7007 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00007008 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00007009}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007010
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007011
John McCalld226f652010-08-21 09:40:31 +00007012Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00007013 AccessSpecifier AS,
7014 bool HasUsingKeyword,
7015 SourceLocation UsingLoc,
7016 CXXScopeSpec &SS,
7017 UnqualifiedId &Name,
7018 AttributeList *AttrList,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007019 bool HasTypenameKeyword,
John McCall78b81052010-11-10 02:40:36 +00007020 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007021 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00007022
Douglas Gregor12c118a2009-11-04 16:30:06 +00007023 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00007024 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00007025 case UnqualifiedId::IK_Identifier:
7026 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00007027 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00007028 case UnqualifiedId::IK_ConversionFunctionId:
7029 break;
7030
7031 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00007032 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00007033 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00007034 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00007035 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00007036 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00007037 diag::err_using_decl_constructor)
7038 << SS.getRange();
7039
Richard Smith80ad52f2013-01-02 11:42:31 +00007040 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00007041
John McCalld226f652010-08-21 09:40:31 +00007042 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00007043
7044 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00007045 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00007046 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007047 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00007048
7049 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00007050 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00007051 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00007052 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00007053 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007054
7055 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7056 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00007057 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00007058 return 0;
John McCall604e7f12009-12-08 07:46:18 +00007059
Richard Smith07b0fdc2013-03-18 21:12:30 +00007060 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00007061 if (!HasUsingKeyword) {
Enea Zaffanellad4de59d2013-07-17 17:28:56 +00007062 Diag(Name.getLocStart(),
Richard Smith1b2209f2013-06-13 02:12:17 +00007063 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7064 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00007065 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00007066 }
7067
Douglas Gregor56c04582010-12-16 00:46:58 +00007068 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7069 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7070 return 0;
7071
John McCall9488ea12009-11-17 05:59:44 +00007072 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007073 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007074 /* IsInstantiation */ false,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007075 HasTypenameKeyword, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00007076 if (UD)
7077 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00007078
John McCalld226f652010-08-21 09:40:31 +00007079 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00007080}
7081
Douglas Gregor09acc982010-07-07 23:08:52 +00007082/// \brief Determine whether a using declaration considers the given
7083/// declarations as "equivalent", e.g., if they are redeclarations of
7084/// the same entity or are both typedefs of the same type.
Richard Smithf06a28932013-10-23 02:17:46 +00007085static bool
7086IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7087 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor09acc982010-07-07 23:08:52 +00007088 return true;
Douglas Gregor09acc982010-07-07 23:08:52 +00007089
Richard Smith162e1c12011-04-15 14:24:37 +00007090 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithf06a28932013-10-23 02:17:46 +00007091 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor09acc982010-07-07 23:08:52 +00007092 return Context.hasSameType(TD1->getUnderlyingType(),
7093 TD2->getUnderlyingType());
Douglas Gregor09acc982010-07-07 23:08:52 +00007094
7095 return false;
7096}
7097
7098
John McCall9f54ad42009-12-10 09:41:52 +00007099/// Determines whether to create a using shadow decl for a particular
7100/// decl, given the set of decls existing prior to this using lookup.
7101bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithf06a28932013-10-23 02:17:46 +00007102 const LookupResult &Previous,
7103 UsingShadowDecl *&PrevShadow) {
John McCall9f54ad42009-12-10 09:41:52 +00007104 // Diagnose finding a decl which is not from a base class of the
7105 // current class. We do this now because there are cases where this
7106 // function will silently decide not to build a shadow decl, which
7107 // will pre-empt further diagnostics.
7108 //
7109 // We don't need to do this in C++0x because we do the check once on
7110 // the qualifier.
7111 //
7112 // FIXME: diagnose the following if we care enough:
7113 // struct A { int foo; };
7114 // struct B : A { using A::foo; };
7115 // template <class T> struct C : A {};
7116 // template <class T> struct D : C<T> { using B::foo; } // <---
7117 // This is invalid (during instantiation) in C++03 because B::foo
7118 // resolves to the using decl in B, which is not a base class of D<T>.
7119 // We can't diagnose it immediately because C<T> is an unknown
7120 // specialization. The UsingShadowDecl in D<T> then points directly
7121 // to A::foo, which will look well-formed when we instantiate.
7122 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00007123 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00007124 DeclContext *OrigDC = Orig->getDeclContext();
7125
7126 // Handle enums and anonymous structs.
7127 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7128 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7129 while (OrigRec->isAnonymousStructOrUnion())
7130 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7131
7132 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7133 if (OrigDC == CurContext) {
7134 Diag(Using->getLocation(),
7135 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007136 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007137 Diag(Orig->getLocation(), diag::note_using_decl_target);
7138 return true;
7139 }
7140
Douglas Gregordc355712011-02-25 00:36:19 +00007141 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00007142 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007143 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00007144 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00007145 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007146 Diag(Orig->getLocation(), diag::note_using_decl_target);
7147 return true;
7148 }
7149 }
7150
7151 if (Previous.empty()) return false;
7152
7153 NamedDecl *Target = Orig;
7154 if (isa<UsingShadowDecl>(Target))
7155 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7156
John McCalld7533ec2009-12-11 02:33:26 +00007157 // If the target happens to be one of the previous declarations, we
7158 // don't have a conflict.
7159 //
7160 // FIXME: but we might be increasing its access, in which case we
7161 // should redeclare it.
7162 NamedDecl *NonTag = 0, *Tag = 0;
Richard Smithf06a28932013-10-23 02:17:46 +00007163 bool FoundEquivalentDecl = false;
John McCalld7533ec2009-12-11 02:33:26 +00007164 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7165 I != E; ++I) {
7166 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithf06a28932013-10-23 02:17:46 +00007167 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7168 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7169 PrevShadow = Shadow;
7170 FoundEquivalentDecl = true;
7171 }
John McCalld7533ec2009-12-11 02:33:26 +00007172
7173 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7174 }
7175
Richard Smithf06a28932013-10-23 02:17:46 +00007176 if (FoundEquivalentDecl)
7177 return false;
7178
Stephen Hines651f13c2014-04-23 16:59:28 -07007179 if (FunctionDecl *FD = Target->getAsFunction()) {
John McCall9f54ad42009-12-10 09:41:52 +00007180 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00007181 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00007182 case Ovl_Overload:
7183 return false;
7184
7185 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00007186 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007187 break;
Stephen Hines651f13c2014-04-23 16:59:28 -07007188
John McCall9f54ad42009-12-10 09:41:52 +00007189 // We found a decl with the exact signature.
7190 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007191 // If we're in a record, we want to hide the target, so we
7192 // return true (without a diagnostic) to tell the caller not to
7193 // build a shadow decl.
7194 if (CurContext->isRecord())
7195 return true;
7196
7197 // If we're not in a record, this is an error.
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;
7200 }
7201
7202 Diag(Target->getLocation(), diag::note_using_decl_target);
7203 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7204 return true;
7205 }
7206
7207 // Target is not a function.
7208
John McCall9f54ad42009-12-10 09:41:52 +00007209 if (isa<TagDecl>(Target)) {
7210 // No conflict between a tag and a non-tag.
7211 if (!Tag) return false;
7212
John McCall41ce66f2009-12-10 19:51:03 +00007213 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007214 Diag(Target->getLocation(), diag::note_using_decl_target);
7215 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7216 return true;
7217 }
7218
7219 // No conflict between a tag and a non-tag.
7220 if (!NonTag) return false;
7221
John McCall41ce66f2009-12-10 19:51:03 +00007222 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007223 Diag(Target->getLocation(), diag::note_using_decl_target);
7224 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7225 return true;
7226}
7227
John McCall9488ea12009-11-17 05:59:44 +00007228/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00007229UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00007230 UsingDecl *UD,
Richard Smithf06a28932013-10-23 02:17:46 +00007231 NamedDecl *Orig,
7232 UsingShadowDecl *PrevDecl) {
John McCall9488ea12009-11-17 05:59:44 +00007233
7234 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00007235 NamedDecl *Target = Orig;
7236 if (isa<UsingShadowDecl>(Target)) {
7237 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7238 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00007239 }
Richard Smithf06a28932013-10-23 02:17:46 +00007240
John McCall9488ea12009-11-17 05:59:44 +00007241 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00007242 = UsingShadowDecl::Create(Context, CurContext,
7243 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00007244 UD->addShadowDecl(Shadow);
Richard Smithf06a28932013-10-23 02:17:46 +00007245
Douglas Gregore80622f2010-09-29 04:25:11 +00007246 Shadow->setAccess(UD->getAccess());
7247 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7248 Shadow->setInvalidDecl();
Richard Smithf06a28932013-10-23 02:17:46 +00007249
7250 Shadow->setPreviousDecl(PrevDecl);
7251
John McCall9488ea12009-11-17 05:59:44 +00007252 if (S)
John McCall604e7f12009-12-08 07:46:18 +00007253 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00007254 else
John McCall604e7f12009-12-08 07:46:18 +00007255 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00007256
John McCall604e7f12009-12-08 07:46:18 +00007257
John McCall9f54ad42009-12-10 09:41:52 +00007258 return Shadow;
7259}
John McCall604e7f12009-12-08 07:46:18 +00007260
John McCall9f54ad42009-12-10 09:41:52 +00007261/// Hides a using shadow declaration. This is required by the current
7262/// using-decl implementation when a resolvable using declaration in a
7263/// class is followed by a declaration which would hide or override
7264/// one or more of the using decl's targets; for example:
7265///
7266/// struct Base { void foo(int); };
7267/// struct Derived : Base {
7268/// using Base::foo;
7269/// void foo(int);
7270/// };
7271///
7272/// The governing language is C++03 [namespace.udecl]p12:
7273///
7274/// When a using-declaration brings names from a base class into a
7275/// derived class scope, member functions in the derived class
7276/// override and/or hide member functions with the same name and
7277/// parameter types in a base class (rather than conflicting).
7278///
7279/// There are two ways to implement this:
7280/// (1) optimistically create shadow decls when they're not hidden
7281/// by existing declarations, or
7282/// (2) don't create any shadow decls (or at least don't make them
7283/// visible) until we've fully parsed/instantiated the class.
7284/// The problem with (1) is that we might have to retroactively remove
7285/// a shadow decl, which requires several O(n) operations because the
7286/// decl structures are (very reasonably) not designed for removal.
7287/// (2) avoids this but is very fiddly and phase-dependent.
7288void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007289 if (Shadow->getDeclName().getNameKind() ==
7290 DeclarationName::CXXConversionFunctionName)
7291 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7292
John McCall9f54ad42009-12-10 09:41:52 +00007293 // Remove it from the DeclContext...
7294 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007295
John McCall9f54ad42009-12-10 09:41:52 +00007296 // ...and the scope, if applicable...
7297 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007298 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007299 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007300 }
7301
John McCall9f54ad42009-12-10 09:41:52 +00007302 // ...and the using decl.
7303 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7304
7305 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007306 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007307}
7308
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007309namespace {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007310class UsingValidatorCCC : public CorrectionCandidateCallback {
7311public:
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007312 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7313 bool RequireMember)
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007314 : HasTypenameKeyword(HasTypenameKeyword),
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007315 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007316
Stephen Hines651f13c2014-04-23 16:59:28 -07007317 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007318 NamedDecl *ND = Candidate.getCorrectionDecl();
7319
7320 // Keywords are not valid here.
7321 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007322 return false;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007323
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007324 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7325 !isa<TypeDecl>(ND))
7326 return false;
7327
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007328 // Completely unqualified names are invalid for a 'using' declaration.
7329 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7330 return false;
7331
7332 if (isa<TypeDecl>(ND))
7333 return HasTypenameKeyword || !IsInstantiation;
7334
7335 return !HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007336 }
7337
7338private:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007339 bool HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007340 bool IsInstantiation;
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007341 bool RequireMember;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007342};
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007343} // end anonymous namespace
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007344
John McCall7ba107a2009-11-18 02:36:19 +00007345/// Builds a using declaration.
7346///
7347/// \param IsInstantiation - Whether this call arises from an
7348/// instantiation of an unresolved using declaration. We treat
7349/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007350NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7351 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007352 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007353 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007354 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007355 bool IsInstantiation,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007356 bool HasTypenameKeyword,
John McCall7ba107a2009-11-18 02:36:19 +00007357 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007358 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007359 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007360 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007361
Anders Carlsson550b14b2009-08-28 05:49:21 +00007362 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007363
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007364 if (SS.isEmpty()) {
7365 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007366 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007367 }
Mike Stump1eb44332009-09-09 15:08:12 +00007368
John McCall9f54ad42009-12-10 09:41:52 +00007369 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007370 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007371 ForRedeclaration);
7372 Previous.setHideTags(false);
7373 if (S) {
7374 LookupName(Previous, S);
7375
7376 // It is really dumb that we have to do this.
7377 LookupResult::Filter F = Previous.makeFilter();
7378 while (F.hasNext()) {
7379 NamedDecl *D = F.next();
7380 if (!isDeclInScope(D, CurContext, S))
7381 F.erase();
7382 }
7383 F.done();
7384 } else {
7385 assert(IsInstantiation && "no scope in non-instantiation");
7386 assert(CurContext->isRecord() && "scope not record in instantiation");
7387 LookupQualifiedName(Previous, CurContext);
7388 }
7389
John McCall9f54ad42009-12-10 09:41:52 +00007390 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007391 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7392 SS, IdentLoc, Previous))
John McCall9f54ad42009-12-10 09:41:52 +00007393 return 0;
7394
7395 // Check for bad qualifiers.
Stephen Hines651f13c2014-04-23 16:59:28 -07007396 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
John McCalled976492009-12-04 22:46:56 +00007397 return 0;
7398
John McCallaf8e6ed2009-11-12 03:15:40 +00007399 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007400 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007401 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007402 if (!LookupContext) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007403 if (HasTypenameKeyword) {
John McCalled976492009-12-04 22:46:56 +00007404 // FIXME: not all declaration name kinds are legal here
7405 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7406 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007407 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007408 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007409 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007410 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7411 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007412 }
John McCalled976492009-12-04 22:46:56 +00007413 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007414 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007415 NameInfo, HasTypenameKeyword);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007416 }
John McCalled976492009-12-04 22:46:56 +00007417 D->setAccess(AS);
7418 CurContext->addDecl(D);
7419
7420 if (!LookupContext) return D;
7421 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007422
John McCall77bb1aa2010-05-01 00:40:08 +00007423 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007424 UD->setInvalidDecl();
7425 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007426 }
7427
Richard Smithc5a89a12012-04-02 01:30:27 +00007428 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007429 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007430 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007431 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007432 return UD;
7433 }
7434
7435 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007436
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007437 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007438
John McCall604e7f12009-12-08 07:46:18 +00007439 // Unlike most lookups, we don't always want to hide tag
7440 // declarations: tag names are visible through the using declaration
7441 // even if hidden by ordinary names, *except* in a dependent context
7442 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007443 if (!IsInstantiation)
7444 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007445
John McCallb9abd8722012-04-07 03:04:20 +00007446 // For the purposes of this lookup, we have a base object type
7447 // equal to that of the current context.
7448 if (CurContext->isRecord()) {
7449 R.setBaseObjectType(
7450 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7451 }
7452
John McCalla24dc2e2009-11-17 02:14:36 +00007453 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007454
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007455 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00007456 if (R.empty()) {
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007457 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7458 CurContext->isRecord());
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007459 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7460 R.getLookupKind(), S, &SS, CCC)){
7461 // We reject any correction for which ND would be NULL.
7462 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007463 R.setLookupName(Corrected.getCorrection());
7464 R.addDecl(ND);
Richard Smith2d670972013-08-17 00:46:16 +00007465 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007466 // literal '0' below.
Richard Smith2d670972013-08-17 00:46:16 +00007467 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7468 << NameInfo.getName() << LookupContext << 0
7469 << SS.getRange());
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007470 } else {
Richard Smith2d670972013-08-17 00:46:16 +00007471 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007472 << NameInfo.getName() << LookupContext << SS.getRange();
7473 UD->setInvalidDecl();
7474 return UD;
7475 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007476 }
7477
John McCalled976492009-12-04 22:46:56 +00007478 if (R.isAmbiguous()) {
7479 UD->setInvalidDecl();
7480 return UD;
7481 }
Mike Stump1eb44332009-09-09 15:08:12 +00007482
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007483 if (HasTypenameKeyword) {
John McCall7ba107a2009-11-18 02:36:19 +00007484 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007485 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007486 Diag(IdentLoc, diag::err_using_typename_non_type);
7487 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7488 Diag((*I)->getUnderlyingDecl()->getLocation(),
7489 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007490 UD->setInvalidDecl();
7491 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007492 }
7493 } else {
7494 // If we asked for a non-typename and we got a type, error out,
7495 // but only if this is an instantiation of an unresolved using
7496 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007497 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007498 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7499 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007500 UD->setInvalidDecl();
7501 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007502 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007503 }
7504
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007505 // C++0x N2914 [namespace.udecl]p6:
7506 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007507 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007508 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7509 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007510 UD->setInvalidDecl();
7511 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007512 }
Mike Stump1eb44332009-09-09 15:08:12 +00007513
John McCall9f54ad42009-12-10 09:41:52 +00007514 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf06a28932013-10-23 02:17:46 +00007515 UsingShadowDecl *PrevDecl = 0;
7516 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7517 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall9f54ad42009-12-10 09:41:52 +00007518 }
John McCall9488ea12009-11-17 05:59:44 +00007519
7520 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007521}
7522
Sebastian Redlf677ea32011-02-05 19:23:19 +00007523/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007524bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007525 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007526
Douglas Gregordc355712011-02-25 00:36:19 +00007527 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007528 assert(SourceType &&
7529 "Using decl naming constructor doesn't have type in scope spec.");
7530 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7531
7532 // Check whether the named type is a direct base class.
7533 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7534 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7535 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7536 BaseIt != BaseE; ++BaseIt) {
7537 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7538 if (CanonicalSourceType == BaseType)
7539 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007540 if (BaseIt->getType()->isDependentType())
7541 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007542 }
7543
7544 if (BaseIt == BaseE) {
7545 // Did not find SourceType in the bases.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007546 Diag(UD->getUsingLoc(),
Sebastian Redlf677ea32011-02-05 19:23:19 +00007547 diag::err_using_decl_constructor_not_in_direct_base)
7548 << UD->getNameInfo().getSourceRange()
7549 << QualType(SourceType, 0) << TargetClass;
7550 return true;
7551 }
7552
Richard Smithc5a89a12012-04-02 01:30:27 +00007553 if (!CurContext->isDependentContext())
7554 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007555
7556 return false;
7557}
7558
John McCall9f54ad42009-12-10 09:41:52 +00007559/// Checks that the given using declaration is not an invalid
7560/// redeclaration. Note that this is checking only for the using decl
7561/// itself, not for any ill-formedness among the UsingShadowDecls.
7562bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007563 bool HasTypenameKeyword,
John McCall9f54ad42009-12-10 09:41:52 +00007564 const CXXScopeSpec &SS,
7565 SourceLocation NameLoc,
7566 const LookupResult &Prev) {
7567 // C++03 [namespace.udecl]p8:
7568 // C++0x [namespace.udecl]p10:
7569 // A using-declaration is a declaration and can therefore be used
7570 // repeatedly where (and only where) multiple declarations are
7571 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007572 //
John McCall8a726212010-11-29 18:01:58 +00007573 // That's in non-member contexts.
7574 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007575 return false;
7576
Stephen Hines651f13c2014-04-23 16:59:28 -07007577 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall9f54ad42009-12-10 09:41:52 +00007578
7579 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7580 NamedDecl *D = *I;
7581
7582 bool DTypename;
7583 NestedNameSpecifier *DQual;
7584 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007585 DTypename = UD->hasTypename();
Douglas Gregordc355712011-02-25 00:36:19 +00007586 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007587 } else if (UnresolvedUsingValueDecl *UD
7588 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7589 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007590 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007591 } else if (UnresolvedUsingTypenameDecl *UD
7592 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7593 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007594 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007595 } else continue;
7596
7597 // using decls differ if one says 'typename' and the other doesn't.
7598 // FIXME: non-dependent using decls?
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007599 if (HasTypenameKeyword != DTypename) continue;
John McCall9f54ad42009-12-10 09:41:52 +00007600
7601 // using decls differ if they name different scopes (but note that
7602 // template instantiation can cause this check to trigger when it
7603 // didn't before instantiation).
7604 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7605 Context.getCanonicalNestedNameSpecifier(DQual))
7606 continue;
7607
7608 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007609 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007610 return true;
7611 }
7612
7613 return false;
7614}
7615
John McCall604e7f12009-12-08 07:46:18 +00007616
John McCalled976492009-12-04 22:46:56 +00007617/// Checks that the given nested-name qualifier used in a using decl
7618/// in the current context is appropriately related to the current
7619/// scope. If an error is found, diagnoses it and returns true.
7620bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7621 const CXXScopeSpec &SS,
Stephen Hines651f13c2014-04-23 16:59:28 -07007622 const DeclarationNameInfo &NameInfo,
John McCalled976492009-12-04 22:46:56 +00007623 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007624 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007625
John McCall604e7f12009-12-08 07:46:18 +00007626 if (!CurContext->isRecord()) {
7627 // C++03 [namespace.udecl]p3:
7628 // C++0x [namespace.udecl]p8:
7629 // A using-declaration for a class member shall be a member-declaration.
7630
7631 // If we weren't able to compute a valid scope, it must be a
7632 // dependent class scope.
7633 if (!NamedContext || NamedContext->isRecord()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07007634 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7635 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
7636 RD = 0;
7637
John McCall604e7f12009-12-08 07:46:18 +00007638 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7639 << SS.getRange();
Stephen Hines651f13c2014-04-23 16:59:28 -07007640
7641 // If we have a complete, non-dependent source type, try to suggest a
7642 // way to get the same effect.
7643 if (!RD)
7644 return true;
7645
7646 // Find what this using-declaration was referring to.
7647 LookupResult R(*this, NameInfo, LookupOrdinaryName);
7648 R.setHideTags(false);
7649 R.suppressDiagnostics();
7650 LookupQualifiedName(R, RD);
7651
7652 if (R.getAsSingle<TypeDecl>()) {
7653 if (getLangOpts().CPlusPlus11) {
7654 // Convert 'using X::Y;' to 'using Y = X::Y;'.
7655 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7656 << 0 // alias declaration
7657 << FixItHint::CreateInsertion(SS.getBeginLoc(),
7658 NameInfo.getName().getAsString() +
7659 " = ");
7660 } else {
7661 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7662 SourceLocation InsertLoc =
7663 PP.getLocForEndOfToken(NameInfo.getLocEnd());
7664 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7665 << 1 // typedef declaration
7666 << FixItHint::CreateReplacement(UsingLoc, "typedef")
7667 << FixItHint::CreateInsertion(
7668 InsertLoc, " " + NameInfo.getName().getAsString());
7669 }
7670 } else if (R.getAsSingle<VarDecl>()) {
7671 // Don't provide a fixit outside C++11 mode; we don't want to suggest
7672 // repeating the type of the static data member here.
7673 FixItHint FixIt;
7674 if (getLangOpts().CPlusPlus11) {
7675 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7676 FixIt = FixItHint::CreateReplacement(
7677 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7678 }
7679
7680 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
7681 << 2 // reference declaration
7682 << FixIt;
7683 }
John McCall604e7f12009-12-08 07:46:18 +00007684 return true;
7685 }
7686
7687 // Otherwise, everything is known to be fine.
7688 return false;
7689 }
7690
7691 // The current scope is a record.
7692
7693 // If the named context is dependent, we can't decide much.
7694 if (!NamedContext) {
7695 // FIXME: in C++0x, we can diagnose if we can prove that the
7696 // nested-name-specifier does not refer to a base class, which is
7697 // still possible in some cases.
7698
7699 // Otherwise we have to conservatively report that things might be
7700 // okay.
7701 return false;
7702 }
7703
7704 if (!NamedContext->isRecord()) {
7705 // Ideally this would point at the last name in the specifier,
7706 // but we don't have that level of source info.
7707 Diag(SS.getRange().getBegin(),
7708 diag::err_using_decl_nested_name_specifier_is_not_class)
Stephen Hines651f13c2014-04-23 16:59:28 -07007709 << SS.getScopeRep() << SS.getRange();
John McCall604e7f12009-12-08 07:46:18 +00007710 return true;
7711 }
7712
Douglas Gregor6fb07292010-12-21 07:41:49 +00007713 if (!NamedContext->isDependentContext() &&
7714 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7715 return true;
7716
Richard Smith80ad52f2013-01-02 11:42:31 +00007717 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007718 // C++0x [namespace.udecl]p3:
7719 // In a using-declaration used as a member-declaration, the
7720 // nested-name-specifier shall name a base class of the class
7721 // being defined.
7722
7723 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7724 cast<CXXRecordDecl>(NamedContext))) {
7725 if (CurContext == NamedContext) {
7726 Diag(NameLoc,
7727 diag::err_using_decl_nested_name_specifier_is_current_class)
7728 << SS.getRange();
7729 return true;
7730 }
7731
7732 Diag(SS.getRange().getBegin(),
7733 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Stephen Hines651f13c2014-04-23 16:59:28 -07007734 << SS.getScopeRep()
John McCall604e7f12009-12-08 07:46:18 +00007735 << cast<CXXRecordDecl>(CurContext)
7736 << SS.getRange();
7737 return true;
7738 }
7739
7740 return false;
7741 }
7742
7743 // C++03 [namespace.udecl]p4:
7744 // A using-declaration used as a member-declaration shall refer
7745 // to a member of a base class of the class being defined [etc.].
7746
7747 // Salient point: SS doesn't have to name a base class as long as
7748 // lookup only finds members from base classes. Therefore we can
7749 // diagnose here only if we can prove that that can't happen,
7750 // i.e. if the class hierarchies provably don't intersect.
7751
7752 // TODO: it would be nice if "definitely valid" results were cached
7753 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7754 // need to be repeated.
7755
7756 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007757 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007758
7759 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7760 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7761 Data->Bases.insert(Base);
7762 return true;
7763 }
7764
7765 bool hasDependentBases(const CXXRecordDecl *Class) {
7766 return !Class->forallBases(collect, this);
7767 }
7768
7769 /// Returns true if the base is dependent or is one of the
7770 /// accumulated base classes.
7771 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7772 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7773 return !Data->Bases.count(Base);
7774 }
7775
7776 bool mightShareBases(const CXXRecordDecl *Class) {
7777 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7778 }
7779 };
7780
7781 UserData Data;
7782
7783 // Returns false if we find a dependent base.
7784 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7785 return false;
7786
7787 // Returns false if the class has a dependent base or if it or one
7788 // of its bases is present in the base set of the current context.
7789 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7790 return false;
7791
7792 Diag(SS.getRange().getBegin(),
7793 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Stephen Hines651f13c2014-04-23 16:59:28 -07007794 << SS.getScopeRep()
John McCall604e7f12009-12-08 07:46:18 +00007795 << cast<CXXRecordDecl>(CurContext)
7796 << SS.getRange();
7797
7798 return true;
John McCalled976492009-12-04 22:46:56 +00007799}
7800
Richard Smith162e1c12011-04-15 14:24:37 +00007801Decl *Sema::ActOnAliasDeclaration(Scope *S,
7802 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007803 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007804 SourceLocation UsingLoc,
7805 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007806 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007807 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007808 // Skip up to the relevant declaration scope.
7809 while (S->getFlags() & Scope::TemplateParamScope)
7810 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007811 assert((S->getFlags() & Scope::DeclScope) &&
7812 "got alias-declaration outside of declaration scope");
7813
7814 if (Type.isInvalid())
7815 return 0;
7816
7817 bool Invalid = false;
7818 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7819 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007820 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007821
7822 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7823 return 0;
7824
7825 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007826 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007827 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007828 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7829 TInfo->getTypeLoc().getBeginLoc());
7830 }
Richard Smith162e1c12011-04-15 14:24:37 +00007831
7832 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7833 LookupName(Previous, S);
7834
7835 // Warn about shadowing the name of a template parameter.
7836 if (Previous.isSingleResult() &&
7837 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007838 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007839 Previous.clear();
7840 }
7841
7842 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7843 "name in alias declaration must be an identifier");
7844 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7845 Name.StartLocation,
7846 Name.Identifier, TInfo);
7847
7848 NewTD->setAccess(AS);
7849
7850 if (Invalid)
7851 NewTD->setInvalidDecl();
7852
Richard Smith6b3d3e52013-02-20 19:22:51 +00007853 ProcessDeclAttributeList(S, NewTD, AttrList);
7854
Richard Smith3e4c6c42011-05-05 21:57:07 +00007855 CheckTypedefForVariablyModifiedType(S, NewTD);
7856 Invalid |= NewTD->isInvalidDecl();
7857
Richard Smith162e1c12011-04-15 14:24:37 +00007858 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007859
7860 NamedDecl *NewND;
7861 if (TemplateParamLists.size()) {
7862 TypeAliasTemplateDecl *OldDecl = 0;
7863 TemplateParameterList *OldTemplateParams = 0;
7864
7865 if (TemplateParamLists.size() != 1) {
7866 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007867 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7868 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007869 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007870 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007871
7872 // Only consider previous declarations in the same scope.
7873 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7874 /*ExplicitInstantiationOrSpecialization*/false);
7875 if (!Previous.empty()) {
7876 Redeclaration = true;
7877
7878 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7879 if (!OldDecl && !Invalid) {
7880 Diag(UsingLoc, diag::err_redefinition_different_kind)
7881 << Name.Identifier;
7882
7883 NamedDecl *OldD = Previous.getRepresentativeDecl();
7884 if (OldD->getLocation().isValid())
7885 Diag(OldD->getLocation(), diag::note_previous_definition);
7886
7887 Invalid = true;
7888 }
7889
7890 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7891 if (TemplateParameterListsAreEqual(TemplateParams,
7892 OldDecl->getTemplateParameters(),
7893 /*Complain=*/true,
7894 TPL_TemplateMatch))
7895 OldTemplateParams = OldDecl->getTemplateParameters();
7896 else
7897 Invalid = true;
7898
7899 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7900 if (!Invalid &&
7901 !Context.hasSameType(OldTD->getUnderlyingType(),
7902 NewTD->getUnderlyingType())) {
7903 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7904 // but we can't reasonably accept it.
7905 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7906 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7907 if (OldTD->getLocation().isValid())
7908 Diag(OldTD->getLocation(), diag::note_previous_definition);
7909 Invalid = true;
7910 }
7911 }
7912 }
7913
7914 // Merge any previous default template arguments into our parameters,
7915 // and check the parameter list.
7916 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7917 TPC_TypeAliasTemplate))
7918 return 0;
7919
7920 TypeAliasTemplateDecl *NewDecl =
7921 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7922 Name.Identifier, TemplateParams,
7923 NewTD);
7924
7925 NewDecl->setAccess(AS);
7926
7927 if (Invalid)
7928 NewDecl->setInvalidDecl();
7929 else if (OldDecl)
Rafael Espindolabc650912013-10-17 15:37:26 +00007930 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007931
7932 NewND = NewDecl;
7933 } else {
7934 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7935 NewND = NewTD;
7936 }
Richard Smith162e1c12011-04-15 14:24:37 +00007937
7938 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007939 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007940
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007941 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007942 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007943}
7944
John McCalld226f652010-08-21 09:40:31 +00007945Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007946 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007947 SourceLocation AliasLoc,
7948 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007949 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007950 SourceLocation IdentLoc,
7951 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007952
Anders Carlsson81c85c42009-03-28 23:53:49 +00007953 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007954 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7955 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007956
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007957 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007958 NamedDecl *PrevDecl
7959 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7960 ForRedeclaration);
7961 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7962 PrevDecl = 0;
7963
7964 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007965 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007966 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007967 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007968 // FIXME: At some point, we'll want to create the (redundant)
7969 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007970 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007971 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007972 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007973 }
Mike Stump1eb44332009-09-09 15:08:12 +00007974
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007975 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7976 diag::err_redefinition_different_kind;
7977 Diag(AliasLoc, DiagID) << Alias;
7978 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007979 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007980 }
7981
John McCalla24dc2e2009-11-17 02:14:36 +00007982 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007983 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007984
John McCallf36e02d2009-10-09 21:13:30 +00007985 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007986 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007987 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007988 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007989 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007990 }
Mike Stump1eb44332009-09-09 15:08:12 +00007991
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007992 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007993 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007994 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007995 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007996
John McCall3dbd3d52010-02-16 06:53:13 +00007997 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007998 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007999}
8000
Sean Hunt001cad92011-05-10 00:49:42 +00008001Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008002Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8003 CXXMethodDecl *MD) {
8004 CXXRecordDecl *ClassDecl = MD->getParent();
8005
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008006 // C++ [except.spec]p14:
8007 // An implicitly declared special member function (Clause 12) shall have an
8008 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00008009 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008010 if (ClassDecl->isInvalidDecl())
8011 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008012
Sebastian Redl60618fa2011-03-12 11:50:43 +00008013 // Direct base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008014 for (const auto &B : ClassDecl->bases()) {
8015 if (B.isVirtual()) // Handled below.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008016 continue;
8017
Stephen Hines651f13c2014-04-23 16:59:28 -07008018 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor18274032010-07-03 00:47:00 +00008019 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00008020 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8021 // If this is a deleted function, add it anyway. This might be conformant
8022 // with the standard. This might not. I'm not sure. It might not matter.
8023 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -07008024 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00008025 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008026 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008027
8028 // Virtual base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008029 for (const auto &B : ClassDecl->vbases()) {
8030 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor18274032010-07-03 00:47:00 +00008031 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00008032 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8033 // If this is a deleted function, add it anyway. This might be conformant
8034 // with the standard. This might not. I'm not sure. It might not matter.
8035 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -07008036 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00008037 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008038 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008039
8040 // Field constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008041 for (const auto *F : ClassDecl->fields()) {
Richard Smith7a614d82011-06-11 17:19:42 +00008042 if (F->hasInClassInitializer()) {
8043 if (Expr *E = F->getInClassInitializer())
8044 ExceptSpec.CalledExpr(E);
8045 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00008046 // DR1351:
8047 // If the brace-or-equal-initializer of a non-static data member
8048 // invokes a defaulted default constructor of its class or of an
8049 // enclosing class in a potentially evaluated subexpression, the
8050 // program is ill-formed.
8051 //
8052 // This resolution is unworkable: the exception specification of the
8053 // default constructor can be needed in an unevaluated context, in
8054 // particular, in the operand of a noexcept-expression, and we can be
8055 // unable to compute an exception specification for an enclosed class.
8056 //
8057 // We do not allow an in-class initializer to require the evaluation
8058 // of the exception specification for any in-class initializer whose
8059 // definition is not lexically complete.
8060 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00008061 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00008062 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00008063 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8064 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8065 // If this is a deleted function, add it anyway. This might be conformant
8066 // with the standard. This might not. I'm not sure. It might not matter.
8067 // In particular, the problem is that this function never gets called. It
8068 // might just be ill-formed because this function attempts to refer to
8069 // a deleted function here.
8070 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008071 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00008072 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008073 }
John McCalle23cf432010-12-14 08:05:40 +00008074
Sean Hunt001cad92011-05-10 00:49:42 +00008075 return ExceptSpec;
8076}
8077
Richard Smith07b0fdc2013-03-18 21:12:30 +00008078Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00008079Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8080 CXXRecordDecl *ClassDecl = CD->getParent();
8081
8082 // C++ [except.spec]p14:
8083 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00008084 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00008085 if (ClassDecl->isInvalidDecl())
8086 return ExceptSpec;
8087
8088 // Inherited constructor.
8089 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8090 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8091 // FIXME: Copying or moving the parameters could add extra exceptions to the
8092 // set, as could the default arguments for the inherited constructor. This
8093 // will be addressed when we implement the resolution of core issue 1351.
8094 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8095
8096 // Direct base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008097 for (const auto &B : ClassDecl->bases()) {
8098 if (B.isVirtual()) // Handled below.
Richard Smith0b0ca472013-04-10 06:11:48 +00008099 continue;
8100
Stephen Hines651f13c2014-04-23 16:59:28 -07008101 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smith0b0ca472013-04-10 06:11:48 +00008102 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8103 if (BaseClassDecl == InheritedDecl)
8104 continue;
8105 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8106 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -07008107 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smith0b0ca472013-04-10 06:11:48 +00008108 }
8109 }
8110
8111 // Virtual base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008112 for (const auto &B : ClassDecl->vbases()) {
8113 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smith0b0ca472013-04-10 06:11:48 +00008114 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8115 if (BaseClassDecl == InheritedDecl)
8116 continue;
8117 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8118 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -07008119 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smith0b0ca472013-04-10 06:11:48 +00008120 }
8121 }
8122
8123 // Field constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008124 for (const auto *F : ClassDecl->fields()) {
Richard Smith0b0ca472013-04-10 06:11:48 +00008125 if (F->hasInClassInitializer()) {
8126 if (Expr *E = F->getInClassInitializer())
8127 ExceptSpec.CalledExpr(E);
8128 else if (!F->isInvalidDecl())
8129 Diag(CD->getLocation(),
8130 diag::err_in_class_initializer_references_def_ctor) << CD;
8131 } else if (const RecordType *RecordTy
8132 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8133 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8134 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8135 if (Constructor)
8136 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8137 }
8138 }
8139
Richard Smith07b0fdc2013-03-18 21:12:30 +00008140 return ExceptSpec;
8141}
8142
Richard Smithafb49182012-11-29 01:34:07 +00008143namespace {
8144/// RAII object to register a special member as being currently declared.
8145struct DeclaringSpecialMember {
8146 Sema &S;
8147 Sema::SpecialMemberDecl D;
8148 bool WasAlreadyBeingDeclared;
8149
8150 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8151 : S(S), D(RD, CSM) {
8152 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8153 if (WasAlreadyBeingDeclared)
8154 // This almost never happens, but if it does, ensure that our cache
8155 // doesn't contain a stale result.
8156 S.SpecialMemberCache.clear();
8157
8158 // FIXME: Register a note to be produced if we encounter an error while
8159 // declaring the special member.
8160 }
8161 ~DeclaringSpecialMember() {
8162 if (!WasAlreadyBeingDeclared)
8163 S.SpecialMembersBeingDeclared.erase(D);
8164 }
8165
8166 /// \brief Are we already trying to declare this special member?
8167 bool isAlreadyBeingDeclared() const {
8168 return WasAlreadyBeingDeclared;
8169 }
8170};
8171}
8172
Sean Hunt001cad92011-05-10 00:49:42 +00008173CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8174 CXXRecordDecl *ClassDecl) {
8175 // C++ [class.ctor]p5:
8176 // A default constructor for a class X is a constructor of class X
8177 // that can be called without an argument. If there is no
8178 // user-declared constructor for class X, a default constructor is
8179 // implicitly declared. An implicitly-declared default constructor
8180 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00008181 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00008182 "Should not build implicit default constructor!");
8183
Richard Smithafb49182012-11-29 01:34:07 +00008184 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8185 if (DSM.isAlreadyBeingDeclared())
8186 return 0;
8187
Richard Smith7756afa2012-06-10 05:43:50 +00008188 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8189 CXXDefaultConstructor,
8190 false);
8191
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008192 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00008193 CanQualType ClassType
8194 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008195 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00008196 DeclarationName Name
8197 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008198 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00008199 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008200 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008201 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008202 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00008203 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00008204 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00008205 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008206
8207 // Build an exception specification pointing back at this constructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008208 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008209 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008210
Richard Smithbc2a35d2012-12-08 08:32:28 +00008211 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8212 // constructors is easy to compute.
8213 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8214
8215 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008216 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008217
Douglas Gregor18274032010-07-03 00:47:00 +00008218 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00008219 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00008220
Douglas Gregor23c94db2010-07-02 17:43:08 +00008221 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00008222 PushOnScopeChains(DefaultCon, S, false);
8223 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00008224
Douglas Gregor32df23e2010-07-01 22:02:46 +00008225 return DefaultCon;
8226}
8227
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008228void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8229 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00008230 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008231 !Constructor->doesThisDeclarationHaveABody() &&
8232 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00008233 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008234
Anders Carlssonf6513ed2010-04-23 16:04:08 +00008235 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00008236 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00008237
Eli Friedman9a14db32012-10-18 20:14:08 +00008238 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008239 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00008240 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008241 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008242 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00008243 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00008244 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008245 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00008246 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008247
8248 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008249 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008250
Eli Friedman86164e82013-09-05 00:02:25 +00008251 Constructor->markUsed(Context);
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008252 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008253
8254 if (ASTMutationListener *L = getASTMutationListener()) {
8255 L->CompletedImplicitDefinition(Constructor);
8256 }
Richard Trieu858d2ba2013-10-25 00:56:00 +00008257
8258 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008259}
8260
Richard Smith7a614d82011-06-11 17:19:42 +00008261void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Toker08235662013-10-18 05:54:19 +00008262 // Perform any delayed checks on exception specifications.
8263 CheckDelayedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00008264}
8265
Richard Smith4841ca52013-04-10 05:48:59 +00008266namespace {
8267/// Information on inheriting constructors to declare.
8268class InheritingConstructorInfo {
8269public:
8270 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8271 : SemaRef(SemaRef), Derived(Derived) {
8272 // Mark the constructors that we already have in the derived class.
8273 //
8274 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8275 // unless there is a user-declared constructor with the same signature in
8276 // the class where the using-declaration appears.
8277 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8278 }
8279
8280 void inheritAll(CXXRecordDecl *RD) {
8281 visitAll(RD, &InheritingConstructorInfo::inherit);
8282 }
8283
8284private:
8285 /// Information about an inheriting constructor.
8286 struct InheritingConstructor {
8287 InheritingConstructor()
8288 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8289
8290 /// If \c true, a constructor with this signature is already declared
8291 /// in the derived class.
8292 bool DeclaredInDerived;
8293
8294 /// The constructor which is inherited.
8295 const CXXConstructorDecl *BaseCtor;
8296
8297 /// The derived constructor we declared.
8298 CXXConstructorDecl *DerivedCtor;
8299 };
8300
8301 /// Inheriting constructors with a given canonical type. There can be at
8302 /// most one such non-template constructor, and any number of templated
8303 /// constructors.
8304 struct InheritingConstructorsForType {
8305 InheritingConstructor NonTemplate;
Robert Wilhelme7205c02013-08-10 12:33:24 +00008306 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8307 Templates;
Richard Smith4841ca52013-04-10 05:48:59 +00008308
8309 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8310 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8311 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8312 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8313 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8314 false, S.TPL_TemplateMatch))
8315 return Templates[I].second;
8316 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8317 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008318 }
Richard Smith4841ca52013-04-10 05:48:59 +00008319
8320 return NonTemplate;
8321 }
8322 };
8323
8324 /// Get or create the inheriting constructor record for a constructor.
8325 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8326 QualType CtorType) {
8327 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8328 .getEntry(SemaRef, Ctor);
8329 }
8330
8331 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8332
8333 /// Process all constructors for a class.
8334 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Stephen Hines651f13c2014-04-23 16:59:28 -07008335 for (const auto *Ctor : RD->ctors())
8336 (this->*Callback)(Ctor);
Richard Smith4841ca52013-04-10 05:48:59 +00008337 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8338 I(RD->decls_begin()), E(RD->decls_end());
8339 I != E; ++I) {
8340 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8341 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8342 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008343 }
8344 }
Richard Smith4841ca52013-04-10 05:48:59 +00008345
8346 /// Note that a constructor (or constructor template) was declared in Derived.
8347 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8348 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8349 }
8350
8351 /// Inherit a single constructor.
8352 void inherit(const CXXConstructorDecl *Ctor) {
8353 const FunctionProtoType *CtorType =
8354 Ctor->getType()->castAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07008355 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
Richard Smith4841ca52013-04-10 05:48:59 +00008356 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8357
8358 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8359
8360 // Core issue (no number yet): the ellipsis is always discarded.
8361 if (EPI.Variadic) {
8362 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8363 SemaRef.Diag(Ctor->getLocation(),
8364 diag::note_using_decl_constructor_ellipsis);
8365 EPI.Variadic = false;
8366 }
8367
8368 // Declare a constructor for each number of parameters.
8369 //
8370 // C++11 [class.inhctor]p1:
8371 // The candidate set of inherited constructors from the class X named in
8372 // the using-declaration consists of [... modulo defects ...] for each
8373 // constructor or constructor template of X, the set of constructors or
8374 // constructor templates that results from omitting any ellipsis parameter
8375 // specification and successively omitting parameters with a default
8376 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008377 unsigned MinParams = minParamsToInherit(Ctor);
8378 unsigned Params = Ctor->getNumParams();
8379 if (Params >= MinParams) {
8380 do
8381 declareCtor(UsingLoc, Ctor,
8382 SemaRef.Context.getFunctionType(
Stephen Hines651f13c2014-04-23 16:59:28 -07008383 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith987c0302013-04-17 19:00:52 +00008384 while (Params > MinParams &&
8385 Ctor->getParamDecl(--Params)->hasDefaultArg());
8386 }
Richard Smith4841ca52013-04-10 05:48:59 +00008387 }
8388
8389 /// Find the using-declaration which specified that we should inherit the
8390 /// constructors of \p Base.
8391 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8392 // No fancy lookup required; just look for the base constructor name
8393 // directly within the derived class.
8394 ASTContext &Context = SemaRef.Context;
8395 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8396 Context.getCanonicalType(Context.getRecordType(Base)));
8397 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8398 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8399 }
8400
8401 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8402 // C++11 [class.inhctor]p3:
8403 // [F]or each constructor template in the candidate set of inherited
8404 // constructors, a constructor template is implicitly declared
8405 if (Ctor->getDescribedFunctionTemplate())
8406 return 0;
8407
8408 // For each non-template constructor in the candidate set of inherited
8409 // constructors other than a constructor having no parameters or a
8410 // copy/move constructor having a single parameter, a constructor is
8411 // implicitly declared [...]
8412 if (Ctor->getNumParams() == 0)
8413 return 1;
8414 if (Ctor->isCopyOrMoveConstructor())
8415 return 2;
8416
8417 // Per discussion on core reflector, never inherit a constructor which
8418 // would become a default, copy, or move constructor of Derived either.
8419 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8420 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8421 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8422 }
8423
8424 /// Declare a single inheriting constructor, inheriting the specified
8425 /// constructor, with the given type.
8426 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8427 QualType DerivedType) {
8428 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8429
8430 // C++11 [class.inhctor]p3:
8431 // ... a constructor is implicitly declared with the same constructor
8432 // characteristics unless there is a user-declared constructor with
8433 // the same signature in the class where the using-declaration appears
8434 if (Entry.DeclaredInDerived)
8435 return;
8436
8437 // C++11 [class.inhctor]p7:
8438 // If two using-declarations declare inheriting constructors with the
8439 // same signature, the program is ill-formed
8440 if (Entry.DerivedCtor) {
8441 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8442 // Only diagnose this once per constructor.
8443 if (Entry.DerivedCtor->isInvalidDecl())
8444 return;
8445 Entry.DerivedCtor->setInvalidDecl();
8446
8447 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8448 SemaRef.Diag(BaseCtor->getLocation(),
8449 diag::note_using_decl_constructor_conflict_current_ctor);
8450 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8451 diag::note_using_decl_constructor_conflict_previous_ctor);
8452 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8453 diag::note_using_decl_constructor_conflict_previous_using);
8454 } else {
8455 // Core issue (no number): if the same inheriting constructor is
8456 // produced by multiple base class constructors from the same base
8457 // class, the inheriting constructor is defined as deleted.
8458 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8459 }
8460
8461 return;
8462 }
8463
8464 ASTContext &Context = SemaRef.Context;
8465 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8466 Context.getCanonicalType(Context.getRecordType(Derived)));
8467 DeclarationNameInfo NameInfo(Name, UsingLoc);
8468
8469 TemplateParameterList *TemplateParams = 0;
8470 if (const FunctionTemplateDecl *FTD =
8471 BaseCtor->getDescribedFunctionTemplate()) {
8472 TemplateParams = FTD->getTemplateParameters();
8473 // We're reusing template parameters from a different DeclContext. This
8474 // is questionable at best, but works out because the template depth in
8475 // both places is guaranteed to be 0.
8476 // FIXME: Rebuild the template parameters in the new context, and
8477 // transform the function type to refer to them.
8478 }
8479
8480 // Build type source info pointing at the using-declaration. This is
8481 // required by template instantiation.
8482 TypeSourceInfo *TInfo =
8483 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8484 FunctionProtoTypeLoc ProtoLoc =
8485 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8486
8487 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8488 Context, Derived, UsingLoc, NameInfo, DerivedType,
8489 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8490 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8491
8492 // Build an unevaluated exception specification for this constructor.
8493 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8494 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8495 EPI.ExceptionSpecType = EST_Unevaluated;
8496 EPI.ExceptionSpecDecl = DerivedCtor;
Stephen Hines651f13c2014-04-23 16:59:28 -07008497 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
8498 FPT->getParamTypes(), EPI));
Richard Smith4841ca52013-04-10 05:48:59 +00008499
8500 // Build the parameter declarations.
8501 SmallVector<ParmVarDecl *, 16> ParamDecls;
Stephen Hines651f13c2014-04-23 16:59:28 -07008502 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith4841ca52013-04-10 05:48:59 +00008503 TypeSourceInfo *TInfo =
Stephen Hines651f13c2014-04-23 16:59:28 -07008504 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith4841ca52013-04-10 05:48:59 +00008505 ParmVarDecl *PD = ParmVarDecl::Create(
8506 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
Stephen Hines651f13c2014-04-23 16:59:28 -07008507 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/0);
Richard Smith4841ca52013-04-10 05:48:59 +00008508 PD->setScopeInfo(0, I);
8509 PD->setImplicit();
8510 ParamDecls.push_back(PD);
Stephen Hines651f13c2014-04-23 16:59:28 -07008511 ProtoLoc.setParam(I, PD);
Richard Smith4841ca52013-04-10 05:48:59 +00008512 }
8513
8514 // Set up the new constructor.
8515 DerivedCtor->setAccess(BaseCtor->getAccess());
8516 DerivedCtor->setParams(ParamDecls);
8517 DerivedCtor->setInheritedConstructor(BaseCtor);
8518 if (BaseCtor->isDeleted())
8519 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8520
8521 // If this is a constructor template, build the template declaration.
8522 if (TemplateParams) {
8523 FunctionTemplateDecl *DerivedTemplate =
8524 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8525 TemplateParams, DerivedCtor);
8526 DerivedTemplate->setAccess(BaseCtor->getAccess());
8527 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8528 Derived->addDecl(DerivedTemplate);
8529 } else {
8530 Derived->addDecl(DerivedCtor);
8531 }
8532
8533 Entry.BaseCtor = BaseCtor;
8534 Entry.DerivedCtor = DerivedCtor;
8535 }
8536
8537 Sema &SemaRef;
8538 CXXRecordDecl *Derived;
8539 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8540 MapType Map;
8541};
8542}
8543
8544void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8545 // Defer declaring the inheriting constructors until the class is
8546 // instantiated.
8547 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008548 return;
8549
Richard Smith4841ca52013-04-10 05:48:59 +00008550 // Find base classes from which we might inherit constructors.
8551 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Stephen Hines651f13c2014-04-23 16:59:28 -07008552 for (const auto &BaseIt : ClassDecl->bases())
8553 if (BaseIt.getInheritConstructors())
8554 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008555
Richard Smith4841ca52013-04-10 05:48:59 +00008556 // Go no further if we're not inheriting any constructors.
8557 if (InheritedBases.empty())
8558 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008559
Richard Smith4841ca52013-04-10 05:48:59 +00008560 // Declare the inherited constructors.
8561 InheritingConstructorInfo ICI(*this, ClassDecl);
8562 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8563 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008564}
8565
Richard Smith07b0fdc2013-03-18 21:12:30 +00008566void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8567 CXXConstructorDecl *Constructor) {
8568 CXXRecordDecl *ClassDecl = Constructor->getParent();
8569 assert(Constructor->getInheritedConstructor() &&
8570 !Constructor->doesThisDeclarationHaveABody() &&
8571 !Constructor->isDeleted());
8572
8573 SynthesizedFunctionScope Scope(*this, Constructor);
8574 DiagnosticErrorTrap Trap(Diags);
8575 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8576 Trap.hasErrorOccurred()) {
8577 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8578 << Context.getTagDeclType(ClassDecl);
8579 Constructor->setInvalidDecl();
8580 return;
8581 }
8582
8583 SourceLocation Loc = Constructor->getLocation();
8584 Constructor->setBody(new (Context) CompoundStmt(Loc));
8585
Eli Friedman86164e82013-09-05 00:02:25 +00008586 Constructor->markUsed(Context);
Richard Smith07b0fdc2013-03-18 21:12:30 +00008587 MarkVTableUsed(CurrentLocation, ClassDecl);
8588
8589 if (ASTMutationListener *L = getASTMutationListener()) {
8590 L->CompletedImplicitDefinition(Constructor);
8591 }
8592}
8593
8594
Sean Huntcb45a0f2011-05-12 22:46:25 +00008595Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008596Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8597 CXXRecordDecl *ClassDecl = MD->getParent();
8598
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008599 // C++ [except.spec]p14:
8600 // An implicitly declared special member function (Clause 12) shall have
8601 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008602 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008603 if (ClassDecl->isInvalidDecl())
8604 return ExceptSpec;
8605
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008606 // Direct base-class destructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008607 for (const auto &B : ClassDecl->bases()) {
8608 if (B.isVirtual()) // Handled below.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008609 continue;
8610
Stephen Hines651f13c2014-04-23 16:59:28 -07008611 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8612 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008613 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008614 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008615
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008616 // Virtual base-class destructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008617 for (const auto &B : ClassDecl->vbases()) {
8618 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8619 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008620 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008621 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008622
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008623 // Field destructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008624 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008625 if (const RecordType *RecordTy
8626 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008627 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008628 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008629 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008630
Sean Huntcb45a0f2011-05-12 22:46:25 +00008631 return ExceptSpec;
8632}
8633
8634CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8635 // C++ [class.dtor]p2:
8636 // If a class has no user-declared destructor, a destructor is
8637 // declared implicitly. An implicitly-declared destructor is an
8638 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008639 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008640
Richard Smithafb49182012-11-29 01:34:07 +00008641 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8642 if (DSM.isAlreadyBeingDeclared())
8643 return 0;
8644
Douglas Gregor4923aa22010-07-02 20:37:36 +00008645 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008646 CanQualType ClassType
8647 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008648 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008649 DeclarationName Name
8650 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008651 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008652 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008653 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8654 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008655 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008656 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008657 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008658 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008659
8660 // Build an exception specification pointing back at this destructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008661 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008662 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008663
Richard Smithbc2a35d2012-12-08 08:32:28 +00008664 AddOverriddenMethods(ClassDecl, Destructor);
8665
8666 // We don't need to use SpecialMemberIsTrivial here; triviality for
8667 // destructors is easy to compute.
8668 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8669
8670 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008671 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008672
Douglas Gregor4923aa22010-07-02 20:37:36 +00008673 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008674 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008675
Douglas Gregor4923aa22010-07-02 20:37:36 +00008676 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008677 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008678 PushOnScopeChains(Destructor, S, false);
8679 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008680
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008681 return Destructor;
8682}
8683
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008684void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008685 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008686 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008687 !Destructor->doesThisDeclarationHaveABody() &&
8688 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008689 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008690 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008691 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008692
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008693 if (Destructor->isInvalidDecl())
8694 return;
8695
Eli Friedman9a14db32012-10-18 20:14:08 +00008696 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008697
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008698 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008699 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8700 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008701
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008702 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008703 Diag(CurrentLocation, diag::note_member_synthesized_at)
8704 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8705
8706 Destructor->setInvalidDecl();
8707 return;
8708 }
8709
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008710 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008711 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman86164e82013-09-05 00:02:25 +00008712 Destructor->markUsed(Context);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008713 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008714
8715 if (ASTMutationListener *L = getASTMutationListener()) {
8716 L->CompletedImplicitDefinition(Destructor);
8717 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008718}
8719
Richard Smitha4156b82012-04-21 18:42:51 +00008720/// \brief Perform any semantic analysis which needs to be delayed until all
8721/// pending class member declarations have been parsed.
8722void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008723 // If the context is an invalid C++ class, just suppress these checks.
8724 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8725 if (Record->isInvalidDecl()) {
Alp Toker08235662013-10-18 05:54:19 +00008726 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregor10318842013-02-01 04:49:10 +00008727 DelayedDestructorExceptionSpecChecks.clear();
8728 return;
8729 }
8730 }
Richard Smitha4156b82012-04-21 18:42:51 +00008731}
8732
Richard Smithb9d0b762012-07-27 04:22:15 +00008733void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8734 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008735 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008736 "adjusting dtor exception specs was introduced in c++11");
8737
Sebastian Redl0ee33912011-05-19 05:13:44 +00008738 // C++11 [class.dtor]p3:
8739 // A declaration of a destructor that does not have an exception-
8740 // specification is implicitly considered to have the same exception-
8741 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008742 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008743 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008744 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008745 return;
8746
Chandler Carruth3f224b22011-09-20 04:55:26 +00008747 // Replace the destructor's type, building off the existing one. Fortunately,
8748 // the only thing of interest in the destructor type is its extended info.
8749 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008750 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8751 EPI.ExceptionSpecType = EST_Unevaluated;
8752 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008753 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008754
Sebastian Redl0ee33912011-05-19 05:13:44 +00008755 // FIXME: If the destructor has a body that could throw, and the newly created
8756 // spec doesn't allow exceptions, we should emit a warning, because this
8757 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008758 // However, we don't have a body or an exception specification yet, so it
8759 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008760}
8761
Pavel Labath66ea35d2013-08-30 08:52:28 +00008762namespace {
8763/// \brief An abstract base class for all helper classes used in building the
8764// copy/move operators. These classes serve as factory functions and help us
8765// avoid using the same Expr* in the AST twice.
8766class ExprBuilder {
8767 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8768 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8769
8770protected:
8771 static Expr *assertNotNull(Expr *E) {
8772 assert(E && "Expression construction must not fail.");
8773 return E;
8774 }
8775
8776public:
8777 ExprBuilder() {}
8778 virtual ~ExprBuilder() {}
8779
8780 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8781};
8782
8783class RefBuilder: public ExprBuilder {
8784 VarDecl *Var;
8785 QualType VarType;
8786
8787public:
Stephen Hines651f13c2014-04-23 16:59:28 -07008788 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008789 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8790 }
8791
8792 RefBuilder(VarDecl *Var, QualType VarType)
8793 : Var(Var), VarType(VarType) {}
8794};
8795
8796class ThisBuilder: public ExprBuilder {
8797public:
Stephen Hines651f13c2014-04-23 16:59:28 -07008798 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008799 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8800 }
8801};
8802
8803class CastBuilder: public ExprBuilder {
8804 const ExprBuilder &Builder;
8805 QualType Type;
8806 ExprValueKind Kind;
8807 const CXXCastPath &Path;
8808
8809public:
Stephen Hines651f13c2014-04-23 16:59:28 -07008810 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008811 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8812 CK_UncheckedDerivedToBase, Kind,
8813 &Path).take());
8814 }
8815
8816 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8817 const CXXCastPath &Path)
8818 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8819};
8820
8821class DerefBuilder: public ExprBuilder {
8822 const ExprBuilder &Builder;
8823
8824public:
Stephen Hines651f13c2014-04-23 16:59:28 -07008825 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008826 return assertNotNull(
8827 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8828 }
8829
8830 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8831};
8832
8833class MemberBuilder: public ExprBuilder {
8834 const ExprBuilder &Builder;
8835 QualType Type;
8836 CXXScopeSpec SS;
8837 bool IsArrow;
8838 LookupResult &MemberLookup;
8839
8840public:
Stephen Hines651f13c2014-04-23 16:59:28 -07008841 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008842 return assertNotNull(S.BuildMemberReferenceExpr(
8843 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8844 MemberLookup, 0).take());
8845 }
8846
8847 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8848 LookupResult &MemberLookup)
8849 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8850 MemberLookup(MemberLookup) {}
8851};
8852
8853class MoveCastBuilder: public ExprBuilder {
8854 const ExprBuilder &Builder;
8855
8856public:
Stephen Hines651f13c2014-04-23 16:59:28 -07008857 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008858 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8859 }
8860
8861 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8862};
8863
8864class LvalueConvBuilder: public ExprBuilder {
8865 const ExprBuilder &Builder;
8866
8867public:
Stephen Hines651f13c2014-04-23 16:59:28 -07008868 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008869 return assertNotNull(
8870 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8871 }
8872
8873 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8874};
8875
8876class SubscriptBuilder: public ExprBuilder {
8877 const ExprBuilder &Base;
8878 const ExprBuilder &Index;
8879
8880public:
Stephen Hines651f13c2014-04-23 16:59:28 -07008881 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008882 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8883 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8884 }
8885
8886 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8887 : Base(Base), Index(Index) {}
8888};
8889
8890} // end anonymous namespace
8891
Richard Smith8c889532012-11-14 00:50:40 +00008892/// When generating a defaulted copy or move assignment operator, if a field
8893/// should be copied with __builtin_memcpy rather than via explicit assignments,
8894/// do so. This optimization only applies for arrays of scalars, and for arrays
8895/// of class type where the selected copy/move-assignment operator is trivial.
8896static StmtResult
8897buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008898 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith8c889532012-11-14 00:50:40 +00008899 // Compute the size of the memory buffer to be copied.
8900 QualType SizeType = S.Context.getSizeType();
8901 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8902 S.Context.getTypeSizeInChars(T).getQuantity());
8903
8904 // Take the address of the field references for "from" and "to". We
8905 // directly construct UnaryOperators here because semantic analysis
8906 // does not permit us to take the address of an xvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00008907 Expr *From = FromB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008908 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8909 S.Context.getPointerType(From->getType()),
8910 VK_RValue, OK_Ordinary, Loc);
Pavel Labath66ea35d2013-08-30 08:52:28 +00008911 Expr *To = ToB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008912 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8913 S.Context.getPointerType(To->getType()),
8914 VK_RValue, OK_Ordinary, Loc);
8915
8916 const Type *E = T->getBaseElementTypeUnsafe();
8917 bool NeedsCollectableMemCpy =
8918 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8919
8920 // Create a reference to the __builtin_objc_memmove_collectable function
8921 StringRef MemCpyName = NeedsCollectableMemCpy ?
8922 "__builtin_objc_memmove_collectable" :
8923 "__builtin_memcpy";
8924 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8925 Sema::LookupOrdinaryName);
8926 S.LookupName(R, S.TUScope, true);
8927
8928 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8929 if (!MemCpy)
8930 // Something went horribly wrong earlier, and we will have complained
8931 // about it.
8932 return StmtError();
8933
8934 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8935 VK_RValue, Loc, 0);
8936 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8937
8938 Expr *CallArgs[] = {
8939 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8940 };
8941 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8942 Loc, CallArgs, Loc);
8943
8944 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8945 return S.Owned(Call.takeAs<Stmt>());
8946}
8947
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008948/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008949/// \c To.
8950///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008951/// This routine is used to copy/move the members of a class with an
8952/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008953/// copied are arrays, this routine builds for loops to copy them.
8954///
8955/// \param S The Sema object used for type-checking.
8956///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008957/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008958///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008959/// \param T The type of the expressions being copied/moved. Both expressions
8960/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008961///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008962/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008963///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008964/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008965///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008966/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008967/// Otherwise, it's a non-static member subobject.
8968///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008969/// \param Copying Whether we're copying or moving.
8970///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008971/// \param Depth Internal parameter recording the depth of the recursion.
8972///
Richard Smith8c889532012-11-14 00:50:40 +00008973/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8974/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008975static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008976buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008977 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00008978 bool CopyingBaseSubobject, bool Copying,
8979 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008980 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008981 // Each subobject is assigned in the manner appropriate to its type:
8982 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008983 // - if the subobject is of class type, as if by a call to operator= with
8984 // the subobject as the object expression and the corresponding
8985 // subobject of x as a single function argument (as if by explicit
8986 // qualification; that is, ignoring any possible virtual overriding
8987 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008988 //
8989 // C++03 [class.copy]p13:
8990 // - if the subobject is of class type, the copy assignment operator for
8991 // the class is used (as if by explicit qualification; that is,
8992 // ignoring any possible virtual overriding functions in more derived
8993 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008994 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8995 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008996
Douglas Gregor06a9f362010-05-01 20:49:11 +00008997 // Look for operator=.
8998 DeclarationName Name
8999 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9000 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9001 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009002
Richard Smith044c8aa2012-11-13 00:54:12 +00009003 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9004 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00009005 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00009006 LookupResult::Filter F = OpLookup.makeFilter();
9007 while (F.hasNext()) {
9008 NamedDecl *D = F.next();
9009 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9010 if (Method->isCopyAssignmentOperator() ||
9011 (!Copying && Method->isMoveAssignmentOperator()))
9012 continue;
9013
9014 F.erase();
9015 }
9016 F.done();
John McCallb0207482010-03-16 06:11:48 +00009017 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009018
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009019 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00009020 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009021 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00009022 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009023 // ambiguities), we need to cast "this" to that subobject type; to
9024 // ensure that we don't go through the virtual call mechanism, we need
9025 // to qualify the operator= name with the base class (see below). However,
9026 // this means that if the base class has a protected copy assignment
9027 // operator, the protected member access check will fail. So, we
9028 // rewrite "protected" access to "public" access in this case, since we
9029 // know by construction that we're calling from a derived class.
9030 if (CopyingBaseSubobject) {
9031 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9032 L != LEnd; ++L) {
9033 if (L.getAccess() == AS_protected)
9034 L.setAccess(AS_public);
9035 }
9036 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009037
Douglas Gregor06a9f362010-05-01 20:49:11 +00009038 // Create the nested-name-specifier that will be used to qualify the
9039 // reference to operator=; this is required to suppress the virtual
9040 // call mechanism.
9041 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00009042 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00009043 SS.MakeTrivial(S.Context,
9044 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00009045 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00009046 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00009047
Douglas Gregor06a9f362010-05-01 20:49:11 +00009048 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00009049 ExprResult OpEqualRef
Pavel Labath66ea35d2013-08-30 08:52:28 +00009050 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9051 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009052 /*FirstQualifierInScope=*/0,
9053 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009054 /*TemplateArgs=*/0,
9055 /*SuppressQualifierCheck=*/true);
9056 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009057 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00009058
Douglas Gregor06a9f362010-05-01 20:49:11 +00009059 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00009060
Pavel Labath66ea35d2013-08-30 08:52:28 +00009061 Expr *FromInst = From.build(S, Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00009062 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00009063 OpEqualRef.takeAs<Expr>(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00009064 Loc, FromInst, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009065 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009066 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00009067
Richard Smith8c889532012-11-14 00:50:40 +00009068 // If we built a call to a trivial 'operator=' while copying an array,
9069 // bail out. We'll replace the whole shebang with a memcpy.
9070 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9071 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9072 return StmtResult((Stmt*)0);
9073
Richard Smith044c8aa2012-11-13 00:54:12 +00009074 // Convert to an expression-statement, and clean up any produced
9075 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00009076 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009077 }
John McCallb0207482010-03-16 06:11:48 +00009078
Richard Smith044c8aa2012-11-13 00:54:12 +00009079 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00009080 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00009081 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009082 if (!ArrayTy) {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009083 ExprResult Assignment = S.CreateBuiltinBinOp(
9084 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009085 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009086 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00009087 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009088 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009089
9090 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00009091 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00009092
Douglas Gregor06a9f362010-05-01 20:49:11 +00009093 // Construct a loop over the array bounds, e.g.,
9094 //
9095 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9096 //
9097 // that will copy each of the array elements.
9098 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00009099
Douglas Gregor06a9f362010-05-01 20:49:11 +00009100 // Create the iteration variable.
9101 IdentifierInfo *IterationVarName = 0;
9102 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009103 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009104 llvm::raw_svector_ostream OS(Str);
9105 OS << "__i" << Depth;
9106 IterationVarName = &S.Context.Idents.get(OS.str());
9107 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009108 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009109 IterationVarName, SizeType,
9110 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009111 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00009112
Douglas Gregor06a9f362010-05-01 20:49:11 +00009113 // Initialize the iteration variable to zero.
9114 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009115 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009116
Pavel Labath66ea35d2013-08-30 08:52:28 +00009117 // Creates a reference to the iteration variable.
9118 RefBuilder IterationVarRef(IterationVar, SizeType);
9119 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman8c382062012-01-23 02:35:22 +00009120
Douglas Gregor06a9f362010-05-01 20:49:11 +00009121 // Create the DeclStmt that holds the iteration variable.
9122 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009123
Douglas Gregor06a9f362010-05-01 20:49:11 +00009124 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009125 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9126 MoveCastBuilder FromIndexMove(FromIndexCopy);
9127 const ExprBuilder *FromIndex;
9128 if (Copying)
9129 FromIndex = &FromIndexCopy;
9130 else
9131 FromIndex = &FromIndexMove;
9132
9133 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009134
9135 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00009136 StmtResult Copy =
9137 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00009138 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith8c889532012-11-14 00:50:40 +00009139 Copying, Depth + 1);
9140 // Bail out if copying fails or if we determined that we should use memcpy.
9141 if (Copy.isInvalid() || !Copy.get())
9142 return Copy;
9143
9144 // Create the comparison against the array bound.
9145 llvm::APInt Upper
9146 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9147 Expr *Comparison
Pavel Labath66ea35d2013-08-30 08:52:28 +00009148 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith8c889532012-11-14 00:50:40 +00009149 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9150 BO_NE, S.Context.BoolTy,
9151 VK_RValue, OK_Ordinary, Loc, false);
9152
9153 // Create the pre-increment of the iteration variable.
9154 Expr *Increment
Pavel Labath66ea35d2013-08-30 08:52:28 +00009155 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9156 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009157
Douglas Gregor06a9f362010-05-01 20:49:11 +00009158 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00009159 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009160 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00009161 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00009162 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009163}
9164
Richard Smith8c889532012-11-14 00:50:40 +00009165static StmtResult
9166buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009167 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00009168 bool CopyingBaseSubobject, bool Copying) {
9169 // Maybe we should use a memcpy?
9170 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9171 T.isTriviallyCopyableType(S.Context))
9172 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9173
9174 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9175 CopyingBaseSubobject,
9176 Copying, 0));
9177
9178 // If we ended up picking a trivial assignment operator for an array of a
9179 // non-trivially-copyable class type, just emit a memcpy.
9180 if (!Result.isInvalid() && !Result.get())
9181 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9182
9183 return Result;
9184}
9185
Richard Smithb9d0b762012-07-27 04:22:15 +00009186Sema::ImplicitExceptionSpecification
9187Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9188 CXXRecordDecl *ClassDecl = MD->getParent();
9189
9190 ImplicitExceptionSpecification ExceptSpec(*this);
9191 if (ClassDecl->isInvalidDecl())
9192 return ExceptSpec;
9193
9194 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07009195 assert(T->getNumParams() == 1 && "not a copy assignment op");
9196 unsigned ArgQuals =
9197 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithb9d0b762012-07-27 04:22:15 +00009198
Douglas Gregorb87786f2010-07-01 17:48:08 +00009199 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00009200 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00009201 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00009202
9203 // It is unspecified whether or not an implicit copy assignment operator
9204 // attempts to deduplicate calls to assignment operators of virtual bases are
9205 // made. As such, this exception specification is effectively unspecified.
9206 // Based on a similar decision made for constness in C++0x, we're erring on
9207 // the side of assuming such calls to be made regardless of whether they
9208 // actually happen.
Stephen Hines651f13c2014-04-23 16:59:28 -07009209 for (const auto &Base : ClassDecl->bases()) {
9210 if (Base.isVirtual())
Sean Hunt661c67a2011-06-21 23:42:56 +00009211 continue;
9212
Douglas Gregora376d102010-07-02 21:50:04 +00009213 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -07009214 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00009215 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9216 ArgQuals, false, 0))
Stephen Hines651f13c2014-04-23 16:59:28 -07009217 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00009218 }
Sean Hunt661c67a2011-06-21 23:42:56 +00009219
Stephen Hines651f13c2014-04-23 16:59:28 -07009220 for (const auto &Base : ClassDecl->vbases()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00009221 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -07009222 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00009223 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9224 ArgQuals, false, 0))
Stephen Hines651f13c2014-04-23 16:59:28 -07009225 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00009226 }
9227
Stephen Hines651f13c2014-04-23 16:59:28 -07009228 for (const auto *Field : ClassDecl->fields()) {
David Blaikie262bc182012-04-30 02:36:29 +00009229 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00009230 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9231 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009232 LookupCopyingAssignment(FieldClassDecl,
9233 ArgQuals | FieldType.getCVRQualifiers(),
9234 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009235 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00009236 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00009237 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009238
Richard Smithb9d0b762012-07-27 04:22:15 +00009239 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00009240}
9241
9242CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9243 // Note: The following rules are largely analoguous to the copy
9244 // constructor rules. Note that virtual bases are not taken into account
9245 // for determining the argument type of the operator. Note also that
9246 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00009247 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00009248
Richard Smithafb49182012-11-29 01:34:07 +00009249 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9250 if (DSM.isAlreadyBeingDeclared())
9251 return 0;
9252
Sean Hunt30de05c2011-05-14 05:23:20 +00009253 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9254 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00009255 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9256 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00009257 ArgType = ArgType.withConst();
9258 ArgType = Context.getLValueReferenceType(ArgType);
9259
Richard Smitha8942d72013-05-07 03:19:20 +00009260 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9261 CXXCopyAssignment,
9262 Const);
9263
Douglas Gregord3c35902010-07-01 16:36:15 +00009264 // An implicitly-declared copy assignment operator is an inline public
9265 // member of its class.
9266 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009267 SourceLocation ClassLoc = ClassDecl->getLocation();
9268 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009269 CXXMethodDecl *CopyAssignment =
9270 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9271 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9272 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00009273 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00009274 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00009275 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00009276
9277 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009278 FunctionProtoType::ExtProtoInfo EPI =
9279 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009280 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009281
Douglas Gregord3c35902010-07-01 16:36:15 +00009282 // Add the parameter to the operator.
9283 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009284 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00009285 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009286 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009287 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00009288
Richard Smithbc2a35d2012-12-08 08:32:28 +00009289 AddOverriddenMethods(ClassDecl, CopyAssignment);
9290
9291 CopyAssignment->setTrivial(
9292 ClassDecl->needsOverloadResolutionForCopyAssignment()
9293 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9294 : ClassDecl->hasTrivialCopyAssignment());
9295
Richard Smith6c4c36c2012-03-30 20:53:28 +00009296 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009297 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009298
Richard Smithbc2a35d2012-12-08 08:32:28 +00009299 // Note that we have added this copy-assignment operator.
9300 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9301
9302 if (Scope *S = getScopeForContext(ClassDecl))
9303 PushOnScopeChains(CopyAssignment, S, false);
9304 ClassDecl->addDecl(CopyAssignment);
9305
Douglas Gregord3c35902010-07-01 16:36:15 +00009306 return CopyAssignment;
9307}
9308
Richard Smith36155c12013-06-13 03:23:42 +00009309/// Diagnose an implicit copy operation for a class which is odr-used, but
9310/// which is deprecated because the class has a user-declared copy constructor,
9311/// copy assignment operator, or destructor.
9312static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9313 SourceLocation UseLoc) {
9314 assert(CopyOp->isImplicit());
9315
9316 CXXRecordDecl *RD = CopyOp->getParent();
9317 CXXMethodDecl *UserDeclaredOperation = 0;
9318
9319 // In Microsoft mode, assignment operations don't affect constructors and
9320 // vice versa.
9321 if (RD->hasUserDeclaredDestructor()) {
9322 UserDeclaredOperation = RD->getDestructor();
9323 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9324 RD->hasUserDeclaredCopyConstructor() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07009325 !S.getLangOpts().MSVCCompat) {
Richard Smith36155c12013-06-13 03:23:42 +00009326 // Find any user-declared copy constructor.
Stephen Hines651f13c2014-04-23 16:59:28 -07009327 for (auto *I : RD->ctors()) {
Richard Smith36155c12013-06-13 03:23:42 +00009328 if (I->isCopyConstructor()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07009329 UserDeclaredOperation = I;
Richard Smith36155c12013-06-13 03:23:42 +00009330 break;
9331 }
9332 }
9333 assert(UserDeclaredOperation);
9334 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9335 RD->hasUserDeclaredCopyAssignment() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07009336 !S.getLangOpts().MSVCCompat) {
Richard Smith36155c12013-06-13 03:23:42 +00009337 // Find any user-declared move assignment operator.
Stephen Hines651f13c2014-04-23 16:59:28 -07009338 for (auto *I : RD->methods()) {
Richard Smith36155c12013-06-13 03:23:42 +00009339 if (I->isCopyAssignmentOperator()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07009340 UserDeclaredOperation = I;
Richard Smith36155c12013-06-13 03:23:42 +00009341 break;
9342 }
9343 }
9344 assert(UserDeclaredOperation);
9345 }
9346
9347 if (UserDeclaredOperation) {
9348 S.Diag(UserDeclaredOperation->getLocation(),
9349 diag::warn_deprecated_copy_operation)
9350 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9351 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9352 S.Diag(UseLoc, diag::note_member_synthesized_at)
9353 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9354 : Sema::CXXCopyAssignment)
9355 << RD;
9356 }
9357}
9358
Douglas Gregor06a9f362010-05-01 20:49:11 +00009359void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9360 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00009361 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009362 CopyAssignOperator->isOverloadedOperator() &&
9363 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009364 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9365 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009366 "DefineImplicitCopyAssignment called for wrong function");
9367
9368 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9369
9370 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9371 CopyAssignOperator->setInvalidDecl();
9372 return;
9373 }
Richard Smith36155c12013-06-13 03:23:42 +00009374
9375 // C++11 [class.copy]p18:
9376 // The [definition of an implicitly declared copy assignment operator] is
9377 // deprecated if the class has a user-declared copy constructor or a
9378 // user-declared destructor.
9379 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9380 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9381
Eli Friedman86164e82013-09-05 00:02:25 +00009382 CopyAssignOperator->markUsed(Context);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009383
Eli Friedman9a14db32012-10-18 20:14:08 +00009384 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009385 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009386
9387 // C++0x [class.copy]p30:
9388 // The implicitly-defined or explicitly-defaulted copy assignment operator
9389 // for a non-union class X performs memberwise copy assignment of its
9390 // subobjects. The direct base classes of X are assigned first, in the
9391 // order of their declaration in the base-specifier-list, and then the
9392 // immediate non-static data members of X are assigned, in the order in
9393 // which they were declared in the class definition.
9394
9395 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009396 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009397
9398 // The parameter for the "other" object, which we are copying from.
9399 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9400 Qualifiers OtherQuals = Other->getType().getQualifiers();
9401 QualType OtherRefType = Other->getType();
9402 if (const LValueReferenceType *OtherRef
9403 = OtherRefType->getAs<LValueReferenceType>()) {
9404 OtherRefType = OtherRef->getPointeeType();
9405 OtherQuals = OtherRefType.getQualifiers();
9406 }
9407
9408 // Our location for everything implicitly-generated.
9409 SourceLocation Loc = CopyAssignOperator->getLocation();
9410
Pavel Labath66ea35d2013-08-30 08:52:28 +00009411 // Builds a DeclRefExpr for the "other" object.
9412 RefBuilder OtherRef(Other, OtherRefType);
9413
9414 // Builds the "this" pointer.
9415 ThisBuilder This;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009416
9417 // Assign base classes.
9418 bool Invalid = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07009419 for (auto &Base : ClassDecl->bases()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009420 // Form the assignment:
9421 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Stephen Hines651f13c2014-04-23 16:59:28 -07009422 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009423 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009424 Invalid = true;
9425 continue;
9426 }
9427
John McCallf871d0c2010-08-07 06:22:56 +00009428 CXXCastPath BasePath;
Stephen Hines651f13c2014-04-23 16:59:28 -07009429 BasePath.push_back(&Base);
John McCallf871d0c2010-08-07 06:22:56 +00009430
Douglas Gregor06a9f362010-05-01 20:49:11 +00009431 // Construct the "from" expression, which is an implicit cast to the
9432 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009433 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9434 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009435
9436 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009437 DerefBuilder DerefThis(This);
9438 CastBuilder To(DerefThis,
9439 Context.getCVRQualifiedType(
9440 BaseType, CopyAssignOperator->getTypeQualifiers()),
9441 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009442
9443 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00009444 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009445 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009446 /*CopyingBaseSubobject=*/true,
9447 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009448 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009449 Diag(CurrentLocation, diag::note_member_synthesized_at)
9450 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9451 CopyAssignOperator->setInvalidDecl();
9452 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009453 }
9454
9455 // Success! Record the copy.
9456 Statements.push_back(Copy.takeAs<Expr>());
9457 }
9458
Douglas Gregor06a9f362010-05-01 20:49:11 +00009459 // Assign non-static members.
Stephen Hines651f13c2014-04-23 16:59:28 -07009460 for (auto *Field : ClassDecl->fields()) {
Douglas Gregord61db332011-10-10 17:22:13 +00009461 if (Field->isUnnamedBitfield())
9462 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00009463
9464 if (Field->isInvalidDecl()) {
9465 Invalid = true;
9466 continue;
9467 }
9468
Douglas Gregor06a9f362010-05-01 20:49:11 +00009469 // Check for members of reference type; we can't copy those.
9470 if (Field->getType()->isReferenceType()) {
9471 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9472 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9473 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009474 Diag(CurrentLocation, diag::note_member_synthesized_at)
9475 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009476 Invalid = true;
9477 continue;
9478 }
9479
9480 // Check for members of const-qualified, non-class type.
9481 QualType BaseType = Context.getBaseElementType(Field->getType());
9482 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9483 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9484 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9485 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009486 Diag(CurrentLocation, diag::note_member_synthesized_at)
9487 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009488 Invalid = true;
9489 continue;
9490 }
John McCallb77115d2011-06-17 00:18:42 +00009491
9492 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009493 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9494 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009495
9496 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009497 if (FieldType->isIncompleteArrayType()) {
9498 assert(ClassDecl->hasFlexibleArrayMember() &&
9499 "Incomplete array type is not valid");
9500 continue;
9501 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009502
9503 // Build references to the field in the object we're copying from and to.
9504 CXXScopeSpec SS; // Intentionally empty
9505 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9506 LookupMemberName);
Stephen Hines651f13c2014-04-23 16:59:28 -07009507 MemberLookup.addDecl(Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009508 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009509
9510 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9511
9512 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009513
Douglas Gregor06a9f362010-05-01 20:49:11 +00009514 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009515 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009516 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009517 /*CopyingBaseSubobject=*/false,
9518 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009519 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009520 Diag(CurrentLocation, diag::note_member_synthesized_at)
9521 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9522 CopyAssignOperator->setInvalidDecl();
9523 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009524 }
9525
9526 // Success! Record the copy.
9527 Statements.push_back(Copy.takeAs<Stmt>());
9528 }
9529
9530 if (!Invalid) {
9531 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009532 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009533
John McCall60d7b3a2010-08-24 06:29:42 +00009534 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009535 if (Return.isInvalid())
9536 Invalid = true;
9537 else {
9538 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009539
9540 if (Trap.hasErrorOccurred()) {
9541 Diag(CurrentLocation, diag::note_member_synthesized_at)
9542 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9543 Invalid = true;
9544 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009545 }
9546 }
9547
9548 if (Invalid) {
9549 CopyAssignOperator->setInvalidDecl();
9550 return;
9551 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009552
9553 StmtResult Body;
9554 {
9555 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009556 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009557 /*isStmtExpr=*/false);
9558 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9559 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009560 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009561
9562 if (ASTMutationListener *L = getASTMutationListener()) {
9563 L->CompletedImplicitDefinition(CopyAssignOperator);
9564 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009565}
9566
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009567Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009568Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9569 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009570
Richard Smithb9d0b762012-07-27 04:22:15 +00009571 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009572 if (ClassDecl->isInvalidDecl())
9573 return ExceptSpec;
9574
9575 // C++0x [except.spec]p14:
9576 // An implicitly declared special member function (Clause 12) shall have an
9577 // exception-specification. [...]
9578
9579 // It is unspecified whether or not an implicit move assignment operator
9580 // attempts to deduplicate calls to assignment operators of virtual bases are
9581 // made. As such, this exception specification is effectively unspecified.
9582 // Based on a similar decision made for constness in C++0x, we're erring on
9583 // the side of assuming such calls to be made regardless of whether they
9584 // actually happen.
9585 // Note that a move constructor is not implicitly declared when there are
9586 // virtual bases, but it can still be user-declared and explicitly defaulted.
Stephen Hines651f13c2014-04-23 16:59:28 -07009587 for (const auto &Base : ClassDecl->bases()) {
9588 if (Base.isVirtual())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009589 continue;
9590
9591 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -07009592 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009593 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009594 0, false, 0))
Stephen Hines651f13c2014-04-23 16:59:28 -07009595 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009596 }
9597
Stephen Hines651f13c2014-04-23 16:59:28 -07009598 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009599 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -07009600 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009601 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009602 0, false, 0))
Stephen Hines651f13c2014-04-23 16:59:28 -07009603 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009604 }
9605
Stephen Hines651f13c2014-04-23 16:59:28 -07009606 for (const auto *Field : ClassDecl->fields()) {
David Blaikie262bc182012-04-30 02:36:29 +00009607 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009608 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009609 if (CXXMethodDecl *MoveAssign =
9610 LookupMovingAssignment(FieldClassDecl,
9611 FieldType.getCVRQualifiers(),
9612 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009613 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009614 }
9615 }
9616
9617 return ExceptSpec;
9618}
9619
9620CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009621 assert(ClassDecl->needsImplicitMoveAssignment());
9622
Richard Smithafb49182012-11-29 01:34:07 +00009623 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9624 if (DSM.isAlreadyBeingDeclared())
9625 return 0;
9626
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009627 // Note: The following rules are largely analoguous to the move
9628 // constructor rules.
9629
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009630 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9631 QualType RetType = Context.getLValueReferenceType(ArgType);
9632 ArgType = Context.getRValueReferenceType(ArgType);
9633
Richard Smitha8942d72013-05-07 03:19:20 +00009634 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9635 CXXMoveAssignment,
9636 false);
9637
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009638 // An implicitly-declared move assignment operator is an inline public
9639 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009640 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9641 SourceLocation ClassLoc = ClassDecl->getLocation();
9642 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009643 CXXMethodDecl *MoveAssignment =
9644 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9645 /*TInfo=*/0, /*StorageClass=*/SC_None,
9646 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009647 MoveAssignment->setAccess(AS_public);
9648 MoveAssignment->setDefaulted();
9649 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009650
Richard Smithb9d0b762012-07-27 04:22:15 +00009651 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009652 FunctionProtoType::ExtProtoInfo EPI =
9653 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009654 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009655
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009656 // Add the parameter to the operator.
9657 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9658 ClassLoc, ClassLoc, /*Id=*/0,
9659 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009660 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009661 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009662
Richard Smithbc2a35d2012-12-08 08:32:28 +00009663 AddOverriddenMethods(ClassDecl, MoveAssignment);
9664
9665 MoveAssignment->setTrivial(
9666 ClassDecl->needsOverloadResolutionForMoveAssignment()
9667 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9668 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009669
Richard Smith7d5088a2012-02-18 02:02:13 +00009670 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith743cbb92013-11-04 01:48:18 +00009671 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9672 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009673 }
9674
Richard Smithbc2a35d2012-12-08 08:32:28 +00009675 // Note that we have added this copy-assignment operator.
9676 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9677
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009678 if (Scope *S = getScopeForContext(ClassDecl))
9679 PushOnScopeChains(MoveAssignment, S, false);
9680 ClassDecl->addDecl(MoveAssignment);
9681
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009682 return MoveAssignment;
9683}
9684
Richard Smith33b1f632013-11-04 04:26:14 +00009685/// Check if we're implicitly defining a move assignment operator for a class
9686/// with virtual bases. Such a move assignment might move-assign the virtual
9687/// base multiple times.
9688static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9689 SourceLocation CurrentLocation) {
9690 assert(!Class->isDependentContext() && "should not define dependent move");
9691
9692 // Only a virtual base could get implicitly move-assigned multiple times.
9693 // Only a non-trivial move assignment can observe this. We only want to
9694 // diagnose if we implicitly define an assignment operator that assigns
9695 // two base classes, both of which move-assign the same virtual base.
9696 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9697 Class->getNumBases() < 2)
9698 return;
9699
9700 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9701 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9702 VBaseMap VBases;
9703
Stephen Hines651f13c2014-04-23 16:59:28 -07009704 for (auto &BI : Class->bases()) {
9705 Worklist.push_back(&BI);
Richard Smith33b1f632013-11-04 04:26:14 +00009706 while (!Worklist.empty()) {
9707 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9708 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9709
9710 // If the base has no non-trivial move assignment operators,
9711 // we don't care about moves from it.
9712 if (!Base->hasNonTrivialMoveAssignment())
9713 continue;
9714
9715 // If there's nothing virtual here, skip it.
9716 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9717 continue;
9718
9719 // If we're not actually going to call a move assignment for this base,
9720 // or the selected move assignment is trivial, skip it.
9721 Sema::SpecialMemberOverloadResult *SMOR =
9722 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9723 /*ConstArg*/false, /*VolatileArg*/false,
9724 /*RValueThis*/true, /*ConstThis*/false,
9725 /*VolatileThis*/false);
9726 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9727 !SMOR->getMethod()->isMoveAssignmentOperator())
9728 continue;
9729
9730 if (BaseSpec->isVirtual()) {
9731 // We're going to move-assign this virtual base, and its move
9732 // assignment operator is not trivial. If this can happen for
9733 // multiple distinct direct bases of Class, diagnose it. (If it
9734 // only happens in one base, we'll diagnose it when synthesizing
9735 // that base class's move assignment operator.)
9736 CXXBaseSpecifier *&Existing =
Stephen Hines651f13c2014-04-23 16:59:28 -07009737 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smith33b1f632013-11-04 04:26:14 +00009738 .first->second;
Stephen Hines651f13c2014-04-23 16:59:28 -07009739 if (Existing && Existing != &BI) {
Richard Smith33b1f632013-11-04 04:26:14 +00009740 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9741 << Class << Base;
9742 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9743 << (Base->getCanonicalDecl() ==
9744 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9745 << Base << Existing->getType() << Existing->getSourceRange();
Stephen Hines651f13c2014-04-23 16:59:28 -07009746 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smith33b1f632013-11-04 04:26:14 +00009747 << (Base->getCanonicalDecl() ==
Stephen Hines651f13c2014-04-23 16:59:28 -07009748 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9749 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smith33b1f632013-11-04 04:26:14 +00009750
9751 // Only diagnose each vbase once.
9752 Existing = 0;
9753 }
9754 } else {
9755 // Only walk over bases that have defaulted move assignment operators.
9756 // We assume that any user-provided move assignment operator handles
9757 // the multiple-moves-of-vbase case itself somehow.
9758 if (!SMOR->getMethod()->isDefaulted())
9759 continue;
9760
9761 // We're going to move the base classes of Base. Add them to the list.
Stephen Hines651f13c2014-04-23 16:59:28 -07009762 for (auto &BI : Base->bases())
9763 Worklist.push_back(&BI);
Richard Smith33b1f632013-11-04 04:26:14 +00009764 }
9765 }
9766 }
9767}
9768
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009769void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9770 CXXMethodDecl *MoveAssignOperator) {
9771 assert((MoveAssignOperator->isDefaulted() &&
9772 MoveAssignOperator->isOverloadedOperator() &&
9773 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009774 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9775 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009776 "DefineImplicitMoveAssignment called for wrong function");
9777
9778 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9779
9780 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9781 MoveAssignOperator->setInvalidDecl();
9782 return;
9783 }
9784
Eli Friedman86164e82013-09-05 00:02:25 +00009785 MoveAssignOperator->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009786
Eli Friedman9a14db32012-10-18 20:14:08 +00009787 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009788 DiagnosticErrorTrap Trap(Diags);
9789
9790 // C++0x [class.copy]p28:
9791 // The implicitly-defined or move assignment operator for a non-union class
9792 // X performs memberwise move assignment of its subobjects. The direct base
9793 // classes of X are assigned first, in the order of their declaration in the
9794 // base-specifier-list, and then the immediate non-static data members of X
9795 // are assigned, in the order in which they were declared in the class
9796 // definition.
9797
Richard Smith33b1f632013-11-04 04:26:14 +00009798 // Issue a warning if our implicit move assignment operator will move
9799 // from a virtual base more than once.
9800 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith743cbb92013-11-04 01:48:18 +00009801
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009802 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009803 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009804
9805 // The parameter for the "other" object, which we are move from.
9806 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9807 QualType OtherRefType = Other->getType()->
9808 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009809 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009810 "Bad argument type of defaulted move assignment");
9811
9812 // Our location for everything implicitly-generated.
9813 SourceLocation Loc = MoveAssignOperator->getLocation();
9814
Pavel Labath66ea35d2013-08-30 08:52:28 +00009815 // Builds a reference to the "other" object.
9816 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009817 // Cast to rvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009818 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009819
Pavel Labath66ea35d2013-08-30 08:52:28 +00009820 // Builds the "this" pointer.
9821 ThisBuilder This;
Richard Smith1c931be2012-04-02 18:40:40 +00009822
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009823 // Assign base classes.
9824 bool Invalid = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07009825 for (auto &Base : ClassDecl->bases()) {
Richard Smith33b1f632013-11-04 04:26:14 +00009826 // C++11 [class.copy]p28:
9827 // It is unspecified whether subobjects representing virtual base classes
9828 // are assigned more than once by the implicitly-defined copy assignment
9829 // operator.
9830 // FIXME: Do not assign to a vbase that will be assigned by some other base
9831 // class. For a move-assignment, this can result in the vbase being moved
9832 // multiple times.
9833
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009834 // Form the assignment:
9835 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Stephen Hines651f13c2014-04-23 16:59:28 -07009836 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009837 if (!BaseType->isRecordType()) {
9838 Invalid = true;
9839 continue;
9840 }
9841
9842 CXXCastPath BasePath;
Stephen Hines651f13c2014-04-23 16:59:28 -07009843 BasePath.push_back(&Base);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009844
9845 // Construct the "from" expression, which is an implicit cast to the
9846 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009847 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009848
9849 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009850 DerefBuilder DerefThis(This);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009851
9852 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009853 CastBuilder To(DerefThis,
9854 Context.getCVRQualifiedType(
9855 BaseType, MoveAssignOperator->getTypeQualifiers()),
9856 VK_LValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009857
9858 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009859 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009860 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009861 /*CopyingBaseSubobject=*/true,
9862 /*Copying=*/false);
9863 if (Move.isInvalid()) {
9864 Diag(CurrentLocation, diag::note_member_synthesized_at)
9865 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9866 MoveAssignOperator->setInvalidDecl();
9867 return;
9868 }
9869
9870 // Success! Record the move.
9871 Statements.push_back(Move.takeAs<Expr>());
9872 }
9873
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009874 // Assign non-static members.
Stephen Hines651f13c2014-04-23 16:59:28 -07009875 for (auto *Field : ClassDecl->fields()) {
Douglas Gregord61db332011-10-10 17:22:13 +00009876 if (Field->isUnnamedBitfield())
9877 continue;
9878
Eli Friedman8150da32013-06-07 01:48:56 +00009879 if (Field->isInvalidDecl()) {
9880 Invalid = true;
9881 continue;
9882 }
9883
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009884 // Check for members of reference type; we can't move those.
9885 if (Field->getType()->isReferenceType()) {
9886 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9887 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9888 Diag(Field->getLocation(), diag::note_declared_at);
9889 Diag(CurrentLocation, diag::note_member_synthesized_at)
9890 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9891 Invalid = true;
9892 continue;
9893 }
9894
9895 // Check for members of const-qualified, non-class type.
9896 QualType BaseType = Context.getBaseElementType(Field->getType());
9897 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9898 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9899 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9900 Diag(Field->getLocation(), diag::note_declared_at);
9901 Diag(CurrentLocation, diag::note_member_synthesized_at)
9902 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9903 Invalid = true;
9904 continue;
9905 }
9906
9907 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009908 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9909 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009910
9911 QualType FieldType = Field->getType().getNonReferenceType();
9912 if (FieldType->isIncompleteArrayType()) {
9913 assert(ClassDecl->hasFlexibleArrayMember() &&
9914 "Incomplete array type is not valid");
9915 continue;
9916 }
9917
9918 // Build references to the field in the object we're copying from and to.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009919 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9920 LookupMemberName);
Stephen Hines651f13c2014-04-23 16:59:28 -07009921 MemberLookup.addDecl(Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009922 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009923 MemberBuilder From(MoveOther, OtherRefType,
9924 /*IsArrow=*/false, MemberLookup);
9925 MemberBuilder To(This, getCurrentThisType(),
9926 /*IsArrow=*/true, MemberLookup);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009927
Pavel Labath66ea35d2013-08-30 08:52:28 +00009928 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009929 "Member reference with rvalue base must be rvalue except for reference "
9930 "members, which aren't allowed for move assignment.");
9931
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009932 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009933 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009934 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009935 /*CopyingBaseSubobject=*/false,
9936 /*Copying=*/false);
9937 if (Move.isInvalid()) {
9938 Diag(CurrentLocation, diag::note_member_synthesized_at)
9939 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9940 MoveAssignOperator->setInvalidDecl();
9941 return;
9942 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009943
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009944 // Success! Record the copy.
9945 Statements.push_back(Move.takeAs<Stmt>());
9946 }
9947
9948 if (!Invalid) {
9949 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009950 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009951
9952 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9953 if (Return.isInvalid())
9954 Invalid = true;
9955 else {
9956 Statements.push_back(Return.takeAs<Stmt>());
9957
9958 if (Trap.hasErrorOccurred()) {
9959 Diag(CurrentLocation, diag::note_member_synthesized_at)
9960 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9961 Invalid = true;
9962 }
9963 }
9964 }
9965
9966 if (Invalid) {
9967 MoveAssignOperator->setInvalidDecl();
9968 return;
9969 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009970
9971 StmtResult Body;
9972 {
9973 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009974 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009975 /*isStmtExpr=*/false);
9976 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9977 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009978 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9979
9980 if (ASTMutationListener *L = getASTMutationListener()) {
9981 L->CompletedImplicitDefinition(MoveAssignOperator);
9982 }
9983}
9984
Richard Smithb9d0b762012-07-27 04:22:15 +00009985Sema::ImplicitExceptionSpecification
9986Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9987 CXXRecordDecl *ClassDecl = MD->getParent();
9988
9989 ImplicitExceptionSpecification ExceptSpec(*this);
9990 if (ClassDecl->isInvalidDecl())
9991 return ExceptSpec;
9992
9993 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07009994 assert(T->getNumParams() >= 1 && "not a copy ctor");
9995 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithb9d0b762012-07-27 04:22:15 +00009996
Douglas Gregor0d405db2010-07-01 20:59:04 +00009997 // C++ [except.spec]p14:
9998 // An implicitly declared special member function (Clause 12) shall have an
9999 // exception-specification. [...]
Stephen Hines651f13c2014-04-23 16:59:28 -070010000 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor0d405db2010-07-01 20:59:04 +000010001 // Virtual bases are handled below.
Stephen Hines651f13c2014-04-23 16:59:28 -070010002 if (Base.isVirtual())
Douglas Gregor0d405db2010-07-01 20:59:04 +000010003 continue;
10004
Douglas Gregor22584312010-07-02 23:41:54 +000010005 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -070010006 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +000010007 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +000010008 LookupCopyingConstructor(BaseClassDecl, Quals))
Stephen Hines651f13c2014-04-23 16:59:28 -070010009 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010010 }
Stephen Hines651f13c2014-04-23 16:59:28 -070010011 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregor22584312010-07-02 23:41:54 +000010012 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -070010013 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +000010014 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +000010015 LookupCopyingConstructor(BaseClassDecl, Quals))
Stephen Hines651f13c2014-04-23 16:59:28 -070010016 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010017 }
Stephen Hines651f13c2014-04-23 16:59:28 -070010018 for (const auto *Field : ClassDecl->fields()) {
David Blaikie262bc182012-04-30 02:36:29 +000010019 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +000010020 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10021 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +000010022 LookupCopyingConstructor(FieldClassDecl,
10023 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +000010024 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010025 }
10026 }
Sebastian Redl60618fa2011-03-12 11:50:43 +000010027
Richard Smithb9d0b762012-07-27 04:22:15 +000010028 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +000010029}
10030
10031CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10032 CXXRecordDecl *ClassDecl) {
10033 // C++ [class.copy]p4:
10034 // If the class definition does not explicitly declare a copy
10035 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +000010036 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +000010037
Richard Smithafb49182012-11-29 01:34:07 +000010038 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10039 if (DSM.isAlreadyBeingDeclared())
10040 return 0;
10041
Sean Hunt49634cf2011-05-13 06:10:58 +000010042 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10043 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +000010044 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +000010045 if (Const)
10046 ArgType = ArgType.withConst();
10047 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +000010048
Richard Smith7756afa2012-06-10 05:43:50 +000010049 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10050 CXXCopyConstructor,
10051 Const);
10052
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010053 DeclarationName Name
10054 = Context.DeclarationNames.getCXXConstructorName(
10055 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010056 SourceLocation ClassLoc = ClassDecl->getLocation();
10057 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +000010058
10059 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010060 // member of its class.
10061 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +000010062 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +000010063 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010064 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010065 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +000010066 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010067
Richard Smithb9d0b762012-07-27 04:22:15 +000010068 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010069 FunctionProtoType::ExtProtoInfo EPI =
10070 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010071 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010072 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010073
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010074 // Add the parameter to the constructor.
10075 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010076 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010077 /*IdentifierInfo=*/0,
10078 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +000010079 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +000010080 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +000010081
Richard Smithbc2a35d2012-12-08 08:32:28 +000010082 CopyConstructor->setTrivial(
10083 ClassDecl->needsOverloadResolutionForCopyConstructor()
10084 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10085 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +000010086
Richard Smith6c4c36c2012-03-30 20:53:28 +000010087 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +000010088 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +000010089
Richard Smithbc2a35d2012-12-08 08:32:28 +000010090 // Note that we have declared this constructor.
10091 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10092
10093 if (Scope *S = getScopeForContext(ClassDecl))
10094 PushOnScopeChains(CopyConstructor, S, false);
10095 ClassDecl->addDecl(CopyConstructor);
10096
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010097 return CopyConstructor;
10098}
10099
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010100void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +000010101 CXXConstructorDecl *CopyConstructor) {
10102 assert((CopyConstructor->isDefaulted() &&
10103 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010104 !CopyConstructor->doesThisDeclarationHaveABody() &&
10105 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010106 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +000010107
Anders Carlsson63010a72010-04-23 16:24:12 +000010108 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010109 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010110
Richard Smith36155c12013-06-13 03:23:42 +000010111 // C++11 [class.copy]p7:
Benjamin Kramere5753592013-09-09 14:48:42 +000010112 // The [definition of an implicitly declared copy constructor] is
Richard Smith36155c12013-06-13 03:23:42 +000010113 // deprecated if the class has a user-declared copy assignment operator
10114 // or a user-declared destructor.
10115 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10116 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10117
Eli Friedman9a14db32012-10-18 20:14:08 +000010118 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +000010119 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010120
David Blaikie93c86172013-01-17 05:26:25 +000010121 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +000010122 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +000010123 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010124 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +000010125 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010126 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010127 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010128 CopyConstructor->setBody(ActOnCompoundStmt(
10129 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10130 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +000010131 }
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010132
Eli Friedman86164e82013-09-05 00:02:25 +000010133 CopyConstructor->markUsed(Context);
Sebastian Redl58a2cd82011-04-24 16:28:06 +000010134 if (ASTMutationListener *L = getASTMutationListener()) {
10135 L->CompletedImplicitDefinition(CopyConstructor);
10136 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010137}
10138
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010139Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +000010140Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10141 CXXRecordDecl *ClassDecl = MD->getParent();
10142
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010143 // C++ [except.spec]p14:
10144 // An implicitly declared special member function (Clause 12) shall have an
10145 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +000010146 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010147 if (ClassDecl->isInvalidDecl())
10148 return ExceptSpec;
10149
10150 // Direct base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -070010151 for (const auto &B : ClassDecl->bases()) {
10152 if (B.isVirtual()) // Handled below.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010153 continue;
10154
Stephen Hines651f13c2014-04-23 16:59:28 -070010155 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010156 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010157 CXXConstructorDecl *Constructor =
10158 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010159 // If this is a deleted function, add it anyway. This might be conformant
10160 // with the standard. This might not. I'm not sure. It might not matter.
10161 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -070010162 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010163 }
10164 }
10165
10166 // Virtual base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -070010167 for (const auto &B : ClassDecl->vbases()) {
10168 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010169 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010170 CXXConstructorDecl *Constructor =
10171 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010172 // If this is a deleted function, add it anyway. This might be conformant
10173 // with the standard. This might not. I'm not sure. It might not matter.
10174 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -070010175 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010176 }
10177 }
10178
10179 // Field constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -070010180 for (const auto *F : ClassDecl->fields()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +000010181 QualType FieldType = Context.getBaseElementType(F->getType());
10182 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10183 CXXConstructorDecl *Constructor =
10184 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010185 // If this is a deleted function, add it anyway. This might be conformant
10186 // with the standard. This might not. I'm not sure. It might not matter.
10187 // In particular, the problem is that this function never gets called. It
10188 // might just be ill-formed because this function attempts to refer to
10189 // a deleted function here.
10190 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010191 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010192 }
10193 }
10194
10195 return ExceptSpec;
10196}
10197
10198CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10199 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +000010200 assert(ClassDecl->needsImplicitMoveConstructor());
10201
Richard Smithafb49182012-11-29 01:34:07 +000010202 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10203 if (DSM.isAlreadyBeingDeclared())
10204 return 0;
10205
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010206 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10207 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010208
Richard Smith7756afa2012-06-10 05:43:50 +000010209 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10210 CXXMoveConstructor,
10211 false);
10212
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010213 DeclarationName Name
10214 = Context.DeclarationNames.getCXXConstructorName(
10215 Context.getCanonicalType(ClassType));
10216 SourceLocation ClassLoc = ClassDecl->getLocation();
10217 DeclarationNameInfo NameInfo(Name, ClassLoc);
10218
Richard Smitha8942d72013-05-07 03:19:20 +000010219 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010220 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010221 // member of its class.
10222 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +000010223 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +000010224 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010225 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010226 MoveConstructor->setAccess(AS_public);
10227 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010228
Richard Smithb9d0b762012-07-27 04:22:15 +000010229 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010230 FunctionProtoType::ExtProtoInfo EPI =
10231 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010232 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010233 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010234
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010235 // Add the parameter to the constructor.
10236 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10237 ClassLoc, ClassLoc,
10238 /*IdentifierInfo=*/0,
10239 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010240 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +000010241 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010242
Richard Smithbc2a35d2012-12-08 08:32:28 +000010243 MoveConstructor->setTrivial(
10244 ClassDecl->needsOverloadResolutionForMoveConstructor()
10245 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10246 : ClassDecl->hasTrivialMoveConstructor());
10247
Sean Hunt769bb2d2011-10-11 06:43:29 +000010248 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith743cbb92013-11-04 01:48:18 +000010249 ClassDecl->setImplicitMoveConstructorIsDeleted();
10250 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010251 }
10252
10253 // Note that we have declared this constructor.
10254 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10255
10256 if (Scope *S = getScopeForContext(ClassDecl))
10257 PushOnScopeChains(MoveConstructor, S, false);
10258 ClassDecl->addDecl(MoveConstructor);
10259
10260 return MoveConstructor;
10261}
10262
10263void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10264 CXXConstructorDecl *MoveConstructor) {
10265 assert((MoveConstructor->isDefaulted() &&
10266 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010267 !MoveConstructor->doesThisDeclarationHaveABody() &&
10268 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010269 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10270
10271 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10272 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10273
Eli Friedman9a14db32012-10-18 20:14:08 +000010274 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010275 DiagnosticErrorTrap Trap(Diags);
10276
David Blaikie93c86172013-01-17 05:26:25 +000010277 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010278 Trap.hasErrorOccurred()) {
10279 Diag(CurrentLocation, diag::note_member_synthesized_at)
10280 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10281 MoveConstructor->setInvalidDecl();
10282 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010283 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010284 MoveConstructor->setBody(ActOnCompoundStmt(
10285 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10286 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010287 }
10288
Eli Friedman86164e82013-09-05 00:02:25 +000010289 MoveConstructor->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010290
10291 if (ASTMutationListener *L = getASTMutationListener()) {
10292 L->CompletedImplicitDefinition(MoveConstructor);
10293 }
10294}
10295
Douglas Gregore4e68d42012-02-15 19:33:52 +000010296bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +000010297 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010298}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010299
10300void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Valid6992ab2013-09-29 08:45:24 +000010301 SourceLocation CurrentLocation,
10302 CXXConversionDecl *Conv) {
10303 CXXRecordDecl *Lambda = Conv->getParent();
10304 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10305 // If we are defining a specialization of a conversion to function-ptr
10306 // cache the deduced template arguments for this specialization
10307 // so that we can use them to retrieve the corresponding call-operator
10308 // and static-invoker.
10309 const TemplateArgumentList *DeducedTemplateArgs = 0;
10310
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010311
Faisal Valid6992ab2013-09-29 08:45:24 +000010312 // Retrieve the corresponding call-operator specialization.
10313 if (Lambda->isGenericLambda()) {
10314 assert(Conv->isFunctionTemplateSpecialization());
10315 FunctionTemplateDecl *CallOpTemplate =
10316 CallOp->getDescribedFunctionTemplate();
10317 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10318 void *InsertPos = 0;
10319 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10320 DeducedTemplateArgs->data(),
10321 DeducedTemplateArgs->size(),
10322 InsertPos);
10323 assert(CallOpSpec &&
10324 "Conversion operator must have a corresponding call operator");
10325 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10326 }
10327 // Mark the call operator referenced (and add to pending instantiations
10328 // if necessary).
10329 // For both the conversion and static-invoker template specializations
10330 // we construct their body's in this function, so no need to add them
10331 // to the PendingInstantiations.
10332 MarkFunctionReferenced(CurrentLocation, CallOp);
10333
Eli Friedman9a14db32012-10-18 20:14:08 +000010334 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010335 DiagnosticErrorTrap Trap(Diags);
Faisal Valid6992ab2013-09-29 08:45:24 +000010336
Stephen Hines651f13c2014-04-23 16:59:28 -070010337 // Retrieve the static invoker...
Faisal Valid6992ab2013-09-29 08:45:24 +000010338 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10339 // ... and get the corresponding specialization for a generic lambda.
10340 if (Lambda->isGenericLambda()) {
10341 assert(DeducedTemplateArgs &&
10342 "Must have deduced template arguments from Conversion Operator");
10343 FunctionTemplateDecl *InvokeTemplate =
10344 Invoker->getDescribedFunctionTemplate();
10345 void *InsertPos = 0;
10346 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10347 DeducedTemplateArgs->data(),
10348 DeducedTemplateArgs->size(),
10349 InsertPos);
10350 assert(InvokeSpec &&
10351 "Must have a corresponding static invoker specialization");
10352 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10353 }
10354 // Construct the body of the conversion function { return __invoke; }.
10355 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10356 VK_LValue, Conv->getLocation()).take();
10357 assert(FunctionRef && "Can't refer to __invoke function?");
10358 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10359 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10360 Conv->getLocation(),
10361 Conv->getLocation()));
10362
10363 Conv->markUsed(Context);
10364 Conv->setReferenced();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010365
Faisal Valid6992ab2013-09-29 08:45:24 +000010366 // Fill in the __invoke function with a dummy implementation. IR generation
10367 // will fill in the actual details.
10368 Invoker->markUsed(Context);
10369 Invoker->setReferenced();
10370 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10371
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010372 if (ASTMutationListener *L = getASTMutationListener()) {
10373 L->CompletedImplicitDefinition(Conv);
Faisal Valid6992ab2013-09-29 08:45:24 +000010374 L->CompletedImplicitDefinition(Invoker);
10375 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010376}
10377
Faisal Valid6992ab2013-09-29 08:45:24 +000010378
10379
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010380void Sema::DefineImplicitLambdaToBlockPointerConversion(
10381 SourceLocation CurrentLocation,
10382 CXXConversionDecl *Conv)
10383{
Faisal Vali56fe35b2013-09-29 17:08:32 +000010384 assert(!Conv->getParent()->isGenericLambda());
Faisal Valid6992ab2013-09-29 08:45:24 +000010385
Eli Friedman86164e82013-09-05 00:02:25 +000010386 Conv->markUsed(Context);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010387
Eli Friedman9a14db32012-10-18 20:14:08 +000010388 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010389 DiagnosticErrorTrap Trap(Diags);
10390
Douglas Gregorac1303e2012-02-22 05:02:47 +000010391 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010392 Expr *This = ActOnCXXThis(CurrentLocation).take();
10393 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010394
Eli Friedman23f02672012-03-01 04:01:32 +000010395 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10396 Conv->getLocation(),
10397 Conv, DerefThis);
10398
10399 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10400 // behavior. Note that only the general conversion function does this
10401 // (since it's unusable otherwise); in the case where we inline the
10402 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010403 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000010404 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10405 CK_CopyAndAutoreleaseBlockObject,
10406 BuildBlock.get(), 0, VK_RValue);
10407
10408 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010409 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000010410 Conv->setInvalidDecl();
10411 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010412 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010413
Douglas Gregorac1303e2012-02-22 05:02:47 +000010414 // Create the return statement that returns the block from the conversion
10415 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010416 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010417 if (Return.isInvalid()) {
10418 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10419 Conv->setInvalidDecl();
10420 return;
10421 }
10422
10423 // Set the body of the conversion function.
10424 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010425 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010426 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010427 Conv->getLocation()));
10428
Douglas Gregorac1303e2012-02-22 05:02:47 +000010429 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010430 if (ASTMutationListener *L = getASTMutationListener()) {
10431 L->CompletedImplicitDefinition(Conv);
10432 }
10433}
10434
Douglas Gregorf52757d2012-03-10 06:53:13 +000010435/// \brief Determine whether the given list arguments contains exactly one
10436/// "real" (non-default) argument.
10437static bool hasOneRealArgument(MultiExprArg Args) {
10438 switch (Args.size()) {
10439 case 0:
10440 return false;
10441
10442 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010443 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010444 return false;
10445
10446 // fall through
10447 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010448 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010449 }
10450
10451 return false;
10452}
10453
John McCall60d7b3a2010-08-24 06:29:42 +000010454ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010455Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010456 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010457 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010458 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010459 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010460 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010461 unsigned ConstructKind,
10462 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010463 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010464
Douglas Gregor2f599792010-04-02 18:24:57 +000010465 // C++0x [class.copy]p34:
10466 // When certain criteria are met, an implementation is allowed to
10467 // omit the copy/move construction of a class object, even if the
10468 // copy/move constructor and/or destructor for the object have
10469 // side effects. [...]
10470 // - when a temporary class object that has not been bound to a
10471 // reference (12.2) would be copied/moved to a class object
10472 // with the same cv-unqualified type, the copy/move operation
10473 // can be omitted by constructing the temporary object
10474 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010475 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010476 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010477 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010478 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010479 }
Mike Stump1eb44332009-09-09 15:08:12 +000010480
10481 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010482 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010483 IsListInitialization, RequiresZeroInit,
10484 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010485}
10486
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010487/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10488/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010489ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010490Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10491 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010492 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010493 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010494 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010495 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010496 unsigned ConstructKind,
10497 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010498 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010499 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010500 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010501 HadMultipleCandidates,
10502 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010503 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10504 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010505}
10506
John McCall68c6c9a2010-02-02 09:10:11 +000010507void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010508 if (VD->isInvalidDecl()) return;
10509
John McCall68c6c9a2010-02-02 09:10:11 +000010510 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010511 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010512 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010513 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010514
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010515 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010516 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010517 CheckDestructorAccess(VD->getLocation(), Destructor,
10518 PDiag(diag::err_access_dtor_var)
10519 << VD->getDeclName()
10520 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010521 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010522
Stephen Hines651f13c2014-04-23 16:59:28 -070010523 if (Destructor->isTrivial()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010524 if (!VD->hasGlobalStorage()) return;
10525
10526 // Emit warning for non-trivial dtor in global scope (a real global,
10527 // class-static, function-static).
10528 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10529
10530 // TODO: this should be re-enabled for static locals by !CXAAtExit
10531 if (!VD->isStaticLocal())
10532 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010533}
10534
Douglas Gregor39da0b82009-09-09 23:08:42 +000010535/// \brief Given a constructor and the set of arguments provided for the
10536/// constructor, convert the arguments and add any required default arguments
10537/// to form a proper call to this constructor.
10538///
10539/// \returns true if an error occurred, false otherwise.
10540bool
10541Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10542 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010543 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010544 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010545 bool AllowExplicit,
10546 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010547 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10548 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010549 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010550
10551 const FunctionProtoType *Proto
10552 = Constructor->getType()->getAs<FunctionProtoType>();
10553 assert(Proto && "Constructor without a prototype?");
Stephen Hines651f13c2014-04-23 16:59:28 -070010554 unsigned NumParams = Proto->getNumParams();
10555
Douglas Gregor39da0b82009-09-09 23:08:42 +000010556 // If too few arguments are available, we'll fill in the rest with defaults.
Stephen Hines651f13c2014-04-23 16:59:28 -070010557 if (NumArgs < NumParams)
10558 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010559 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010560 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010561
10562 VariadicCallType CallType =
10563 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010564 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010565 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010566 Proto, 0,
10567 llvm::makeArrayRef(Args, NumArgs),
10568 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010569 CallType, AllowExplicit,
10570 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010571 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010572
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010573 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010574
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010575 CheckConstructorCall(Constructor,
10576 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10577 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010578 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010579
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010580 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010581}
10582
Anders Carlsson20d45d22009-12-12 00:32:00 +000010583static inline bool
10584CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10585 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010586 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010587 if (isa<NamespaceDecl>(DC)) {
10588 return SemaRef.Diag(FnDecl->getLocation(),
10589 diag::err_operator_new_delete_declared_in_namespace)
10590 << FnDecl->getDeclName();
10591 }
10592
10593 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010594 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010595 return SemaRef.Diag(FnDecl->getLocation(),
10596 diag::err_operator_new_delete_declared_static)
10597 << FnDecl->getDeclName();
10598 }
10599
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010600 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010601}
10602
Anders Carlsson156c78e2009-12-13 17:53:43 +000010603static inline bool
10604CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10605 CanQualType ExpectedResultType,
10606 CanQualType ExpectedFirstParamType,
10607 unsigned DependentParamTypeDiag,
10608 unsigned InvalidParamTypeDiag) {
Stephen Hines651f13c2014-04-23 16:59:28 -070010609 QualType ResultType =
10610 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson156c78e2009-12-13 17:53:43 +000010611
10612 // Check that the result type is not dependent.
10613 if (ResultType->isDependentType())
10614 return SemaRef.Diag(FnDecl->getLocation(),
10615 diag::err_operator_new_delete_dependent_result_type)
10616 << FnDecl->getDeclName() << ExpectedResultType;
10617
10618 // Check that the result type is what we expect.
10619 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10620 return SemaRef.Diag(FnDecl->getLocation(),
10621 diag::err_operator_new_delete_invalid_result_type)
10622 << FnDecl->getDeclName() << ExpectedResultType;
10623
10624 // A function template must have at least 2 parameters.
10625 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10626 return SemaRef.Diag(FnDecl->getLocation(),
10627 diag::err_operator_new_delete_template_too_few_parameters)
10628 << FnDecl->getDeclName();
10629
10630 // The function decl must have at least 1 parameter.
10631 if (FnDecl->getNumParams() == 0)
10632 return SemaRef.Diag(FnDecl->getLocation(),
10633 diag::err_operator_new_delete_too_few_parameters)
10634 << FnDecl->getDeclName();
10635
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010636 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010637 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10638 if (FirstParamType->isDependentType())
10639 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10640 << FnDecl->getDeclName() << ExpectedFirstParamType;
10641
10642 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010643 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010644 ExpectedFirstParamType)
10645 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10646 << FnDecl->getDeclName() << ExpectedFirstParamType;
10647
10648 return false;
10649}
10650
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010651static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010652CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010653 // C++ [basic.stc.dynamic.allocation]p1:
10654 // A program is ill-formed if an allocation function is declared in a
10655 // namespace scope other than global scope or declared static in global
10656 // scope.
10657 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10658 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010659
10660 CanQualType SizeTy =
10661 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10662
10663 // C++ [basic.stc.dynamic.allocation]p1:
10664 // The return type shall be void*. The first parameter shall have type
10665 // std::size_t.
10666 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10667 SizeTy,
10668 diag::err_operator_new_dependent_param_type,
10669 diag::err_operator_new_param_type))
10670 return true;
10671
10672 // C++ [basic.stc.dynamic.allocation]p1:
10673 // The first parameter shall not have an associated default argument.
10674 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010675 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010676 diag::err_operator_new_default_arg)
10677 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10678
10679 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010680}
10681
10682static bool
Richard Smith444d3842012-10-20 08:26:51 +000010683CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010684 // C++ [basic.stc.dynamic.deallocation]p1:
10685 // A program is ill-formed if deallocation functions are declared in a
10686 // namespace scope other than global scope or declared static in global
10687 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010688 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10689 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010690
10691 // C++ [basic.stc.dynamic.deallocation]p2:
10692 // Each deallocation function shall return void and its first parameter
10693 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010694 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10695 SemaRef.Context.VoidPtrTy,
10696 diag::err_operator_delete_dependent_param_type,
10697 diag::err_operator_delete_param_type))
10698 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010699
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010700 return false;
10701}
10702
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010703/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10704/// of this overloaded operator is well-formed. If so, returns false;
10705/// otherwise, emits appropriate diagnostics and returns true.
10706bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010707 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010708 "Expected an overloaded operator declaration");
10709
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010710 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10711
Mike Stump1eb44332009-09-09 15:08:12 +000010712 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010713 // The allocation and deallocation functions, operator new,
10714 // operator new[], operator delete and operator delete[], are
10715 // described completely in 3.7.3. The attributes and restrictions
10716 // found in the rest of this subclause do not apply to them unless
10717 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010718 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010719 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010720
Anders Carlssona3ccda52009-12-12 00:26:23 +000010721 if (Op == OO_New || Op == OO_Array_New)
10722 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010723
10724 // C++ [over.oper]p6:
10725 // An operator function shall either be a non-static member
10726 // function or be a non-member function and have at least one
10727 // parameter whose type is a class, a reference to a class, an
10728 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010729 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10730 if (MethodDecl->isStatic())
10731 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010732 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010733 } else {
10734 bool ClassOrEnumParam = false;
Stephen Hines651f13c2014-04-23 16:59:28 -070010735 for (auto Param : FnDecl->params()) {
10736 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010737 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10738 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010739 ClassOrEnumParam = true;
10740 break;
10741 }
10742 }
10743
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010744 if (!ClassOrEnumParam)
10745 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010746 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010747 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010748 }
10749
10750 // C++ [over.oper]p8:
10751 // An operator function cannot have default arguments (8.3.6),
10752 // except where explicitly stated below.
10753 //
Mike Stump1eb44332009-09-09 15:08:12 +000010754 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010755 // (C++ [over.call]p1).
10756 if (Op != OO_Call) {
Stephen Hines651f13c2014-04-23 16:59:28 -070010757 for (auto Param : FnDecl->params()) {
10758 if (Param->hasDefaultArg())
10759 return Diag(Param->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010760 diag::err_operator_overload_default_arg)
Stephen Hines651f13c2014-04-23 16:59:28 -070010761 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010762 }
10763 }
10764
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010765 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10766 { false, false, false }
10767#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10768 , { Unary, Binary, MemberOnly }
10769#include "clang/Basic/OperatorKinds.def"
10770 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010771
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010772 bool CanBeUnaryOperator = OperatorUses[Op][0];
10773 bool CanBeBinaryOperator = OperatorUses[Op][1];
10774 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010775
10776 // C++ [over.oper]p8:
10777 // [...] Operator functions cannot have more or fewer parameters
10778 // than the number required for the corresponding operator, as
10779 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010780 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010781 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010782 if (Op != OO_Call &&
10783 ((NumParams == 1 && !CanBeUnaryOperator) ||
10784 (NumParams == 2 && !CanBeBinaryOperator) ||
10785 (NumParams < 1) || (NumParams > 2))) {
10786 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010787 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010788 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010789 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010790 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010791 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010792 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010793 assert(CanBeBinaryOperator &&
10794 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010795 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010796 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010797
Chris Lattner416e46f2008-11-21 07:57:12 +000010798 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010799 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010800 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010801
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010802 // Overloaded operators other than operator() cannot be variadic.
10803 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010804 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010805 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010806 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010807 }
10808
10809 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010810 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10811 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010812 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010813 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010814 }
10815
10816 // C++ [over.inc]p1:
10817 // The user-defined function called operator++ implements the
10818 // prefix and postfix ++ operator. If this function is a member
10819 // function with no parameters, or a non-member function with one
10820 // parameter of class or enumeration type, it defines the prefix
10821 // increment operator ++ for objects of that type. If the function
10822 // is a member function with one parameter (which shall be of type
10823 // int) or a non-member function with two parameters (the second
10824 // of which shall be of type int), it defines the postfix
10825 // increment operator ++ for objects of that type.
10826 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10827 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Stephen Hines651f13c2014-04-23 16:59:28 -070010828 QualType ParamType = LastParam->getType();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010829
Stephen Hines651f13c2014-04-23 16:59:28 -070010830 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
10831 !ParamType->isDependentType())
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010832 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010833 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010834 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010835 }
10836
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010837 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010838}
Chris Lattner5a003a42008-12-17 07:09:26 +000010839
Sean Hunta6c058d2010-01-13 09:01:02 +000010840/// CheckLiteralOperatorDeclaration - Check whether the declaration
10841/// of this literal operator function is well-formed. If so, returns
10842/// false; otherwise, emits appropriate diagnostics and returns true.
10843bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010844 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010845 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10846 << FnDecl->getDeclName();
10847 return true;
10848 }
10849
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010850 if (FnDecl->isExternC()) {
10851 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10852 return true;
10853 }
10854
Sean Hunta6c058d2010-01-13 09:01:02 +000010855 bool Valid = false;
10856
Richard Smith36f5cfe2012-03-09 08:00:36 +000010857 // This might be the definition of a literal operator template.
10858 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10859 // This might be a specialization of a literal operator template.
10860 if (!TpDecl)
10861 TpDecl = FnDecl->getPrimaryTemplate();
10862
Richard Smithb328e292013-10-07 19:57:58 +000010863 // template <char...> type operator "" name() and
10864 // template <class T, T...> type operator "" name() are the only valid
10865 // template signatures, and the only valid signatures with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010866 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010867 if (FnDecl->param_size() == 0) {
Richard Smithb328e292013-10-07 19:57:58 +000010868 // Must have one or two template parameters
Sean Hunt216c2782010-04-07 23:11:06 +000010869 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10870 if (Params->size() == 1) {
10871 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010872 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010873
Sean Hunt216c2782010-04-07 23:11:06 +000010874 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010875 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10876 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10877 Valid = true;
Richard Smithb328e292013-10-07 19:57:58 +000010878 } else if (Params->size() == 2) {
10879 TemplateTypeParmDecl *PmType =
10880 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10881 NonTypeTemplateParmDecl *PmArgs =
10882 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10883
10884 // The second template parameter must be a parameter pack with the
10885 // first template parameter as its type.
10886 if (PmType && PmArgs &&
10887 !PmType->isTemplateParameterPack() &&
10888 PmArgs->isTemplateParameterPack()) {
10889 const TemplateTypeParmType *TArgs =
10890 PmArgs->getType()->getAs<TemplateTypeParmType>();
10891 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10892 TArgs->getIndex() == PmType->getIndex()) {
10893 Valid = true;
10894 if (ActiveTemplateInstantiations.empty())
10895 Diag(FnDecl->getLocation(),
10896 diag::ext_string_literal_operator_template);
10897 }
10898 }
Sean Hunt216c2782010-04-07 23:11:06 +000010899 }
10900 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010901 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010902 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010903 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10904
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010905 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010906
Sean Hunt30019c02010-04-07 22:57:35 +000010907 // unsigned long long int, long double, and any character type are allowed
10908 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010909 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10910 Context.hasSameType(T, Context.LongDoubleTy) ||
10911 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010912 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010913 Context.hasSameType(T, Context.Char16Ty) ||
10914 Context.hasSameType(T, Context.Char32Ty)) {
10915 if (++Param == FnDecl->param_end())
10916 Valid = true;
10917 goto FinishedParams;
10918 }
10919
Sean Hunt30019c02010-04-07 22:57:35 +000010920 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010921 const PointerType *PT = T->getAs<PointerType>();
10922 if (!PT)
10923 goto FinishedParams;
10924 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010925 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010926 goto FinishedParams;
10927 T = T.getUnqualifiedType();
10928
10929 // Move on to the second parameter;
10930 ++Param;
10931
10932 // If there is no second parameter, the first must be a const char *
10933 if (Param == FnDecl->param_end()) {
10934 if (Context.hasSameType(T, Context.CharTy))
10935 Valid = true;
10936 goto FinishedParams;
10937 }
10938
10939 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10940 // are allowed as the first parameter to a two-parameter function
10941 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010942 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010943 Context.hasSameType(T, Context.Char16Ty) ||
10944 Context.hasSameType(T, Context.Char32Ty)))
10945 goto FinishedParams;
10946
10947 // The second and final parameter must be an std::size_t
10948 T = (*Param)->getType().getUnqualifiedType();
10949 if (Context.hasSameType(T, Context.getSizeType()) &&
10950 ++Param == FnDecl->param_end())
10951 Valid = true;
10952 }
10953
10954 // FIXME: This diagnostic is absolutely terrible.
10955FinishedParams:
10956 if (!Valid) {
10957 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10958 << FnDecl->getDeclName();
10959 return true;
10960 }
10961
Richard Smitha9e88b22012-03-09 08:16:22 +000010962 // A parameter-declaration-clause containing a default argument is not
10963 // equivalent to any of the permitted forms.
Stephen Hines651f13c2014-04-23 16:59:28 -070010964 for (auto Param : FnDecl->params()) {
10965 if (Param->hasDefaultArg()) {
10966 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smitha9e88b22012-03-09 08:16:22 +000010967 diag::err_literal_operator_default_argument)
Stephen Hines651f13c2014-04-23 16:59:28 -070010968 << Param->getDefaultArgRange();
Richard Smitha9e88b22012-03-09 08:16:22 +000010969 break;
10970 }
10971 }
10972
Richard Smith2fb4ae32012-03-08 02:39:21 +000010973 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010974 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10975 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010976 // C++11 [usrlit.suffix]p1:
10977 // Literal suffix identifiers that do not start with an underscore
10978 // are reserved for future standardization.
Richard Smith4ac537b2013-07-23 08:14:48 +000010979 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10980 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor1155c422011-08-30 22:40:35 +000010981 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010982
Sean Hunta6c058d2010-01-13 09:01:02 +000010983 return false;
10984}
10985
Douglas Gregor074149e2009-01-05 19:45:36 +000010986/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10987/// linkage specification, including the language and (if present)
Stephen Hines651f13c2014-04-23 16:59:28 -070010988/// the '{'. ExternLoc is the location of the 'extern', Lang is the
10989/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor074149e2009-01-05 19:45:36 +000010990/// the '{' brace. Otherwise, this linkage specification does not
10991/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010992Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Stephen Hines651f13c2014-04-23 16:59:28 -070010993 Expr *LangStr,
Chris Lattner7d642712010-11-09 20:15:55 +000010994 SourceLocation LBraceLoc) {
Stephen Hines651f13c2014-04-23 16:59:28 -070010995 StringLiteral *Lit = cast<StringLiteral>(LangStr);
10996 if (!Lit->isAscii()) {
10997 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
10998 << LangStr->getSourceRange();
10999 return 0;
11000 }
11001
11002 StringRef Lang = Lit->getString();
Chris Lattnercc98eac2008-12-17 07:13:27 +000011003 LinkageSpecDecl::LanguageIDs Language;
Stephen Hines651f13c2014-04-23 16:59:28 -070011004 if (Lang == "C")
Chris Lattnercc98eac2008-12-17 07:13:27 +000011005 Language = LinkageSpecDecl::lang_c;
Stephen Hines651f13c2014-04-23 16:59:28 -070011006 else if (Lang == "C++")
Chris Lattnercc98eac2008-12-17 07:13:27 +000011007 Language = LinkageSpecDecl::lang_cxx;
11008 else {
Stephen Hines651f13c2014-04-23 16:59:28 -070011009 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11010 << LangStr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011011 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000011012 }
Mike Stump1eb44332009-09-09 15:08:12 +000011013
Chris Lattnercc98eac2008-12-17 07:13:27 +000011014 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000011015
Stephen Hines651f13c2014-04-23 16:59:28 -070011016 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11017 LangStr->getExprLoc(), Language,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000011018 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011019 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000011020 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000011021 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000011022}
11023
Abramo Bagnara35f9a192010-07-30 16:47:02 +000011024/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000011025/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11026/// valid, it's the position of the closing '}' brace in a linkage
11027/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000011028Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000011029 Decl *LinkageSpec,
11030 SourceLocation RBraceLoc) {
Stephen Hines651f13c2014-04-23 16:59:28 -070011031 if (RBraceLoc.isValid()) {
11032 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11033 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000011034 }
Stephen Hines651f13c2014-04-23 16:59:28 -070011035 PopDeclContext();
Douglas Gregor074149e2009-01-05 19:45:36 +000011036 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000011037}
11038
Michael Han684aa732013-02-22 17:15:32 +000011039Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11040 AttributeList *AttrList,
11041 SourceLocation SemiLoc) {
11042 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11043 // Attribute declarations appertain to empty declaration so we handle
11044 // them here.
11045 if (AttrList)
11046 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000011047
Michael Han684aa732013-02-22 17:15:32 +000011048 CurContext->addDecl(ED);
11049 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000011050}
11051
Douglas Gregord308e622009-05-18 20:51:54 +000011052/// \brief Perform semantic analysis for the variable declaration that
11053/// occurs within a C++ catch clause, returning the newly-created
11054/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011055VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000011056 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011057 SourceLocation StartLoc,
11058 SourceLocation Loc,
11059 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000011060 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000011061 QualType ExDeclType = TInfo->getType();
11062
Sebastian Redl4b07b292008-12-22 19:15:10 +000011063 // Arrays and functions decay.
11064 if (ExDeclType->isArrayType())
11065 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11066 else if (ExDeclType->isFunctionType())
11067 ExDeclType = Context.getPointerType(ExDeclType);
11068
11069 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11070 // The exception-declaration shall not denote a pointer or reference to an
11071 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011072 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000011073 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000011074 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011075 Invalid = true;
11076 }
Douglas Gregord308e622009-05-18 20:51:54 +000011077
Sebastian Redl4b07b292008-12-22 19:15:10 +000011078 QualType BaseType = ExDeclType;
11079 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000011080 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000011081 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011082 BaseType = Ptr->getPointeeType();
11083 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000011084 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000011085 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011086 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011087 BaseType = Ref->getPointeeType();
11088 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000011089 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011090 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011091 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000011092 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000011093 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011094
Mike Stump1eb44332009-09-09 15:08:12 +000011095 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000011096 RequireNonAbstractType(Loc, ExDeclType,
11097 diag::err_abstract_type_in_decl,
11098 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000011099 Invalid = true;
11100
John McCall5a180392010-07-24 00:37:23 +000011101 // Only the non-fragile NeXT runtime currently supports C++ catches
11102 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000011103 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000011104 QualType T = ExDeclType;
11105 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11106 T = RT->getPointeeType();
11107
11108 if (T->isObjCObjectType()) {
11109 Diag(Loc, diag::err_objc_object_catch);
11110 Invalid = true;
11111 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000011112 // FIXME: should this be a test for macosx-fragile specifically?
11113 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000011114 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000011115 }
11116 }
11117
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011118 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000011119 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000011120 ExDecl->setExceptionVariable(true);
11121
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011122 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011123 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011124 Invalid = true;
11125
Douglas Gregorc41b8782011-07-06 18:14:43 +000011126 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000011127 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000011128 // Insulate this from anything else we might currently be parsing.
11129 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11130
Douglas Gregor6d182892010-03-05 23:38:39 +000011131 // C++ [except.handle]p16:
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011132 // The object declared in an exception-declaration or, if the
11133 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6d182892010-03-05 23:38:39 +000011134 // copy-initialized (8.5) from the exception object. [...]
11135 // The object is destroyed when the handler exits, after the destruction
11136 // of any automatic objects initialized within the handler.
11137 //
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011138 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6d182892010-03-05 23:38:39 +000011139 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000011140 QualType initType = ExDeclType;
11141
11142 InitializedEntity entity =
11143 InitializedEntity::InitializeVariable(ExDecl);
11144 InitializationKind initKind =
11145 InitializationKind::CreateCopy(Loc, SourceLocation());
11146
11147 Expr *opaqueValue =
11148 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000011149 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11150 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000011151 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000011152 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000011153 else {
11154 // If the constructor used was non-trivial, set this as the
11155 // "initializer".
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011156 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCalle996ffd2011-02-16 08:02:54 +000011157 if (!construct->getConstructor()->isTrivial()) {
11158 Expr *init = MaybeCreateExprWithCleanups(construct);
11159 ExDecl->setInit(init);
11160 }
11161
11162 // And make sure it's destructable.
11163 FinalizeVarWithDestructor(ExDecl, recordType);
11164 }
Douglas Gregor6d182892010-03-05 23:38:39 +000011165 }
11166 }
11167
Douglas Gregord308e622009-05-18 20:51:54 +000011168 if (Invalid)
11169 ExDecl->setInvalidDecl();
11170
11171 return ExDecl;
11172}
11173
11174/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11175/// handler.
John McCalld226f652010-08-21 09:40:31 +000011176Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000011177 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000011178 bool Invalid = D.isInvalidType();
11179
11180 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000011181 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11182 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000011183 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11184 D.getIdentifierLoc());
11185 Invalid = true;
11186 }
11187
Sebastian Redl4b07b292008-12-22 19:15:10 +000011188 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000011189 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000011190 LookupOrdinaryName,
11191 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011192 // The scope should be freshly made just for us. There is just no way
11193 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000011194 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000011195 if (PrevDecl->isTemplateParameter()) {
11196 // Maybe we will complain about the shadowed template parameter.
11197 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000011198 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011199 }
11200 }
11201
Chris Lattnereaaebc72009-04-25 08:06:05 +000011202 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011203 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11204 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000011205 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011206 }
11207
Douglas Gregor83cb9422010-09-09 17:09:21 +000011208 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000011209 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011210 D.getIdentifierLoc(),
11211 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000011212 if (Invalid)
11213 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000011214
Sebastian Redl4b07b292008-12-22 19:15:10 +000011215 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011216 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000011217 PushOnScopeChains(ExDecl, S);
11218 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011219 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000011220
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011221 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000011222 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011223}
Anders Carlssonfb311762009-03-14 00:25:26 +000011224
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011225Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000011226 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000011227 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011228 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000011229 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000011230
Richard Smithe3f470a2012-07-11 22:37:56 +000011231 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11232 return 0;
11233
11234 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11235 AssertMessage, RParenLoc, false);
11236}
11237
11238Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11239 Expr *AssertExpr,
11240 StringLiteral *AssertMessage,
11241 SourceLocation RParenLoc,
11242 bool Failed) {
11243 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11244 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000011245 // In a static_assert-declaration, the constant-expression shall be a
11246 // constant expression that can be contextually converted to bool.
11247 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11248 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011249 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000011250
Richard Smithdaaefc52011-12-14 23:32:26 +000011251 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000011252 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011253 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000011254 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011255 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000011256
Richard Smithe3f470a2012-07-11 22:37:56 +000011257 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011258 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000011259 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000011260 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011261 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000011262 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000011263 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000011264 }
Anders Carlssonc3082412009-03-14 00:33:21 +000011265 }
Mike Stump1eb44332009-09-09 15:08:12 +000011266
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011267 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000011268 AssertExpr, AssertMessage, RParenLoc,
11269 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000011270
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011271 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000011272 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000011273}
Sebastian Redl50de12f2009-03-24 22:27:57 +000011274
Douglas Gregor1d869352010-04-07 16:53:43 +000011275/// \brief Perform semantic analysis of the given friend type declaration.
11276///
11277/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000011278FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000011279 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011280 TypeSourceInfo *TSInfo) {
11281 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11282
11283 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000011284 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000011285
Richard Smith6b130222011-10-18 21:39:00 +000011286 // C++03 [class.friend]p2:
11287 // An elaborated-type-specifier shall be used in a friend declaration
11288 // for a class.*
11289 //
11290 // * The class-key of the elaborated-type-specifier is required.
11291 if (!ActiveTemplateInstantiations.empty()) {
11292 // Do not complain about the form of friend template types during
11293 // template instantiation; we will already have complained when the
11294 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011295 } else {
11296 if (!T->isElaboratedTypeSpecifier()) {
11297 // If we evaluated the type to a record type, suggest putting
11298 // a tag in front.
11299 if (const RecordType *RT = T->getAs<RecordType>()) {
11300 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000011301
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011302 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000011303
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011304 Diag(TypeRange.getBegin(),
11305 getLangOpts().CPlusPlus11 ?
11306 diag::warn_cxx98_compat_unelaborated_friend_type :
11307 diag::ext_unelaborated_friend_type)
11308 << (unsigned) RD->getTagKind()
11309 << T
11310 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11311 InsertionText);
11312 } else {
11313 Diag(FriendLoc,
11314 getLangOpts().CPlusPlus11 ?
11315 diag::warn_cxx98_compat_nonclass_type_friend :
11316 diag::ext_nonclass_type_friend)
11317 << T
11318 << TypeRange;
11319 }
11320 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000011321 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000011322 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011323 diag::warn_cxx98_compat_enum_friend :
11324 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000011325 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000011326 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000011327 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011328
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011329 // C++11 [class.friend]p3:
11330 // A friend declaration that does not declare a function shall have one
11331 // of the following forms:
11332 // friend elaborated-type-specifier ;
11333 // friend simple-type-specifier ;
11334 // friend typename-specifier ;
11335 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11336 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11337 }
Richard Smithd6f80da2012-09-20 01:31:00 +000011338
Douglas Gregor06245bf2010-04-07 17:57:12 +000011339 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000011340 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000011341 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000011342 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000011343}
11344
John McCall9a34edb2010-10-19 01:40:49 +000011345/// Handle a friend tag declaration where the scope specifier was
11346/// templated.
11347Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11348 unsigned TagSpec, SourceLocation TagLoc,
11349 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011350 IdentifierInfo *Name,
11351 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000011352 AttributeList *Attr,
11353 MultiTemplateParamsArg TempParamLists) {
11354 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11355
11356 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000011357 bool Invalid = false;
11358
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000011359 if (TemplateParameterList *TemplateParams =
11360 MatchTemplateParametersToScopeSpecifier(
11361 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11362 isExplicitSpecialization, Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000011363 if (TemplateParams->size() > 0) {
11364 // This is a declaration of a class template.
11365 if (Invalid)
11366 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000011367
Eric Christopher4110e132011-07-21 05:34:24 +000011368 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11369 SS, Name, NameLoc, Attr,
11370 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000011371 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000011372 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011373 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000011374 } else {
11375 // The "template<>" header is extraneous.
11376 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11377 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11378 isExplicitSpecialization = true;
11379 }
11380 }
11381
11382 if (Invalid) return 0;
11383
John McCall9a34edb2010-10-19 01:40:49 +000011384 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000011385 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011386 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000011387 isAllExplicitSpecializations = false;
11388 break;
11389 }
11390 }
11391
11392 // FIXME: don't ignore attributes.
11393
11394 // If it's explicit specializations all the way down, just forget
11395 // about the template header and build an appropriate non-templated
11396 // friend. TODO: for source fidelity, remember the headers.
11397 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011398 if (SS.isEmpty()) {
11399 bool Owned = false;
11400 bool IsDependent = false;
11401 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Stephen Hines651f13c2014-04-23 16:59:28 -070011402 Attr, AS_public,
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011403 /*ModulePrivateLoc=*/SourceLocation(),
Stephen Hines651f13c2014-04-23 16:59:28 -070011404 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000011405 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011406 /*ScopedEnumUsesClassTag=*/false,
Stephen Hines651f13c2014-04-23 16:59:28 -070011407 /*UnderlyingType=*/TypeResult(),
11408 /*IsTypeSpecifier=*/false);
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011409 }
Stephen Hines651f13c2014-04-23 16:59:28 -070011410
Douglas Gregor2494dd02011-03-01 01:34:45 +000011411 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000011412 ElaboratedTypeKeyword Keyword
11413 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011414 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000011415 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011416 if (T.isNull())
11417 return 0;
11418
11419 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11420 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000011421 DependentNameTypeLoc TL =
11422 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011423 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011424 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011425 TL.setNameLoc(NameLoc);
11426 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000011427 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011428 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000011429 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000011430 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011431 }
11432
11433 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011434 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011435 Friend->setAccess(AS_public);
11436 CurContext->addDecl(Friend);
11437 return Friend;
11438 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011439
11440 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11441
11442
John McCall9a34edb2010-10-19 01:40:49 +000011443
11444 // Handle the case of a templated-scope friend class. e.g.
11445 // template <class T> class A<T>::B;
11446 // FIXME: we don't support these right now.
Richard Smithce6426f2013-11-08 18:59:56 +000011447 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11448 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCall9a34edb2010-10-19 01:40:49 +000011449 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11450 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11451 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011452 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011453 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011454 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011455 TL.setNameLoc(NameLoc);
11456
11457 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011458 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011459 Friend->setAccess(AS_public);
11460 Friend->setUnsupportedFriend(true);
11461 CurContext->addDecl(Friend);
11462 return Friend;
11463}
11464
11465
John McCalldd4a3b02009-09-16 22:47:08 +000011466/// Handle a friend type declaration. This works in tandem with
11467/// ActOnTag.
11468///
11469/// Notes on friend class templates:
11470///
11471/// We generally treat friend class declarations as if they were
11472/// declaring a class. So, for example, the elaborated type specifier
11473/// in a friend declaration is required to obey the restrictions of a
11474/// class-head (i.e. no typedefs in the scope chain), template
11475/// parameters are required to match up with simple template-ids, &c.
11476/// However, unlike when declaring a template specialization, it's
11477/// okay to refer to a template specialization without an empty
11478/// template parameter declaration, e.g.
11479/// friend class A<T>::B<unsigned>;
11480/// We permit this as a special case; if there are any template
11481/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011482/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011483Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011484 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011485 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011486
11487 assert(DS.isFriendSpecified());
11488 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11489
John McCalldd4a3b02009-09-16 22:47:08 +000011490 // Try to convert the decl specifier to a type. This works for
11491 // friend templates because ActOnTag never produces a ClassTemplateDecl
11492 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011493 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011494 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11495 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011496 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011497 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011498
Douglas Gregor6ccab972010-12-16 01:14:37 +000011499 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11500 return 0;
11501
John McCalldd4a3b02009-09-16 22:47:08 +000011502 // This is definitely an error in C++98. It's probably meant to
11503 // be forbidden in C++0x, too, but the specification is just
11504 // poorly written.
11505 //
11506 // The problem is with declarations like the following:
11507 // template <T> friend A<T>::foo;
11508 // where deciding whether a class C is a friend or not now hinges
11509 // on whether there exists an instantiation of A that causes
11510 // 'foo' to equal C. There are restrictions on class-heads
11511 // (which we declare (by fiat) elaborated friend declarations to
11512 // be) that makes this tractable.
11513 //
11514 // FIXME: handle "template <> friend class A<T>;", which
11515 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011516 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011517 Diag(Loc, diag::err_tagless_friend_type_template)
11518 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011519 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011520 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011521
John McCall02cace72009-08-28 07:59:38 +000011522 // C++98 [class.friend]p1: A friend of a class is a function
11523 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011524 // This is fixed in DR77, which just barely didn't make the C++03
11525 // deadline. It's also a very silly restriction that seriously
11526 // affects inner classes and which nobody else seems to implement;
11527 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011528 //
11529 // But note that we could warn about it: it's always useless to
11530 // friend one of your own members (it's not, however, worthless to
11531 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011532
John McCalldd4a3b02009-09-16 22:47:08 +000011533 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011534 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011535 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011536 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011537 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011538 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011539 DS.getFriendSpecLoc());
11540 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011541 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011542
11543 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011544 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011545
John McCalldd4a3b02009-09-16 22:47:08 +000011546 D->setAccess(AS_public);
11547 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011548
John McCalld226f652010-08-21 09:40:31 +000011549 return D;
John McCall02cace72009-08-28 07:59:38 +000011550}
11551
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011552NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11553 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011554 const DeclSpec &DS = D.getDeclSpec();
11555
11556 assert(DS.isFriendSpecified());
11557 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11558
11559 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011560 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011561
11562 // C++ [class.friend]p1
11563 // A friend of a class is a function or class....
11564 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011565 // It *doesn't* see through dependent types, which is correct
11566 // according to [temp.arg.type]p3:
11567 // If a declaration acquires a function type through a
11568 // type dependent on a template-parameter and this causes
11569 // a declaration that does not use the syntactic form of a
11570 // function declarator to have a function type, the program
11571 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011572 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011573 Diag(Loc, diag::err_unexpected_friend);
11574
11575 // It might be worthwhile to try to recover by creating an
11576 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011577 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011578 }
11579
11580 // C++ [namespace.memdef]p3
11581 // - If a friend declaration in a non-local class first declares a
11582 // class or function, the friend class or function is a member
11583 // of the innermost enclosing namespace.
11584 // - The name of the friend is not found by simple name lookup
11585 // until a matching declaration is provided in that namespace
11586 // scope (either before or after the class declaration granting
11587 // friendship).
11588 // - If a friend function is called, its name may be found by the
11589 // name lookup that considers functions from namespaces and
11590 // classes associated with the types of the function arguments.
11591 // - When looking for a prior declaration of a class or a function
11592 // declared as a friend, scopes outside the innermost enclosing
11593 // namespace scope are not considered.
11594
John McCall337ec3d2010-10-12 23:13:28 +000011595 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011596 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11597 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011598 assert(Name);
11599
Douglas Gregor6ccab972010-12-16 01:14:37 +000011600 // Check for unexpanded parameter packs.
11601 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11602 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11603 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11604 return 0;
11605
John McCall67d1a672009-08-06 02:15:43 +000011606 // The context we found the declaration in, or in which we should
11607 // create the declaration.
11608 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011609 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011610 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011611 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011612
Richard Smith4e9686b2013-08-09 04:35:01 +000011613 // There are five cases here.
11614 // - There's no scope specifier and we're in a local class. Only look
11615 // for functions declared in the immediately-enclosing block scope.
11616 // We recover from invalid scope qualifiers as if they just weren't there.
11617 FunctionDecl *FunctionContainingLocalClass = 0;
11618 if ((SS.isInvalid() || !SS.isSet()) &&
11619 (FunctionContainingLocalClass =
11620 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11621 // C++11 [class.friend]p11:
John McCall29ae6e52010-10-13 05:45:15 +000011622 // If a friend declaration appears in a local class and the name
11623 // specified is an unqualified name, a prior declaration is
11624 // looked up without considering scopes that are outside the
11625 // innermost enclosing non-class scope. For a friend function
11626 // declaration, if there is no prior declaration, the program is
11627 // ill-formed.
Richard Smith4e9686b2013-08-09 04:35:01 +000011628
11629 // Find the innermost enclosing non-class scope. This is the block
11630 // scope containing the local class definition (or for a nested class,
11631 // the outer local class).
11632 DCScope = S->getFnParent();
11633
11634 // Look up the function name in the scope.
11635 Previous.clear(LookupLocalFriendName);
11636 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11637
11638 if (!Previous.empty()) {
11639 // All possible previous declarations must have the same context:
11640 // either they were declared at block scope or they are members of
11641 // one of the enclosing local classes.
11642 DC = Previous.getRepresentativeDecl()->getDeclContext();
11643 } else {
11644 // This is ill-formed, but provide the context that we would have
11645 // declared the function in, if we were permitted to, for error recovery.
11646 DC = FunctionContainingLocalClass;
11647 }
Richard Smitha41c97a2013-09-20 01:15:31 +000011648 adjustContextForLocalExternDecl(DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011649
11650 // C++ [class.friend]p6:
11651 // A function can be defined in a friend declaration of a class if and
11652 // only if the class is a non-local class (9.8), the function name is
11653 // unqualified, and the function has namespace scope.
11654 if (D.isFunctionDefinition()) {
11655 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11656 }
11657
11658 // - There's no scope specifier, in which case we just go to the
11659 // appropriate scope and look for a function or function template
11660 // there as appropriate.
11661 } else if (SS.isInvalid() || !SS.isSet()) {
11662 // C++11 [namespace.memdef]p3:
11663 // If the name in a friend declaration is neither qualified nor
11664 // a template-id and the declaration is a function or an
11665 // elaborated-type-specifier, the lookup to determine whether
11666 // the entity has been previously declared shall not consider
11667 // any scopes outside the innermost enclosing namespace.
John McCall8a407372010-10-14 22:22:28 +000011668 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011669
John McCall29ae6e52010-10-13 05:45:15 +000011670 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011671 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011672
Rafael Espindola11dc6342013-04-25 20:12:36 +000011673 // Skip class contexts. If someone can cite chapter and verse
11674 // for this behavior, that would be nice --- it's what GCC and
11675 // EDG do, and it seems like a reasonable intent, but the spec
11676 // really only says that checks for unqualified existing
11677 // declarations should stop at the nearest enclosing namespace,
11678 // not that they should only consider the nearest enclosing
11679 // namespace.
11680 while (DC->isRecord())
11681 DC = DC->getParent();
11682
11683 DeclContext *LookupDC = DC;
11684 while (LookupDC->isTransparentContext())
11685 LookupDC = LookupDC->getParent();
11686
11687 while (true) {
11688 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011689
Rafael Espindola11dc6342013-04-25 20:12:36 +000011690 if (!Previous.empty()) {
11691 DC = LookupDC;
11692 break;
John McCall8a407372010-10-14 22:22:28 +000011693 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011694
11695 if (isTemplateId) {
11696 if (isa<TranslationUnitDecl>(LookupDC)) break;
11697 } else {
11698 if (LookupDC->isFileContext()) break;
11699 }
11700 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011701 }
11702
John McCall380aaa42010-10-13 06:22:15 +000011703 DCScope = getScopeForDeclContext(S, DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011704
John McCall337ec3d2010-10-12 23:13:28 +000011705 // - There's a non-dependent scope specifier, in which case we
11706 // compute it and do a previous lookup there for a function
11707 // or function template.
11708 } else if (!SS.getScopeRep()->isDependent()) {
11709 DC = computeDeclContext(SS);
11710 if (!DC) return 0;
11711
11712 if (RequireCompleteDeclContext(SS, DC)) return 0;
11713
11714 LookupQualifiedName(Previous, DC);
11715
11716 // Ignore things found implicitly in the wrong scope.
11717 // TODO: better diagnostics for this case. Suggesting the right
11718 // qualified scope would be nice...
11719 LookupResult::Filter F = Previous.makeFilter();
11720 while (F.hasNext()) {
11721 NamedDecl *D = F.next();
11722 if (!DC->InEnclosingNamespaceSetOf(
11723 D->getDeclContext()->getRedeclContext()))
11724 F.erase();
11725 }
11726 F.done();
11727
11728 if (Previous.empty()) {
11729 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011730 Diag(Loc, diag::err_qualified_friend_not_found)
11731 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011732 return 0;
11733 }
11734
11735 // C++ [class.friend]p1: A friend of a class is a function or
11736 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011737 if (DC->Equals(CurContext))
11738 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011739 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011740 diag::warn_cxx98_compat_friend_is_member :
11741 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011742
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011743 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011744 // C++ [class.friend]p6:
11745 // A function can be defined in a friend declaration of a class if and
11746 // only if the class is a non-local class (9.8), the function name is
11747 // unqualified, and the function has namespace scope.
11748 SemaDiagnosticBuilder DB
11749 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11750
11751 DB << SS.getScopeRep();
11752 if (DC->isFileContext())
11753 DB << FixItHint::CreateRemoval(SS.getRange());
11754 SS.clear();
11755 }
John McCall337ec3d2010-10-12 23:13:28 +000011756
11757 // - There's a scope specifier that does not match any template
11758 // parameter lists, in which case we use some arbitrary context,
11759 // create a method or method template, and wait for instantiation.
11760 // - There's a scope specifier that does match some template
11761 // parameter lists, which we don't handle right now.
11762 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011763 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011764 // C++ [class.friend]p6:
11765 // A function can be defined in a friend declaration of a class if and
11766 // only if the class is a non-local class (9.8), the function name is
11767 // unqualified, and the function has namespace scope.
11768 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11769 << SS.getScopeRep();
11770 }
11771
John McCall337ec3d2010-10-12 23:13:28 +000011772 DC = CurContext;
11773 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011774 }
Douglas Gregor883af832011-10-10 01:11:59 +000011775
John McCall29ae6e52010-10-13 05:45:15 +000011776 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011777 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011778 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11779 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11780 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011781 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011782 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11783 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011784 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011785 }
John McCall67d1a672009-08-06 02:15:43 +000011786 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011787
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011788 // FIXME: This is an egregious hack to cope with cases where the scope stack
11789 // does not contain the declaration context, i.e., in an out-of-line
11790 // definition of a class.
11791 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11792 if (!DCScope) {
11793 FakeDCScope.setEntity(DC);
11794 DCScope = &FakeDCScope;
11795 }
Richard Smith4e9686b2013-08-09 04:35:01 +000011796
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011797 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011798 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011799 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011800 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011801
Douglas Gregor182ddf02009-09-28 00:08:27 +000011802 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011803
Richard Smith4e9686b2013-08-09 04:35:01 +000011804 // If we performed typo correction, we might have added a scope specifier
11805 // and changed the decl context.
11806 DC = ND->getDeclContext();
11807
John McCallab88d972009-08-31 22:39:49 +000011808 // Add the function declaration to the appropriate lookup tables,
11809 // adjusting the redeclarations list as necessary. We don't
11810 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011811 //
John McCallab88d972009-08-31 22:39:49 +000011812 // Also update the scope-based lookup if the target context's
11813 // lookup context is in lexical scope.
11814 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011815 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011816 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011817 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011818 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011819 }
John McCall02cace72009-08-28 07:59:38 +000011820
11821 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011822 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011823 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011824 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011825 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011826
John McCall1f2e1a92012-08-10 03:15:35 +000011827 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011828 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011829 } else {
11830 if (DC->isRecord()) CheckFriendAccess(ND);
11831
John McCall6102ca12010-10-16 06:59:13 +000011832 FunctionDecl *FD;
11833 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11834 FD = FTD->getTemplatedDecl();
11835 else
11836 FD = cast<FunctionDecl>(ND);
11837
David Majnemerf6a144f2013-06-25 23:09:30 +000011838 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11839 // default argument expression, that declaration shall be a definition
11840 // and shall be the only declaration of the function or function
11841 // template in the translation unit.
11842 if (functionDeclHasDefaultArgument(FD)) {
11843 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11844 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11845 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11846 } else if (!D.isFunctionDefinition())
11847 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11848 }
11849
John McCall6102ca12010-10-16 06:59:13 +000011850 // Mark templated-scope function declarations as unsupported.
11851 if (FD->getNumTemplateParameterLists())
11852 FrD->setUnsupportedFriend(true);
11853 }
John McCall337ec3d2010-10-12 23:13:28 +000011854
John McCalld226f652010-08-21 09:40:31 +000011855 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011856}
11857
John McCalld226f652010-08-21 09:40:31 +000011858void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11859 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011860
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011861 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011862 if (!Fn) {
11863 Diag(DelLoc, diag::err_deleted_non_function);
11864 return;
11865 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011866
Douglas Gregoref96ee02012-01-14 16:38:05 +000011867 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011868 // Don't consider the implicit declaration we generate for explicit
11869 // specializations. FIXME: Do not generate these implicit declarations.
Stephen Hines651f13c2014-04-23 16:59:28 -070011870 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
11871 Prev->getPreviousDecl()) &&
11872 !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011873 Diag(DelLoc, diag::err_deleted_decl_not_first);
Stephen Hines651f13c2014-04-23 16:59:28 -070011874 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
11875 Prev->isImplicit() ? diag::note_previous_implicit_declaration
11876 : diag::note_previous_declaration);
David Blaikied9cf8262012-06-25 21:55:30 +000011877 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011878 // If the declaration wasn't the first, we delete the function anyway for
11879 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011880 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011881 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011882
11883 if (Fn->isDeleted())
11884 return;
11885
11886 // See if we're deleting a function which is already known to override a
11887 // non-deleted virtual function.
11888 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11889 bool IssuedDiagnostic = false;
11890 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11891 E = MD->end_overridden_methods();
11892 I != E; ++I) {
11893 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11894 if (!IssuedDiagnostic) {
11895 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11896 IssuedDiagnostic = true;
11897 }
11898 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11899 }
11900 }
11901 }
11902
Stephen Hines651f13c2014-04-23 16:59:28 -070011903 // C++11 [basic.start.main]p3:
11904 // A program that defines main as deleted [...] is ill-formed.
11905 if (Fn->isMain())
11906 Diag(DelLoc, diag::err_deleted_main);
11907
Sean Hunt10620eb2011-05-06 20:44:56 +000011908 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011909}
Sebastian Redl13e88542009-04-27 21:33:24 +000011910
Sean Hunte4246a62011-05-12 06:15:49 +000011911void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011912 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011913
11914 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011915 if (MD->getParent()->isDependentType()) {
11916 MD->setDefaulted();
11917 MD->setExplicitlyDefaulted();
11918 return;
11919 }
11920
Sean Hunte4246a62011-05-12 06:15:49 +000011921 CXXSpecialMember Member = getSpecialMember(MD);
11922 if (Member == CXXInvalid) {
Eli Friedmanfcb5a252013-07-11 23:55:07 +000011923 if (!MD->isInvalidDecl())
11924 Diag(DefaultLoc, diag::err_default_special_members);
Sean Hunte4246a62011-05-12 06:15:49 +000011925 return;
11926 }
11927
11928 MD->setDefaulted();
11929 MD->setExplicitlyDefaulted();
11930
Sean Huntcd10dec2011-05-23 23:14:04 +000011931 // If this definition appears within the record, do the checking when
11932 // the record is complete.
11933 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011934 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011935 // Find the uninstantiated declaration that actually had the '= default'
11936 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011937 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011938
Richard Smith12fef492013-03-27 00:22:47 +000011939 // If the method was defaulted on its first declaration, we will have
11940 // already performed the checking in CheckCompletedCXXClass. Such a
11941 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011942 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011943 return;
11944
Richard Smithb9d0b762012-07-27 04:22:15 +000011945 CheckExplicitlyDefaultedSpecialMember(MD);
11946
Richard Smith1d28caf2012-12-11 01:14:52 +000011947 // The exception specification is needed because we are defining the
11948 // function.
11949 ResolveExceptionSpec(DefaultLoc,
11950 MD->getType()->castAs<FunctionProtoType>());
11951
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011952 if (MD->isInvalidDecl())
11953 return;
11954
Sean Hunte4246a62011-05-12 06:15:49 +000011955 switch (Member) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011956 case CXXDefaultConstructor:
11957 DefineImplicitDefaultConstructor(DefaultLoc,
11958 cast<CXXConstructorDecl>(MD));
Sean Hunt49634cf2011-05-13 06:10:58 +000011959 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011960 case CXXCopyConstructor:
11961 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunte4246a62011-05-12 06:15:49 +000011962 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011963 case CXXCopyAssignment:
11964 DefineImplicitCopyAssignment(DefaultLoc, MD);
Sean Hunt2b188082011-05-14 05:23:28 +000011965 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011966 case CXXDestructor:
11967 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Sean Huntcb45a0f2011-05-12 22:46:25 +000011968 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011969 case CXXMoveConstructor:
11970 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunt82713172011-05-25 23:16:36 +000011971 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011972 case CXXMoveAssignment:
11973 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011974 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011975 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011976 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011977 }
11978 } else {
11979 Diag(DefaultLoc, diag::err_default_special_members);
11980 }
11981}
11982
Sebastian Redl13e88542009-04-27 21:33:24 +000011983static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011984 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011985 Stmt *SubStmt = *CI;
11986 if (!SubStmt)
11987 continue;
11988 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011989 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011990 diag::err_return_in_constructor_handler);
11991 if (!isa<Expr>(SubStmt))
11992 SearchForReturnInStmt(Self, SubStmt);
11993 }
11994}
11995
11996void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11997 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11998 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11999 SearchForReturnInStmt(*this, Handler);
12000 }
12001}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012002
David Blaikie299adab2013-01-18 23:03:15 +000012003bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000012004 const CXXMethodDecl *Old) {
12005 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12006 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12007
12008 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12009
12010 // If the calling conventions match, everything is fine
12011 if (NewCC == OldCC)
12012 return false;
12013
Stephen Hines651f13c2014-04-23 16:59:28 -070012014 // If the calling conventions mismatch because the new function is static,
12015 // suppress the calling convention mismatch error; the error about static
12016 // function override (err_static_overrides_virtual from
12017 // Sema::CheckFunctionDeclaration) is more clear.
12018 if (New->getStorageClass() == SC_Static)
12019 return false;
12020
Reid Kleckneref072032013-08-27 23:08:25 +000012021 Diag(New->getLocation(),
12022 diag::err_conflicting_overriding_cc_attributes)
12023 << New->getDeclName() << New->getType() << Old->getType();
12024 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12025 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000012026}
12027
Mike Stump1eb44332009-09-09 15:08:12 +000012028bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012029 const CXXMethodDecl *Old) {
Stephen Hines651f13c2014-04-23 16:59:28 -070012030 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12031 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012032
Chandler Carruth73857792010-02-15 11:53:20 +000012033 if (Context.hasSameType(NewTy, OldTy) ||
12034 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012035 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000012036
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012037 // Check if the return types are covariant
12038 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000012039
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012040 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012041 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12042 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012043 NewClassTy = NewPT->getPointeeType();
12044 OldClassTy = OldPT->getPointeeType();
12045 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012046 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12047 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12048 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12049 NewClassTy = NewRT->getPointeeType();
12050 OldClassTy = OldRT->getPointeeType();
12051 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012052 }
12053 }
Mike Stump1eb44332009-09-09 15:08:12 +000012054
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012055 // The return types aren't either both pointers or references to a class type.
12056 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000012057 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012058 diag::err_different_return_type_for_overriding_virtual_function)
12059 << New->getDeclName() << NewTy << OldTy;
12060 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000012061
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012062 return true;
12063 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012064
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012065 // C++ [class.virtual]p6:
12066 // If the return type of D::f differs from the return type of B::f, the
12067 // class type in the return type of D::f shall be complete at the point of
12068 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000012069 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12070 if (!RT->isBeingDefined() &&
12071 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000012072 diag::err_covariant_return_incomplete,
12073 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012074 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000012075 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012076
Douglas Gregora4923eb2009-11-16 21:35:15 +000012077 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012078 // Check if the new class derives from the old class.
12079 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12080 Diag(New->getLocation(),
12081 diag::err_covariant_return_not_derived)
12082 << New->getDeclName() << NewTy << OldTy;
12083 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12084 return true;
12085 }
Mike Stump1eb44332009-09-09 15:08:12 +000012086
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012087 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000012088 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000012089 diag::err_covariant_return_inaccessible_base,
12090 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12091 // FIXME: Should this point to the return type?
12092 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000012093 // FIXME: this note won't trigger for delayed access control
12094 // diagnostics, and it's impossible to get an undelayed error
12095 // here from access control during the original parse because
12096 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012097 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12098 return true;
12099 }
12100 }
Mike Stump1eb44332009-09-09 15:08:12 +000012101
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012102 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012103 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012104 Diag(New->getLocation(),
12105 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012106 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012107 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12108 return true;
12109 };
Mike Stump1eb44332009-09-09 15:08:12 +000012110
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012111
12112 // The new class type must have the same or less qualifiers as the old type.
12113 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12114 Diag(New->getLocation(),
12115 diag::err_covariant_return_type_class_type_more_qualified)
12116 << New->getDeclName() << NewTy << OldTy;
12117 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12118 return true;
12119 };
Mike Stump1eb44332009-09-09 15:08:12 +000012120
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012121 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012122}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012123
Douglas Gregor4ba31362009-12-01 17:24:26 +000012124/// \brief Mark the given method pure.
12125///
12126/// \param Method the method to be marked pure.
12127///
12128/// \param InitRange the source range that covers the "0" initializer.
12129bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000012130 SourceLocation EndLoc = InitRange.getEnd();
12131 if (EndLoc.isValid())
12132 Method->setRangeEnd(EndLoc);
12133
Douglas Gregor4ba31362009-12-01 17:24:26 +000012134 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12135 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000012136 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000012137 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000012138
12139 if (!Method->isInvalidDecl())
12140 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12141 << Method->getDeclName() << InitRange;
12142 return true;
12143}
12144
Douglas Gregor552e2992012-02-21 02:22:07 +000012145/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012146static bool isStaticDataMember(const Decl *D) {
12147 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12148 return Var->isStaticDataMember();
12149
12150 return false;
Douglas Gregor552e2992012-02-21 02:22:07 +000012151}
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012152
John McCall731ad842009-12-19 09:28:58 +000012153/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12154/// an initializer for the out-of-line declaration 'Dcl'. The scope
12155/// is a fresh scope pushed for just this purpose.
12156///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012157/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12158/// static data member of class X, names should be looked up in the scope of
12159/// class X.
John McCalld226f652010-08-21 09:40:31 +000012160void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012161 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000012162 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012163
Stephen Hines651f13c2014-04-23 16:59:28 -070012164 // We will always have a nested name specifier here, but this declaration
12165 // might not be out of line if the specifier names the current namespace:
12166 // extern int n;
12167 // int ::n = 0;
12168 if (D->isOutOfLine())
12169 EnterDeclaratorContext(S, D->getDeclContext());
12170
Douglas Gregor552e2992012-02-21 02:22:07 +000012171 // If we are parsing the initializer for a static data member, push a
12172 // new expression evaluation context that is associated with this static
12173 // data member.
12174 if (isStaticDataMember(D))
12175 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012176}
12177
12178/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000012179/// initializer for the out-of-line declaration 'D'.
12180void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012181 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000012182 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012183
Douglas Gregor552e2992012-02-21 02:22:07 +000012184 if (isStaticDataMember(D))
Stephen Hines651f13c2014-04-23 16:59:28 -070012185 PopExpressionEvaluationContext();
Douglas Gregor552e2992012-02-21 02:22:07 +000012186
Stephen Hines651f13c2014-04-23 16:59:28 -070012187 if (D->isOutOfLine())
12188 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012189}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012190
12191/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12192/// C++ if/switch/while/for statement.
12193/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000012194DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012195 // C++ 6.4p2:
12196 // The declarator shall not specify a function or an array.
12197 // The type-specifier-seq shall not contain typedef and shall not declare a
12198 // new class or enumeration.
12199 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12200 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012201
12202 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000012203 if (!Dcl)
12204 return true;
12205
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012206 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12207 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012208 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000012209 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012210 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012211
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012212 return Dcl;
12213}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012214
Douglas Gregordfe65432011-07-28 19:11:31 +000012215void Sema::LoadExternalVTableUses() {
12216 if (!ExternalSource)
12217 return;
12218
12219 SmallVector<ExternalVTableUse, 4> VTables;
12220 ExternalSource->ReadUsedVTables(VTables);
12221 SmallVector<VTableUse, 4> NewUses;
12222 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12223 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12224 = VTablesUsed.find(VTables[I].Record);
12225 // Even if a definition wasn't required before, it may be required now.
12226 if (Pos != VTablesUsed.end()) {
12227 if (!Pos->second && VTables[I].DefinitionRequired)
12228 Pos->second = true;
12229 continue;
12230 }
12231
12232 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12233 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12234 }
12235
12236 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12237}
12238
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012239void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12240 bool DefinitionRequired) {
12241 // Ignore any vtable uses in unevaluated operands or for classes that do
12242 // not have a vtable.
12243 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000012244 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000012245 return;
12246
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012247 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000012248 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012249 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12250 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12251 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12252 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000012253 // If we already had an entry, check to see if we are promoting this vtable
12254 // to required a definition. If so, we need to reappend to the VTableUses
12255 // list, since we may have already processed the first entry.
12256 if (DefinitionRequired && !Pos.first->second) {
12257 Pos.first->second = true;
12258 } else {
12259 // Otherwise, we can early exit.
12260 return;
12261 }
Stephen Hines651f13c2014-04-23 16:59:28 -070012262 } else {
12263 // The Microsoft ABI requires that we perform the destructor body
12264 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12265 // the deleting destructor is emitted with the vtable, not with the
12266 // destructor definition as in the Itanium ABI.
12267 // If it has a definition, we do the check at that point instead.
12268 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12269 Class->hasUserDeclaredDestructor() &&
12270 !Class->getDestructor()->isDefined() &&
12271 !Class->getDestructor()->isDeleted()) {
12272 CheckDestructor(Class->getDestructor());
12273 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012274 }
12275
12276 // Local classes need to have their virtual members marked
12277 // immediately. For all other classes, we mark their virtual members
12278 // at the end of the translation unit.
12279 if (Class->isLocalClass())
12280 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000012281 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012282 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000012283}
12284
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012285bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000012286 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012287 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000012288 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000012289
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012290 // Note: The VTableUses vector could grow as a result of marking
12291 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000012292 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012293 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000012294 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012295 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000012296 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012297 if (!Class)
12298 continue;
12299
12300 SourceLocation Loc = VTableUses[I].second;
12301
Richard Smithb9d0b762012-07-27 04:22:15 +000012302 bool DefineVTable = true;
12303
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012304 // If this class has a key function, but that key function is
12305 // defined in another translation unit, we don't need to emit the
12306 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000012307 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000012308 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolafc218132013-08-26 23:23:21 +000012309 // The key function is in another translation unit.
12310 DefineVTable = false;
12311 TemplateSpecializationKind TSK =
12312 KeyFunction->getTemplateSpecializationKind();
12313 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12314 TSK != TSK_ImplicitInstantiation &&
12315 "Instantiations don't have key functions");
12316 (void)TSK;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012317 } else if (!KeyFunction) {
12318 // If we have a class with no key function that is the subject
12319 // of an explicit instantiation declaration, suppress the
12320 // vtable; it will live with the explicit instantiation
12321 // definition.
12322 bool IsExplicitInstantiationDeclaration
12323 = Class->getTemplateSpecializationKind()
12324 == TSK_ExplicitInstantiationDeclaration;
Stephen Hines651f13c2014-04-23 16:59:28 -070012325 for (auto R : Class->redecls()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012326 TemplateSpecializationKind TSK
Stephen Hines651f13c2014-04-23 16:59:28 -070012327 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012328 if (TSK == TSK_ExplicitInstantiationDeclaration)
12329 IsExplicitInstantiationDeclaration = true;
12330 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12331 IsExplicitInstantiationDeclaration = false;
12332 break;
12333 }
12334 }
12335
12336 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000012337 DefineVTable = false;
12338 }
12339
12340 // The exception specifications for all virtual members may be needed even
12341 // if we are not providing an authoritative form of the vtable in this TU.
12342 // We may choose to emit it available_externally anyway.
12343 if (!DefineVTable) {
12344 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12345 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012346 }
12347
12348 // Mark all of the virtual members of this class as referenced, so
12349 // that we can build a vtable. Then, tell the AST consumer that a
12350 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000012351 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012352 MarkVirtualMembersReferenced(Loc, Class);
12353 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12354 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12355
12356 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000012357 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012358 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000012359 const FunctionDecl *KeyFunctionDef = 0;
12360 if (!KeyFunction ||
12361 (KeyFunction->hasBody(KeyFunctionDef) &&
12362 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000012363 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12364 TSK_ExplicitInstantiationDefinition
12365 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12366 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012367 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012368 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012369 VTableUses.clear();
12370
Douglas Gregor78844032011-04-22 22:25:37 +000012371 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012372}
Anders Carlssond6a637f2009-12-07 08:24:59 +000012373
Richard Smithb9d0b762012-07-27 04:22:15 +000012374void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12375 const CXXRecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -070012376 for (const auto *I : RD->methods())
12377 if (I->isVirtual() && !I->isPure())
12378 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithb9d0b762012-07-27 04:22:15 +000012379}
12380
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012381void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12382 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000012383 // Mark all functions which will appear in RD's vtable as used.
12384 CXXFinalOverriderMap FinalOverriders;
12385 RD->getFinalOverriders(FinalOverriders);
12386 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12387 E = FinalOverriders.end();
12388 I != E; ++I) {
12389 for (OverridingMethods::const_iterator OI = I->second.begin(),
12390 OE = I->second.end();
12391 OI != OE; ++OI) {
12392 assert(OI->second.size() > 0 && "no final overrider");
12393 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000012394
Richard Smithff817f72012-07-07 06:59:51 +000012395 // C++ [basic.def.odr]p2:
12396 // [...] A virtual member function is used if it is not pure. [...]
12397 if (!Overrider->isPure())
12398 MarkFunctionReferenced(Loc, Overrider);
12399 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012400 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012401
12402 // Only classes that have virtual bases need a VTT.
12403 if (RD->getNumVBases() == 0)
12404 return;
12405
Stephen Hines651f13c2014-04-23 16:59:28 -070012406 for (const auto &I : RD->bases()) {
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012407 const CXXRecordDecl *Base =
Stephen Hines651f13c2014-04-23 16:59:28 -070012408 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012409 if (Base->getNumVBases() == 0)
12410 continue;
12411 MarkVirtualMembersReferenced(Loc, Base);
12412 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012413}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012414
12415/// SetIvarInitializers - This routine builds initialization ASTs for the
12416/// Objective-C implementation whose ivars need be initialized.
12417void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012418 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012419 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000012420 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000012421 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012422 CollectIvarsToConstructOrDestruct(OID, ivars);
12423 if (ivars.empty())
12424 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000012425 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012426 for (unsigned i = 0; i < ivars.size(); i++) {
12427 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012428 if (Field->isInvalidDecl())
12429 continue;
12430
Sean Huntcbb67482011-01-08 20:30:50 +000012431 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012432 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12433 InitializationKind InitKind =
12434 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000012435
12436 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12437 ExprResult MemberInit =
12438 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000012439 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012440 // Note, MemberInit could actually come back empty if no initialization
12441 // is required (e.g., because it would call a trivial default constructor)
12442 if (!MemberInit.get() || MemberInit.isInvalid())
12443 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000012444
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012445 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000012446 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12447 SourceLocation(),
12448 MemberInit.takeAs<Expr>(),
12449 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012450 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012451
12452 // Be sure that the destructor is accessible and is marked as referenced.
12453 if (const RecordType *RecordTy
12454 = Context.getBaseElementType(Field->getType())
12455 ->getAs<RecordType>()) {
12456 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012457 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012458 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012459 CheckDestructorAccess(Field->getLocation(), Destructor,
12460 PDiag(diag::err_access_dtor_ivar)
12461 << Context.getBaseElementType(Field->getType()));
12462 }
12463 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012464 }
12465 ObjCImplementation->setIvarInitializers(Context,
12466 AllToInit.data(), AllToInit.size());
12467 }
12468}
Sean Huntfe57eef2011-05-04 05:57:24 +000012469
Sean Huntebcbe1d2011-05-04 23:29:54 +000012470static
12471void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12472 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12473 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12474 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12475 Sema &S) {
Sean Huntebcbe1d2011-05-04 23:29:54 +000012476 if (Ctor->isInvalidDecl())
12477 return;
12478
Richard Smitha8eaf002012-08-23 06:16:52 +000012479 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12480
12481 // Target may not be determinable yet, for instance if this is a dependent
12482 // call in an uninstantiated template.
12483 if (Target) {
12484 const FunctionDecl *FNTarget = 0;
12485 (void)Target->hasBody(FNTarget);
12486 Target = const_cast<CXXConstructorDecl*>(
12487 cast_or_null<CXXConstructorDecl>(FNTarget));
12488 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012489
12490 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12491 // Avoid dereferencing a null pointer here.
12492 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12493
12494 if (!Current.insert(Canonical))
12495 return;
12496
12497 // We know that beyond here, we aren't chaining into a cycle.
12498 if (!Target || !Target->isDelegatingConstructor() ||
12499 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012500 Valid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012501 Current.clear();
12502 // We've hit a cycle.
12503 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12504 Current.count(TCanonical)) {
12505 // If we haven't diagnosed this cycle yet, do so now.
12506 if (!Invalid.count(TCanonical)) {
12507 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012508 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012509 << Ctor;
12510
Richard Smitha8eaf002012-08-23 06:16:52 +000012511 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012512 if (TCanonical != Canonical)
12513 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12514
12515 CXXConstructorDecl *C = Target;
12516 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012517 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012518 (void)C->getTargetConstructor()->hasBody(FNTarget);
12519 assert(FNTarget && "Ctor cycle through bodiless function");
12520
Richard Smitha8eaf002012-08-23 06:16:52 +000012521 C = const_cast<CXXConstructorDecl*>(
12522 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012523 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12524 }
12525 }
12526
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012527 Invalid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012528 Current.clear();
12529 } else {
12530 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12531 }
12532}
12533
12534
Sean Huntfe57eef2011-05-04 05:57:24 +000012535void Sema::CheckDelegatingCtorCycles() {
12536 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12537
Douglas Gregor0129b562011-07-27 21:57:17 +000012538 for (DelegatingCtorDeclsType::iterator
12539 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012540 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012541 I != E; ++I)
12542 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012543
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012544 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12545 CE = Invalid.end();
12546 CI != CE; ++CI)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012547 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012548}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012549
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012550namespace {
12551 /// \brief AST visitor that finds references to the 'this' expression.
12552 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12553 Sema &S;
12554
12555 public:
12556 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12557
12558 bool VisitCXXThisExpr(CXXThisExpr *E) {
12559 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12560 << E->isImplicit();
12561 return false;
12562 }
12563 };
12564}
12565
12566bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12567 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12568 if (!TSInfo)
12569 return false;
12570
12571 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012572 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012573 if (!ProtoTL)
12574 return false;
12575
12576 // C++11 [expr.prim.general]p3:
12577 // [The expression this] shall not appear before the optional
12578 // cv-qualifier-seq and it shall not appear within the declaration of a
12579 // static member function (although its type and value category are defined
12580 // within a static member function as they are within a non-static member
12581 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012582 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012583 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012584 FindCXXThisExpr Finder(*this);
12585
12586 // If the return type came after the cv-qualifier-seq, check it now.
12587 if (Proto->hasTrailingReturn() &&
Stephen Hines651f13c2014-04-23 16:59:28 -070012588 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012589 return true;
12590
12591 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012592 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12593 return true;
12594
12595 return checkThisInStaticMemberFunctionAttributes(Method);
12596}
12597
12598bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12599 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12600 if (!TSInfo)
12601 return false;
12602
12603 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012604 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012605 if (!ProtoTL)
12606 return false;
12607
David Blaikie39e6ab42013-02-18 22:06:02 +000012608 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012609 FindCXXThisExpr Finder(*this);
12610
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012611 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012612 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012613 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012614 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012615 case EST_DynamicNone:
12616 case EST_MSAny:
12617 case EST_None:
12618 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012619
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012620 case EST_ComputedNoexcept:
12621 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12622 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012623
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012624 case EST_Dynamic:
Stephen Hines651f13c2014-04-23 16:59:28 -070012625 for (const auto &E : Proto->exceptions()) {
12626 if (!Finder.TraverseType(E))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012627 return true;
12628 }
12629 break;
12630 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012631
12632 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012633}
12634
12635bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12636 FindCXXThisExpr Finder(*this);
12637
12638 // Check attributes.
Stephen Hines651f13c2014-04-23 16:59:28 -070012639 for (const auto *A : Method->attrs()) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012640 // FIXME: This should be emitted by tblgen.
12641 Expr *Arg = 0;
12642 ArrayRef<Expr *> Args;
Stephen Hines651f13c2014-04-23 16:59:28 -070012643 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012644 Arg = G->getArg();
Stephen Hines651f13c2014-04-23 16:59:28 -070012645 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012646 Arg = G->getArg();
Stephen Hines651f13c2014-04-23 16:59:28 -070012647 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012648 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070012649 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012650 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070012651 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012652 Arg = ETLF->getSuccessValue();
12653 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070012654 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012655 Arg = STLF->getSuccessValue();
12656 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070012657 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012658 Arg = LR->getArg();
Stephen Hines651f13c2014-04-23 16:59:28 -070012659 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012660 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070012661 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
12662 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
12663 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
12664 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12665 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12666 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12667 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
12668 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012669
12670 if (Arg && !Finder.TraverseStmt(Arg))
12671 return true;
12672
12673 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12674 if (!Finder.TraverseStmt(Args[I]))
12675 return true;
12676 }
12677 }
12678
12679 return false;
12680}
12681
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012682void
12683Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12684 ArrayRef<ParsedType> DynamicExceptions,
12685 ArrayRef<SourceRange> DynamicExceptionRanges,
12686 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012687 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012688 FunctionProtoType::ExtProtoInfo &EPI) {
12689 Exceptions.clear();
12690 EPI.ExceptionSpecType = EST;
12691 if (EST == EST_Dynamic) {
12692 Exceptions.reserve(DynamicExceptions.size());
12693 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12694 // FIXME: Preserve type source info.
12695 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12696
12697 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12698 collectUnexpandedParameterPacks(ET, Unexpanded);
12699 if (!Unexpanded.empty()) {
12700 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12701 UPPC_ExceptionType,
12702 Unexpanded);
12703 continue;
12704 }
12705
12706 // Check that the type is valid for an exception spec, and
12707 // drop it if not.
12708 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12709 Exceptions.push_back(ET);
12710 }
12711 EPI.NumExceptions = Exceptions.size();
12712 EPI.Exceptions = Exceptions.data();
12713 return;
12714 }
12715
12716 if (EST == EST_ComputedNoexcept) {
12717 // If an error occurred, there's no expression here.
12718 if (NoexceptExpr) {
12719 assert((NoexceptExpr->isTypeDependent() ||
12720 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12721 Context.BoolTy) &&
12722 "Parser should have made sure that the expression is boolean");
12723 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12724 EPI.ExceptionSpecType = EST_BasicNoexcept;
12725 return;
12726 }
12727
12728 if (!NoexceptExpr->isValueDependent())
12729 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012730 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012731 /*AllowFold*/ false).take();
12732 EPI.NoexceptExpr = NoexceptExpr;
12733 }
12734 return;
12735 }
12736}
12737
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012738/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12739Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12740 // Implicitly declared functions (e.g. copy constructors) are
12741 // __host__ __device__
12742 if (D->isImplicit())
12743 return CFT_HostDevice;
12744
12745 if (D->hasAttr<CUDAGlobalAttr>())
12746 return CFT_Global;
12747
12748 if (D->hasAttr<CUDADeviceAttr>()) {
12749 if (D->hasAttr<CUDAHostAttr>())
12750 return CFT_HostDevice;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012751 return CFT_Device;
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012752 }
12753
12754 return CFT_Host;
12755}
12756
12757bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12758 CUDAFunctionTarget CalleeTarget) {
12759 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12760 // Callable from the device only."
12761 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12762 return true;
12763
12764 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12765 // Callable from the host only."
12766 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12767 // Callable from the host only."
12768 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12769 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12770 return true;
12771
12772 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12773 return true;
12774
12775 return false;
12776}
John McCall76da55d2013-04-16 07:28:30 +000012777
12778/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12779///
12780MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12781 SourceLocation DeclStart,
12782 Declarator &D, Expr *BitWidth,
12783 InClassInitStyle InitStyle,
12784 AccessSpecifier AS,
12785 AttributeList *MSPropertyAttr) {
12786 IdentifierInfo *II = D.getIdentifier();
12787 if (!II) {
12788 Diag(DeclStart, diag::err_anonymous_property);
12789 return NULL;
12790 }
12791 SourceLocation Loc = D.getIdentifierLoc();
12792
12793 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12794 QualType T = TInfo->getType();
12795 if (getLangOpts().CPlusPlus) {
12796 CheckExtraCXXDefaultArguments(D);
12797
12798 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12799 UPPC_DataMemberType)) {
12800 D.setInvalidType();
12801 T = Context.IntTy;
12802 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12803 }
12804 }
12805
12806 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12807
12808 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12809 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12810 diag::err_invalid_thread)
12811 << DeclSpec::getSpecifierName(TSCS);
12812
12813 // Check to see if this name was declared as a member previously
12814 NamedDecl *PrevDecl = 0;
12815 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12816 LookupName(Previous, S);
12817 switch (Previous.getResultKind()) {
12818 case LookupResult::Found:
12819 case LookupResult::FoundUnresolvedValue:
12820 PrevDecl = Previous.getAsSingle<NamedDecl>();
12821 break;
12822
12823 case LookupResult::FoundOverloaded:
12824 PrevDecl = Previous.getRepresentativeDecl();
12825 break;
12826
12827 case LookupResult::NotFound:
12828 case LookupResult::NotFoundInCurrentInstantiation:
12829 case LookupResult::Ambiguous:
12830 break;
12831 }
12832
12833 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12834 // Maybe we will complain about the shadowed template parameter.
12835 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12836 // Just pretend that we didn't see the previous declaration.
12837 PrevDecl = 0;
12838 }
12839
12840 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12841 PrevDecl = 0;
12842
12843 SourceLocation TSSL = D.getLocStart();
John McCall76da55d2013-04-16 07:28:30 +000012844 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Stephen Hines651f13c2014-04-23 16:59:28 -070012845 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
12846 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall76da55d2013-04-16 07:28:30 +000012847 ProcessDeclAttributes(TUScope, NewPD, D);
12848 NewPD->setAccess(AS);
12849
12850 if (NewPD->isInvalidDecl())
12851 Record->setInvalidDecl();
12852
12853 if (D.getDeclSpec().isModulePrivateSpecified())
12854 NewPD->setModulePrivate();
12855
12856 if (NewPD->isInvalidDecl() && PrevDecl) {
12857 // Don't introduce NewFD into scope; there's already something
12858 // with the same name in the same scope.
12859 } else if (II) {
12860 PushOnScopeChains(NewPD, S);
12861 } else
12862 Record->addDecl(NewPD);
12863
12864 return NewPD;
12865}