blob: 4a008a0ed3c9f364cfe63f1cc7ea74c9ecd9d660 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000040#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000041#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000042
43using namespace clang;
44
Chris Lattner8123a952008-04-10 02:22:51 +000045//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
Chris Lattner9e979552008-04-12 23:52:44 +000049namespace {
50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51 /// the default argument of a parameter to determine whether it
52 /// contains any ill-formed subexpressions. For example, this will
53 /// diagnose the use of local variables or parameters within the
54 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000055 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000056 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000057 Expr *DefaultArg;
58 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 public:
Mike Stump1eb44332009-09-09 15:08:12 +000061 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000062 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000063
Chris Lattner9e979552008-04-12 23:52:44 +000064 bool VisitExpr(Expr *Node);
65 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000066 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000067 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000068 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000069 };
Chris Lattner8123a952008-04-10 02:22:51 +000070
Chris Lattner9e979552008-04-12 23:52:44 +000071 /// VisitExpr - Visit all of the children of this expression.
72 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
73 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000074 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000075 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000076 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000077 }
78
Chris Lattner9e979552008-04-12 23:52:44 +000079 /// VisitDeclRefExpr - Visit a reference to a declaration, to
80 /// determine whether this declaration can be used in the default
81 /// argument expression.
82 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000083 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000084 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
85 // C++ [dcl.fct.default]p9
86 // Default arguments are evaluated each time the function is
87 // called. The order of evaluation of function arguments is
88 // unspecified. Consequently, parameters of a function shall not
89 // be used in default argument expressions, even if they are not
90 // evaluated. Parameters of a function declared before a default
91 // argument expression are in scope and can hide namespace and
92 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000093 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000094 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000095 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000096 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000097 // C++ [dcl.fct.default]p7
98 // Local variables shall not be used in default argument
99 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000100 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000101 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000102 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000103 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000104 }
Chris Lattner8123a952008-04-10 02:22:51 +0000105
Douglas Gregor3996f232008-11-04 13:41:56 +0000106 return false;
107 }
Chris Lattner9e979552008-04-12 23:52:44 +0000108
Douglas Gregor796da182008-11-04 14:32:21 +0000109 /// VisitCXXThisExpr - Visit a C++ "this" expression.
110 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
111 // C++ [dcl.fct.default]p8:
112 // The keyword this shall not be used in a default argument of a
113 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000114 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000115 diag::err_param_default_argument_references_this)
116 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000117 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000118
John McCall045d2522013-04-09 01:56:28 +0000119 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
120 bool Invalid = false;
121 for (PseudoObjectExpr::semantics_iterator
122 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
123 Expr *E = *i;
124
125 // Look through bindings.
126 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
127 E = OVE->getSourceExpr();
128 assert(E && "pseudo-object binding without source expression?");
129 }
130
131 Invalid |= Visit(E);
132 }
133 return Invalid;
134 }
135
Douglas Gregorf0459f82012-02-10 23:30:22 +0000136 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
137 // C++11 [expr.lambda.prim]p13:
138 // A lambda-expression appearing in a default argument shall not
139 // implicitly or explicitly capture any entity.
140 if (Lambda->capture_begin() == Lambda->capture_end())
141 return false;
142
143 return S->Diag(Lambda->getLocStart(),
144 diag::err_lambda_capture_default_arg);
145 }
Chris Lattner8123a952008-04-10 02:22:51 +0000146}
147
Richard Smith0b0ca472013-04-10 06:11:48 +0000148void
149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
150 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000151 // If we have an MSAny spec already, don't bother.
152 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000153 return;
154
155 const FunctionProtoType *Proto
156 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000157 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
158 if (!Proto)
159 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000160
161 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
162
163 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000164 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000165 ClearExceptions();
166 ComputedEST = EST;
167 return;
168 }
169
Richard Smith7a614d82011-06-11 17:19:42 +0000170 // FIXME: If the call to this decl is using any of its default arguments, we
171 // need to search them for potentially-throwing calls.
172
Sean Hunt001cad92011-05-10 00:49:42 +0000173 // If this function has a basic noexcept, it doesn't affect the outcome.
174 if (EST == EST_BasicNoexcept)
175 return;
176
177 // If we have a throw-all spec at this point, ignore the function.
178 if (ComputedEST == EST_None)
179 return;
180
181 // If we're still at noexcept(true) and there's a nothrow() callee,
182 // change to that specification.
183 if (EST == EST_DynamicNone) {
184 if (ComputedEST == EST_BasicNoexcept)
185 ComputedEST = EST_DynamicNone;
186 return;
187 }
188
189 // Check out noexcept specs.
190 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000191 FunctionProtoType::NoexceptResult NR =
192 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000193 assert(NR != FunctionProtoType::NR_NoNoexcept &&
194 "Must have noexcept result for EST_ComputedNoexcept.");
195 assert(NR != FunctionProtoType::NR_Dependent &&
196 "Should not generate implicit declarations for dependent cases, "
197 "and don't know how to handle them anyway.");
198
199 // noexcept(false) -> no spec on the new function
200 if (NR == FunctionProtoType::NR_Throw) {
201 ClearExceptions();
202 ComputedEST = EST_None;
203 }
204 // noexcept(true) won't change anything either.
205 return;
206 }
207
208 assert(EST == EST_Dynamic && "EST case not considered earlier.");
209 assert(ComputedEST != EST_None &&
210 "Shouldn't collect exceptions when throw-all is guaranteed.");
211 ComputedEST = EST_Dynamic;
212 // Record the exceptions in this function's exception specification.
213 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
214 EEnd = Proto->exception_end();
215 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000217 Exceptions.push_back(*E);
218}
219
Richard Smith7a614d82011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithe6975e92012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssoned961f92009-08-25 02:29:20 +0000249bool
John McCall9ae2f072010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000271 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000273
Richard Smith6c3af3d2013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Anders Carlssoned961f92009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson9351c172009-08-25 03:18:48 +0000292 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000293}
294
Chris Lattner8123a952008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000298void
John McCalld226f652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000302 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCalld226f652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner3d1cee32008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6f526752010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlsson66e30672009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
John McCall9ae2f072010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000329}
330
Douglas Gregor61366e92008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCalld226f652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param)
343 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Anders Carlsson5e300d12009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000346}
347
Douglas Gregor72b505b2008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCalld226f652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Anders Carlsson5e300d12009-06-12 16:51:40 +0000356 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Anders Carlsson5e300d12009-06-12 16:51:40 +0000358 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000359}
360
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000361/// CheckExtraCXXDefaultArguments - Check for any extra default
362/// arguments in the declarator, which is not a function declaration
363/// or definition and therefore is not permitted to have default
364/// arguments. This routine should be invoked for every declarator
365/// that is not a function declaration or definition.
366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367 // C++ [dcl.fct.default]p3
368 // A default argument expression shall be specified only in the
369 // parameter-declaration-clause of a function declaration or in a
370 // template-parameter (14.1). It shall not be specified for a
371 // parameter pack. If it is specified in a
372 // parameter-declaration-clause, it shall not occur within a
373 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000374 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000376 DeclaratorChunk &chunk = D.getTypeObject(i);
377 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000378 if (MightBeFunction) {
379 // This is a function declaration. It can have default arguments, but
380 // keep looking in case its return type is a function type with default
381 // arguments.
382 MightBeFunction = false;
383 continue;
384 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000385 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
386 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000387 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000388 if (Param->hasUnparsedDefaultArg()) {
389 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000391 << SourceRange((*Toks)[1].getLocation(),
392 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000393 delete Toks;
394 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000395 } else if (Param->getDefaultArg()) {
396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397 << Param->getDefaultArg()->getSourceRange();
398 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000399 }
400 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000401 } else if (chunk.Kind != DeclaratorChunk::Paren) {
402 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000403 }
404 }
405}
406
David Majnemerf6a144f2013-06-25 23:09:30 +0000407static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
408 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
409 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
410 if (!PVD->hasDefaultArg())
411 return false;
412 if (!PVD->hasInheritedDefaultArg())
413 return true;
414 }
415 return false;
416}
417
Craig Topper1a6eac82012-09-21 04:33:26 +0000418/// MergeCXXFunctionDecl - Merge two declarations of the same C++
419/// function, once we already know that they have the same
420/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
421/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000422bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
423 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000424 bool Invalid = false;
425
Chris Lattner3d1cee32008-04-08 05:04:30 +0000426 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000427 // For non-template functions, default arguments can be added in
428 // later declarations of a function in the same
429 // scope. Declarations in different scopes have completely
430 // distinct sets of default arguments. That is, declarations in
431 // inner scopes do not acquire default arguments from
432 // declarations in outer scopes, and vice versa. In a given
433 // function declaration, all parameters subsequent to a
434 // parameter with a default argument shall have default
435 // arguments supplied in this or previous declarations. A
436 // default argument shall not be redefined by a later
437 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000438 //
439 // C++ [dcl.fct.default]p6:
440 // Except for member functions of class templates, the default arguments
441 // in a member function definition that appears outside of the class
442 // definition are added to the set of default arguments provided by the
443 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000444 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
445 ParmVarDecl *OldParam = Old->getParamDecl(p);
446 ParmVarDecl *NewParam = New->getParamDecl(p);
447
James Molloy9cda03f2012-03-13 08:55:35 +0000448 bool OldParamHasDfl = OldParam->hasDefaultArg();
449 bool NewParamHasDfl = NewParam->hasDefaultArg();
450
451 NamedDecl *ND = Old;
452 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
453 // Ignore default parameters of old decl if they are not in
454 // the same scope.
455 OldParamHasDfl = false;
456
457 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000458
Francois Pichet8d051e02011-04-10 03:03:52 +0000459 unsigned DiagDefaultParamID =
460 diag::err_param_default_argument_redefinition;
461
462 // MSVC accepts that default parameters be redefined for member functions
463 // of template class. The new default parameter's value is ignored.
464 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000465 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000466 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
467 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000468 // Merge the old default argument into the new parameter.
469 NewParam->setHasInheritedDefaultArg();
470 if (OldParam->hasUninstantiatedDefaultArg())
471 NewParam->setUninstantiatedDefaultArg(
472 OldParam->getUninstantiatedDefaultArg());
473 else
474 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000475 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000476 Invalid = false;
477 }
478 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000479
Francois Pichet8cf90492011-04-10 04:58:30 +0000480 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
481 // hint here. Alternatively, we could walk the type-source information
482 // for NewParam to find the last source location in the type... but it
483 // isn't worth the effort right now. This is the kind of test case that
484 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000485 // int f(int);
486 // void g(int (*fp)(int) = f);
487 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000488 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000489 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000490
491 // Look for the function declaration where the default argument was
492 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000493 for (FunctionDecl *Older = Old->getPreviousDecl();
494 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000495 if (!Older->getParamDecl(p)->hasDefaultArg())
496 break;
497
498 OldParam = Older->getParamDecl(p);
499 }
500
501 Diag(OldParam->getLocation(), diag::note_previous_definition)
502 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000503 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000504 // Merge the old default argument into the new parameter.
505 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000506 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000507 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000508 if (OldParam->hasUninstantiatedDefaultArg())
509 NewParam->setUninstantiatedDefaultArg(
510 OldParam->getUninstantiatedDefaultArg());
511 else
John McCall3d6c1782010-05-04 01:53:42 +0000512 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000513 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000514 if (New->getDescribedFunctionTemplate()) {
515 // Paragraph 4, quoted above, only applies to non-template functions.
516 Diag(NewParam->getLocation(),
517 diag::err_param_default_argument_template_redecl)
518 << NewParam->getDefaultArgRange();
519 Diag(Old->getLocation(), diag::note_template_prev_declaration)
520 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000521 } else if (New->getTemplateSpecializationKind()
522 != TSK_ImplicitInstantiation &&
523 New->getTemplateSpecializationKind() != TSK_Undeclared) {
524 // C++ [temp.expr.spec]p21:
525 // Default function arguments shall not be specified in a declaration
526 // or a definition for one of the following explicit specializations:
527 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000528 // - the explicit specialization of a member function template;
529 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000530 // template where the class template specialization to which the
531 // member function specialization belongs is implicitly
532 // instantiated.
533 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
534 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
535 << New->getDeclName()
536 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000537 } else if (New->getDeclContext()->isDependentContext()) {
538 // C++ [dcl.fct.default]p6 (DR217):
539 // Default arguments for a member function of a class template shall
540 // be specified on the initial declaration of the member function
541 // within the class template.
542 //
543 // Reading the tea leaves a bit in DR217 and its reference to DR205
544 // leads me to the conclusion that one cannot add default function
545 // arguments for an out-of-line definition of a member function of a
546 // dependent type.
547 int WhichKind = 2;
548 if (CXXRecordDecl *Record
549 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
550 if (Record->getDescribedClassTemplate())
551 WhichKind = 0;
552 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
553 WhichKind = 1;
554 else
555 WhichKind = 2;
556 }
557
558 Diag(NewParam->getLocation(),
559 diag::err_param_default_argument_member_template_redecl)
560 << WhichKind
561 << NewParam->getDefaultArgRange();
562 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000563 }
564 }
565
Richard Smithb8abff62012-11-28 03:45:24 +0000566 // DR1344: If a default argument is added outside a class definition and that
567 // default argument makes the function a special member function, the program
568 // is ill-formed. This can only happen for constructors.
569 if (isa<CXXConstructorDecl>(New) &&
570 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
571 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
572 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
573 if (NewSM != OldSM) {
574 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
575 assert(NewParam->hasDefaultArg());
576 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
577 << NewParam->getDefaultArgRange() << NewSM;
578 Diag(Old->getLocation(), diag::note_previous_declaration);
579 }
580 }
581
Richard Smithff234882012-02-20 23:28:05 +0000582 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000583 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000584 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000585 if (New->isConstexpr() != Old->isConstexpr()) {
586 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
587 << New << New->isConstexpr();
588 Diag(Old->getLocation(), diag::note_previous_declaration);
589 Invalid = true;
590 }
591
David Majnemerf6a144f2013-06-25 23:09:30 +0000592 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
593 // argument expression, that declaration shall be a definition and shall be
594 // the only declaration of the function or function template in the
595 // translation unit.
596 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
597 functionDeclHasDefaultArgument(Old)) {
598 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
599 Diag(Old->getLocation(), diag::note_previous_declaration);
600 Invalid = true;
601 }
602
Douglas Gregore13ad832010-02-12 07:32:17 +0000603 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000604 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000605
Douglas Gregorcda9c672009-02-16 17:45:42 +0000606 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000607}
608
Sebastian Redl60618fa2011-03-12 11:50:43 +0000609/// \brief Merge the exception specifications of two variable declarations.
610///
611/// This is called when there's a redeclaration of a VarDecl. The function
612/// checks if the redeclaration might have an exception specification and
613/// validates compatibility and merges the specs if necessary.
614void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
615 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000616 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000617 return;
618
619 assert(Context.hasSameType(New->getType(), Old->getType()) &&
620 "Should only be called if types are otherwise the same.");
621
622 QualType NewType = New->getType();
623 QualType OldType = Old->getType();
624
625 // We're only interested in pointers and references to functions, as well
626 // as pointers to member functions.
627 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
628 NewType = R->getPointeeType();
629 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
630 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
631 NewType = P->getPointeeType();
632 OldType = OldType->getAs<PointerType>()->getPointeeType();
633 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
634 NewType = M->getPointeeType();
635 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
636 }
637
638 if (!NewType->isFunctionProtoType())
639 return;
640
641 // There's lots of special cases for functions. For function pointers, system
642 // libraries are hopefully not as broken so that we don't need these
643 // workarounds.
644 if (CheckEquivalentExceptionSpec(
645 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
646 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
647 New->setInvalidDecl();
648 }
649}
650
Chris Lattner3d1cee32008-04-08 05:04:30 +0000651/// CheckCXXDefaultArguments - Verify that the default arguments for a
652/// function declaration are well-formed according to C++
653/// [dcl.fct.default].
654void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
655 unsigned NumParams = FD->getNumParams();
656 unsigned p;
657
658 // Find first parameter with a default argument
659 for (p = 0; p < NumParams; ++p) {
660 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000661 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000662 break;
663 }
664
665 // C++ [dcl.fct.default]p4:
666 // In a given function declaration, all parameters
667 // subsequent to a parameter with a default argument shall
668 // have default arguments supplied in this or previous
669 // declarations. A default argument shall not be redefined
670 // by a later declaration (not even to the same value).
671 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000672 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000673 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000674 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000675 if (Param->isInvalidDecl())
676 /* We already complained about this parameter. */;
677 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000678 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000679 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000680 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000681 else
Mike Stump1eb44332009-09-09 15:08:12 +0000682 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000683 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Chris Lattner3d1cee32008-04-08 05:04:30 +0000685 LastMissingDefaultArg = p;
686 }
687 }
688
689 if (LastMissingDefaultArg > 0) {
690 // Some default arguments were missing. Clear out all of the
691 // default arguments up to (and including) the last missing
692 // default argument, so that we leave the function parameters
693 // in a semantically valid state.
694 for (p = 0; p <= LastMissingDefaultArg; ++p) {
695 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000696 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000697 Param->setDefaultArg(0);
698 }
699 }
700 }
701}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000702
Richard Smith9f569cc2011-10-01 02:31:28 +0000703// CheckConstexprParameterTypes - Check whether a function's parameter types
704// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000705// diagnostic and return false.
706static bool CheckConstexprParameterTypes(Sema &SemaRef,
707 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000708 unsigned ArgIndex = 0;
709 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
710 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
711 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
712 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
713 SourceLocation ParamLoc = PD->getLocation();
714 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000715 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000716 diag::err_constexpr_non_literal_param,
717 ArgIndex+1, PD->getSourceRange(),
718 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000719 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000720 }
Joao Matos17d35c32012-08-31 22:18:20 +0000721 return true;
722}
723
724/// \brief Get diagnostic %select index for tag kind for
725/// record diagnostic message.
726/// WARNING: Indexes apply to particular diagnostics only!
727///
728/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000729static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000730 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000731 case TTK_Struct: return 0;
732 case TTK_Interface: return 1;
733 case TTK_Class: return 2;
734 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000735 }
Joao Matos17d35c32012-08-31 22:18:20 +0000736}
737
738// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
739// the requirements of a constexpr function definition or a constexpr
740// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000741// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000742//
Richard Smith86c3ae42012-02-13 03:54:03 +0000743// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
744bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000745 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
746 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000747 // C++11 [dcl.constexpr]p4:
748 // The definition of a constexpr constructor shall satisfy the following
749 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000750 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000751 const CXXRecordDecl *RD = MD->getParent();
752 if (RD->getNumVBases()) {
753 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
754 << isa<CXXConstructorDecl>(NewFD)
755 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
756 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
757 E = RD->vbases_end(); I != E; ++I)
758 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000759 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000760 return false;
761 }
Richard Smith35340502012-01-13 04:54:00 +0000762 }
763
764 if (!isa<CXXConstructorDecl>(NewFD)) {
765 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000766 // The definition of a constexpr function shall satisfy the following
767 // constraints:
768 // - it shall not be virtual;
769 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
770 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000771 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000772
Richard Smith86c3ae42012-02-13 03:54:03 +0000773 // If it's not obvious why this function is virtual, find an overridden
774 // function which uses the 'virtual' keyword.
775 const CXXMethodDecl *WrittenVirtual = Method;
776 while (!WrittenVirtual->isVirtualAsWritten())
777 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
778 if (WrittenVirtual != Method)
779 Diag(WrittenVirtual->getLocation(),
780 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000781 return false;
782 }
783
784 // - its return type shall be a literal type;
785 QualType RT = NewFD->getResultType();
786 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000787 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000788 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000789 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000790 }
791
Richard Smith35340502012-01-13 04:54:00 +0000792 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000793 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000794 return false;
795
Richard Smith9f569cc2011-10-01 02:31:28 +0000796 return true;
797}
798
799/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000800/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000801///
Richard Smitha10b9782013-04-22 15:31:51 +0000802/// \return true if the body is OK (maybe only as an extension), false if we
803/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000804static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000805 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
806 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000807 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
808 // contain only
809 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
810 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
811 switch ((*DclIt)->getKind()) {
812 case Decl::StaticAssert:
813 case Decl::Using:
814 case Decl::UsingShadow:
815 case Decl::UsingDirective:
816 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000817 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000818 // - static_assert-declarations
819 // - using-declarations,
820 // - using-directives,
821 continue;
822
823 case Decl::Typedef:
824 case Decl::TypeAlias: {
825 // - typedef declarations and alias-declarations that do not define
826 // classes or enumerations,
827 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
828 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
829 // Don't allow variably-modified types in constexpr functions.
830 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
831 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
832 << TL.getSourceRange() << TL.getType()
833 << isa<CXXConstructorDecl>(Dcl);
834 return false;
835 }
836 continue;
837 }
838
839 case Decl::Enum:
840 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000841 // C++1y allows types to be defined, not just declared.
842 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
843 SemaRef.Diag(DS->getLocStart(),
844 SemaRef.getLangOpts().CPlusPlus1y
845 ? diag::warn_cxx11_compat_constexpr_type_definition
846 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000847 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000848 continue;
849
Richard Smitha10b9782013-04-22 15:31:51 +0000850 case Decl::EnumConstant:
851 case Decl::IndirectField:
852 case Decl::ParmVar:
853 // These can only appear with other declarations which are banned in
854 // C++11 and permitted in C++1y, so ignore them.
855 continue;
856
857 case Decl::Var: {
858 // C++1y [dcl.constexpr]p3 allows anything except:
859 // a definition of a variable of non-literal type or of static or
860 // thread storage duration or for which no initialization is performed.
861 VarDecl *VD = cast<VarDecl>(*DclIt);
862 if (VD->isThisDeclarationADefinition()) {
863 if (VD->isStaticLocal()) {
864 SemaRef.Diag(VD->getLocation(),
865 diag::err_constexpr_local_var_static)
866 << isa<CXXConstructorDecl>(Dcl)
867 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
868 return false;
869 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000870 if (!VD->getType()->isDependentType() &&
871 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000872 VD->getLocation(), VD->getType(),
873 diag::err_constexpr_local_var_non_literal_type,
874 isa<CXXConstructorDecl>(Dcl)))
875 return false;
876 if (!VD->hasInit()) {
877 SemaRef.Diag(VD->getLocation(),
878 diag::err_constexpr_local_var_no_init)
879 << isa<CXXConstructorDecl>(Dcl);
880 return false;
881 }
882 }
883 SemaRef.Diag(VD->getLocation(),
884 SemaRef.getLangOpts().CPlusPlus1y
885 ? diag::warn_cxx11_compat_constexpr_local_var
886 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000887 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000888 continue;
889 }
890
891 case Decl::NamespaceAlias:
892 case Decl::Function:
893 // These are disallowed in C++11 and permitted in C++1y. Allow them
894 // everywhere as an extension.
895 if (!Cxx1yLoc.isValid())
896 Cxx1yLoc = DS->getLocStart();
897 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000898
899 default:
900 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
901 << isa<CXXConstructorDecl>(Dcl);
902 return false;
903 }
904 }
905
906 return true;
907}
908
909/// Check that the given field is initialized within a constexpr constructor.
910///
911/// \param Dcl The constexpr constructor being checked.
912/// \param Field The field being checked. This may be a member of an anonymous
913/// struct or union nested within the class being checked.
914/// \param Inits All declarations, including anonymous struct/union members and
915/// indirect members, for which any initialization was provided.
916/// \param Diagnosed Set to true if an error is produced.
917static void CheckConstexprCtorInitializer(Sema &SemaRef,
918 const FunctionDecl *Dcl,
919 FieldDecl *Field,
920 llvm::SmallSet<Decl*, 16> &Inits,
921 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000922 if (Field->isUnnamedBitfield())
923 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000924
925 if (Field->isAnonymousStructOrUnion() &&
926 Field->getType()->getAsCXXRecordDecl()->isEmpty())
927 return;
928
Richard Smith9f569cc2011-10-01 02:31:28 +0000929 if (!Inits.count(Field)) {
930 if (!Diagnosed) {
931 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
932 Diagnosed = true;
933 }
934 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
935 } else if (Field->isAnonymousStructOrUnion()) {
936 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
937 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
938 I != E; ++I)
939 // If an anonymous union contains an anonymous struct of which any member
940 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000941 if (!RD->isUnion() || Inits.count(*I))
942 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000943 }
944}
945
Richard Smitha10b9782013-04-22 15:31:51 +0000946/// Check the provided statement is allowed in a constexpr function
947/// definition.
948static bool
949CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
950 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
951 SourceLocation &Cxx1yLoc) {
952 // - its function-body shall be [...] a compound-statement that contains only
953 switch (S->getStmtClass()) {
954 case Stmt::NullStmtClass:
955 // - null statements,
956 return true;
957
958 case Stmt::DeclStmtClass:
959 // - static_assert-declarations
960 // - using-declarations,
961 // - using-directives,
962 // - typedef declarations and alias-declarations that do not define
963 // classes or enumerations,
964 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
965 return false;
966 return true;
967
968 case Stmt::ReturnStmtClass:
969 // - and exactly one return statement;
970 if (isa<CXXConstructorDecl>(Dcl)) {
971 // C++1y allows return statements in constexpr constructors.
972 if (!Cxx1yLoc.isValid())
973 Cxx1yLoc = S->getLocStart();
974 return true;
975 }
976
977 ReturnStmts.push_back(S->getLocStart());
978 return true;
979
980 case Stmt::CompoundStmtClass: {
981 // C++1y allows compound-statements.
982 if (!Cxx1yLoc.isValid())
983 Cxx1yLoc = S->getLocStart();
984
985 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
986 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
987 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
988 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
989 Cxx1yLoc))
990 return false;
991 }
992 return true;
993 }
994
995 case Stmt::AttributedStmtClass:
996 if (!Cxx1yLoc.isValid())
997 Cxx1yLoc = S->getLocStart();
998 return true;
999
1000 case Stmt::IfStmtClass: {
1001 // C++1y allows if-statements.
1002 if (!Cxx1yLoc.isValid())
1003 Cxx1yLoc = S->getLocStart();
1004
1005 IfStmt *If = cast<IfStmt>(S);
1006 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1007 Cxx1yLoc))
1008 return false;
1009 if (If->getElse() &&
1010 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1011 Cxx1yLoc))
1012 return false;
1013 return true;
1014 }
1015
1016 case Stmt::WhileStmtClass:
1017 case Stmt::DoStmtClass:
1018 case Stmt::ForStmtClass:
1019 case Stmt::CXXForRangeStmtClass:
1020 case Stmt::ContinueStmtClass:
1021 // C++1y allows all of these. We don't allow them as extensions in C++11,
1022 // because they don't make sense without variable mutation.
1023 if (!SemaRef.getLangOpts().CPlusPlus1y)
1024 break;
1025 if (!Cxx1yLoc.isValid())
1026 Cxx1yLoc = S->getLocStart();
1027 for (Stmt::child_range Children = S->children(); Children; ++Children)
1028 if (*Children &&
1029 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1030 Cxx1yLoc))
1031 return false;
1032 return true;
1033
1034 case Stmt::SwitchStmtClass:
1035 case Stmt::CaseStmtClass:
1036 case Stmt::DefaultStmtClass:
1037 case Stmt::BreakStmtClass:
1038 // C++1y allows switch-statements, and since they don't need variable
1039 // mutation, we can reasonably allow them in C++11 as an extension.
1040 if (!Cxx1yLoc.isValid())
1041 Cxx1yLoc = S->getLocStart();
1042 for (Stmt::child_range Children = S->children(); Children; ++Children)
1043 if (*Children &&
1044 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1045 Cxx1yLoc))
1046 return false;
1047 return true;
1048
1049 default:
1050 if (!isa<Expr>(S))
1051 break;
1052
1053 // C++1y allows expression-statements.
1054 if (!Cxx1yLoc.isValid())
1055 Cxx1yLoc = S->getLocStart();
1056 return true;
1057 }
1058
1059 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1060 << isa<CXXConstructorDecl>(Dcl);
1061 return false;
1062}
1063
Richard Smith9f569cc2011-10-01 02:31:28 +00001064/// Check the body for the given constexpr function declaration only contains
1065/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1066///
1067/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001068bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001069 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001070 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001071 // The definition of a constexpr function shall satisfy the following
1072 // constraints: [...]
1073 // - its function-body shall be = delete, = default, or a
1074 // compound-statement
1075 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001076 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001077 // In the definition of a constexpr constructor, [...]
1078 // - its function-body shall not be a function-try-block;
1079 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1080 << isa<CXXConstructorDecl>(Dcl);
1081 return false;
1082 }
1083
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001084 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001085
1086 // - its function-body shall be [...] a compound-statement that contains only
1087 // [... list of cases ...]
1088 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1089 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001090 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1091 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001092 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1093 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001094 }
1095
Richard Smitha10b9782013-04-22 15:31:51 +00001096 if (Cxx1yLoc.isValid())
1097 Diag(Cxx1yLoc,
1098 getLangOpts().CPlusPlus1y
1099 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1100 : diag::ext_constexpr_body_invalid_stmt)
1101 << isa<CXXConstructorDecl>(Dcl);
1102
Richard Smith9f569cc2011-10-01 02:31:28 +00001103 if (const CXXConstructorDecl *Constructor
1104 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1105 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001106 // DR1359:
1107 // - every non-variant non-static data member and base class sub-object
1108 // shall be initialized;
1109 // - if the class is a non-empty union, or for each non-empty anonymous
1110 // union member of a non-union class, exactly one non-static data member
1111 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001112 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001113 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001114 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1115 return false;
1116 }
Richard Smith6e433752011-10-10 16:38:04 +00001117 } else if (!Constructor->isDependentContext() &&
1118 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001119 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1120
1121 // Skip detailed checking if we have enough initializers, and we would
1122 // allow at most one initializer per member.
1123 bool AnyAnonStructUnionMembers = false;
1124 unsigned Fields = 0;
1125 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1126 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001127 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001128 AnyAnonStructUnionMembers = true;
1129 break;
1130 }
1131 }
1132 if (AnyAnonStructUnionMembers ||
1133 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1134 // Check initialization of non-static data members. Base classes are
1135 // always initialized so do not need to be checked. Dependent bases
1136 // might not have initializers in the member initializer list.
1137 llvm::SmallSet<Decl*, 16> Inits;
1138 for (CXXConstructorDecl::init_const_iterator
1139 I = Constructor->init_begin(), E = Constructor->init_end();
1140 I != E; ++I) {
1141 if (FieldDecl *FD = (*I)->getMember())
1142 Inits.insert(FD);
1143 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1144 Inits.insert(ID->chain_begin(), ID->chain_end());
1145 }
1146
1147 bool Diagnosed = false;
1148 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1149 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001150 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001151 if (Diagnosed)
1152 return false;
1153 }
1154 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001155 } else {
1156 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001157 // C++1y doesn't require constexpr functions to contain a 'return'
1158 // statement. We still do, unless the return type is void, because
1159 // otherwise if there's no return statement, the function cannot
1160 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001161 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001162 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001163 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1164 : diag::err_constexpr_body_no_return);
1165 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001166 }
1167 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001168 Diag(ReturnStmts.back(),
1169 getLangOpts().CPlusPlus1y
1170 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1171 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001172 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1173 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001174 }
1175 }
1176
Richard Smith5ba73e12012-02-04 00:33:54 +00001177 // C++11 [dcl.constexpr]p5:
1178 // if no function argument values exist such that the function invocation
1179 // substitution would produce a constant expression, the program is
1180 // ill-formed; no diagnostic required.
1181 // C++11 [dcl.constexpr]p3:
1182 // - every constructor call and implicit conversion used in initializing the
1183 // return value shall be one of those allowed in a constant expression.
1184 // C++11 [dcl.constexpr]p4:
1185 // - every constructor involved in initializing non-static data members and
1186 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001187 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001188 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001189 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001190 << isa<CXXConstructorDecl>(Dcl);
1191 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1192 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001193 // Don't return false here: we allow this for compatibility in
1194 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001195 }
1196
Richard Smith9f569cc2011-10-01 02:31:28 +00001197 return true;
1198}
1199
Douglas Gregorb48fe382008-10-31 09:07:45 +00001200/// isCurrentClassName - Determine whether the identifier II is the
1201/// name of the class type currently being defined. In the case of
1202/// nested classes, this will only return true if II is the name of
1203/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001204bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1205 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001206 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001207
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001208 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001209 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001210 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001211 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1212 } else
1213 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1214
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001215 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001216 return &II == CurDecl->getIdentifier();
1217 else
1218 return false;
1219}
1220
Douglas Gregor229d47a2012-11-10 07:24:09 +00001221/// \brief Determine whether the given class is a base class of the given
1222/// class, including looking at dependent bases.
1223static bool findCircularInheritance(const CXXRecordDecl *Class,
1224 const CXXRecordDecl *Current) {
1225 SmallVector<const CXXRecordDecl*, 8> Queue;
1226
1227 Class = Class->getCanonicalDecl();
1228 while (true) {
1229 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1230 E = Current->bases_end();
1231 I != E; ++I) {
1232 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1233 if (!Base)
1234 continue;
1235
1236 Base = Base->getDefinition();
1237 if (!Base)
1238 continue;
1239
1240 if (Base->getCanonicalDecl() == Class)
1241 return true;
1242
1243 Queue.push_back(Base);
1244 }
1245
1246 if (Queue.empty())
1247 return false;
1248
1249 Current = Queue.back();
1250 Queue.pop_back();
1251 }
1252
1253 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001254}
1255
Mike Stump1eb44332009-09-09 15:08:12 +00001256/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001257///
1258/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1259/// and returns NULL otherwise.
1260CXXBaseSpecifier *
1261Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1262 SourceRange SpecifierRange,
1263 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001264 TypeSourceInfo *TInfo,
1265 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001266 QualType BaseType = TInfo->getType();
1267
Douglas Gregor2943aed2009-03-03 04:44:36 +00001268 // C++ [class.union]p1:
1269 // A union shall not have base classes.
1270 if (Class->isUnion()) {
1271 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1272 << SpecifierRange;
1273 return 0;
1274 }
1275
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001276 if (EllipsisLoc.isValid() &&
1277 !TInfo->getType()->containsUnexpandedParameterPack()) {
1278 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1279 << TInfo->getTypeLoc().getSourceRange();
1280 EllipsisLoc = SourceLocation();
1281 }
Douglas Gregord777e282012-11-10 01:18:17 +00001282
1283 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1284
1285 if (BaseType->isDependentType()) {
1286 // Make sure that we don't have circular inheritance among our dependent
1287 // bases. For non-dependent bases, the check for completeness below handles
1288 // this.
1289 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1290 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1291 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001292 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001293 Diag(BaseLoc, diag::err_circular_inheritance)
1294 << BaseType << Context.getTypeDeclType(Class);
1295
1296 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1297 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1298 << BaseType;
1299
1300 return 0;
1301 }
1302 }
1303
Mike Stump1eb44332009-09-09 15:08:12 +00001304 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001305 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001306 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001307 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001308
1309 // Base specifiers must be record types.
1310 if (!BaseType->isRecordType()) {
1311 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1312 return 0;
1313 }
1314
1315 // C++ [class.union]p1:
1316 // A union shall not be used as a base class.
1317 if (BaseType->isUnionType()) {
1318 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1319 return 0;
1320 }
1321
1322 // C++ [class.derived]p2:
1323 // The class-name in a base-specifier shall not be an incompletely
1324 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001325 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001326 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001327 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001328 return 0;
John McCall572fc622010-08-17 07:23:57 +00001329 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001330
Eli Friedman1d954f62009-08-15 21:55:26 +00001331 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001332 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001333 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001334 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001335 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001336 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001337 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001338
Anders Carlsson1d209272011-03-25 14:55:14 +00001339 // C++ [class]p3:
1340 // If a class is marked final and it appears as a base-type-specifier in
1341 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001342 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001343 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1344 << CXXBaseDecl->getDeclName();
1345 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1346 << CXXBaseDecl->getDeclName();
1347 return 0;
1348 }
1349
John McCall572fc622010-08-17 07:23:57 +00001350 if (BaseDecl->isInvalidDecl())
1351 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001352
1353 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001354 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001355 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001356 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001357}
1358
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001359/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1360/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001361/// example:
1362/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001363/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001364BaseResult
John McCalld226f652010-08-21 09:40:31 +00001365Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001366 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001367 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001368 ParsedType basetype, SourceLocation BaseLoc,
1369 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001370 if (!classdecl)
1371 return true;
1372
Douglas Gregor40808ce2009-03-09 23:48:35 +00001373 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001374 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001375 if (!Class)
1376 return true;
1377
Richard Smith05321402013-02-19 23:47:15 +00001378 // We do not support any C++11 attributes on base-specifiers yet.
1379 // Diagnose any attributes we see.
1380 if (!Attributes.empty()) {
1381 for (AttributeList *Attr = Attributes.getList(); Attr;
1382 Attr = Attr->getNext()) {
1383 if (Attr->isInvalid() ||
1384 Attr->getKind() == AttributeList::IgnoredAttribute)
1385 continue;
1386 Diag(Attr->getLoc(),
1387 Attr->getKind() == AttributeList::UnknownAttribute
1388 ? diag::warn_unknown_attribute_ignored
1389 : diag::err_base_specifier_attribute)
1390 << Attr->getName();
1391 }
1392 }
1393
Nick Lewycky56062202010-07-26 16:56:01 +00001394 TypeSourceInfo *TInfo = 0;
1395 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001396
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001397 if (EllipsisLoc.isInvalid() &&
1398 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001399 UPPC_BaseType))
1400 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001401
Douglas Gregor2943aed2009-03-03 04:44:36 +00001402 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001403 Virtual, Access, TInfo,
1404 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001405 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001406 else
1407 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Douglas Gregor2943aed2009-03-03 04:44:36 +00001409 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001410}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001411
Douglas Gregor2943aed2009-03-03 04:44:36 +00001412/// \brief Performs the actual work of attaching the given base class
1413/// specifiers to a C++ class.
1414bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1415 unsigned NumBases) {
1416 if (NumBases == 0)
1417 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001418
1419 // Used to keep track of which base types we have already seen, so
1420 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001421 // that the key is always the unqualified canonical type of the base
1422 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001423 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1424
1425 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001426 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001427 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001428 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001429 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001430 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001431 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001432
1433 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1434 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001435 // C++ [class.mi]p3:
1436 // A class shall not be specified as a direct base class of a
1437 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001438 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001439 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001440 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001441 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001442
1443 // Delete the duplicate base class specifier; we're going to
1444 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001445 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001446
1447 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001448 } else {
1449 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001450 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001451 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001452 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1453 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1454 if (Class->isInterface() &&
1455 (!RD->isInterface() ||
1456 KnownBase->getAccessSpecifier() != AS_public)) {
1457 // The Microsoft extension __interface does not permit bases that
1458 // are not themselves public interfaces.
1459 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1460 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1461 << RD->getSourceRange();
1462 Invalid = true;
1463 }
1464 if (RD->hasAttr<WeakAttr>())
1465 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1466 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001467 }
1468 }
1469
1470 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001471 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001472
1473 // Delete the remaining (good) base class specifiers, since their
1474 // data has been copied into the CXXRecordDecl.
1475 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001476 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001477
1478 return Invalid;
1479}
1480
1481/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1482/// class, after checking whether there are any duplicate base
1483/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001484void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001485 unsigned NumBases) {
1486 if (!ClassDecl || !Bases || !NumBases)
1487 return;
1488
1489 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001490 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001491 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001492}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001493
Douglas Gregora8f32e02009-10-06 17:59:45 +00001494/// \brief Determine whether the type \p Derived is a C++ class that is
1495/// derived from the type \p Base.
1496bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001497 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001498 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001499
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001500 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001501 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001502 return false;
1503
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001504 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001505 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001506 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001507
1508 // If either the base or the derived type is invalid, don't try to
1509 // check whether one is derived from the other.
1510 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1511 return false;
1512
John McCall86ff3082010-02-04 22:26:26 +00001513 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1514 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001515}
1516
1517/// \brief Determine whether the type \p Derived is a C++ class that is
1518/// derived from the type \p Base.
1519bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001520 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001521 return false;
1522
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001523 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001524 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001525 return false;
1526
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001527 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001528 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001529 return false;
1530
Douglas Gregora8f32e02009-10-06 17:59:45 +00001531 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1532}
1533
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001534void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001535 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001536 assert(BasePathArray.empty() && "Base path array must be empty!");
1537 assert(Paths.isRecordingPaths() && "Must record paths!");
1538
1539 const CXXBasePath &Path = Paths.front();
1540
1541 // We first go backward and check if we have a virtual base.
1542 // FIXME: It would be better if CXXBasePath had the base specifier for
1543 // the nearest virtual base.
1544 unsigned Start = 0;
1545 for (unsigned I = Path.size(); I != 0; --I) {
1546 if (Path[I - 1].Base->isVirtual()) {
1547 Start = I - 1;
1548 break;
1549 }
1550 }
1551
1552 // Now add all bases.
1553 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001554 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001555}
1556
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001557/// \brief Determine whether the given base path includes a virtual
1558/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001559bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1560 for (CXXCastPath::const_iterator B = BasePath.begin(),
1561 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001562 B != BEnd; ++B)
1563 if ((*B)->isVirtual())
1564 return true;
1565
1566 return false;
1567}
1568
Douglas Gregora8f32e02009-10-06 17:59:45 +00001569/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1570/// conversion (where Derived and Base are class types) is
1571/// well-formed, meaning that the conversion is unambiguous (and
1572/// that all of the base classes are accessible). Returns true
1573/// and emits a diagnostic if the code is ill-formed, returns false
1574/// otherwise. Loc is the location where this routine should point to
1575/// if there is an error, and Range is the source range to highlight
1576/// if there is an error.
1577bool
1578Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001579 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001580 unsigned AmbigiousBaseConvID,
1581 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001582 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001583 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001584 // First, determine whether the path from Derived to Base is
1585 // ambiguous. This is slightly more expensive than checking whether
1586 // the Derived to Base conversion exists, because here we need to
1587 // explore multiple paths to determine if there is an ambiguity.
1588 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1589 /*DetectVirtual=*/false);
1590 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1591 assert(DerivationOkay &&
1592 "Can only be used with a derived-to-base conversion");
1593 (void)DerivationOkay;
1594
1595 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001596 if (InaccessibleBaseID) {
1597 // Check that the base class can be accessed.
1598 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1599 InaccessibleBaseID)) {
1600 case AR_inaccessible:
1601 return true;
1602 case AR_accessible:
1603 case AR_dependent:
1604 case AR_delayed:
1605 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001606 }
John McCall6b2accb2010-02-10 09:31:12 +00001607 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001608
1609 // Build a base path if necessary.
1610 if (BasePath)
1611 BuildBasePathArray(Paths, *BasePath);
1612 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001613 }
1614
David Majnemer2f686692013-06-22 06:43:58 +00001615 if (AmbigiousBaseConvID) {
1616 // We know that the derived-to-base conversion is ambiguous, and
1617 // we're going to produce a diagnostic. Perform the derived-to-base
1618 // search just one more time to compute all of the possible paths so
1619 // that we can print them out. This is more expensive than any of
1620 // the previous derived-to-base checks we've done, but at this point
1621 // performance isn't as much of an issue.
1622 Paths.clear();
1623 Paths.setRecordingPaths(true);
1624 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1625 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1626 (void)StillOkay;
1627
1628 // Build up a textual representation of the ambiguous paths, e.g.,
1629 // D -> B -> A, that will be used to illustrate the ambiguous
1630 // conversions in the diagnostic. We only print one of the paths
1631 // to each base class subobject.
1632 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1633
1634 Diag(Loc, AmbigiousBaseConvID)
1635 << Derived << Base << PathDisplayStr << Range << Name;
1636 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001637 return true;
1638}
1639
1640bool
1641Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001642 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001643 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001644 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001645 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001646 IgnoreAccess ? 0
1647 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001648 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001649 Loc, Range, DeclarationName(),
1650 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001651}
1652
1653
1654/// @brief Builds a string representing ambiguous paths from a
1655/// specific derived class to different subobjects of the same base
1656/// class.
1657///
1658/// This function builds a string that can be used in error messages
1659/// to show the different paths that one can take through the
1660/// inheritance hierarchy to go from the derived class to different
1661/// subobjects of a base class. The result looks something like this:
1662/// @code
1663/// struct D -> struct B -> struct A
1664/// struct D -> struct C -> struct A
1665/// @endcode
1666std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1667 std::string PathDisplayStr;
1668 std::set<unsigned> DisplayedPaths;
1669 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1670 Path != Paths.end(); ++Path) {
1671 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1672 // We haven't displayed a path to this particular base
1673 // class subobject yet.
1674 PathDisplayStr += "\n ";
1675 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1676 for (CXXBasePath::const_iterator Element = Path->begin();
1677 Element != Path->end(); ++Element)
1678 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1679 }
1680 }
1681
1682 return PathDisplayStr;
1683}
1684
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001685//===----------------------------------------------------------------------===//
1686// C++ class member Handling
1687//===----------------------------------------------------------------------===//
1688
Abramo Bagnara6206d532010-06-05 05:09:32 +00001689/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001690bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1691 SourceLocation ASLoc,
1692 SourceLocation ColonLoc,
1693 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001694 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001695 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001696 ASLoc, ColonLoc);
1697 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001698 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001699}
1700
Richard Smitha4b39652012-08-06 03:25:17 +00001701/// CheckOverrideControl - Check C++11 override control semantics.
1702void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001703 if (D->isInvalidDecl())
1704 return;
1705
Chris Lattner5f9e2722011-07-23 10:55:15 +00001706 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001707
Richard Smitha4b39652012-08-06 03:25:17 +00001708 // Do we know which functions this declaration might be overriding?
1709 bool OverridesAreKnown = !MD ||
1710 (!MD->getParent()->hasAnyDependentBases() &&
1711 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001712
Richard Smitha4b39652012-08-06 03:25:17 +00001713 if (!MD || !MD->isVirtual()) {
1714 if (OverridesAreKnown) {
1715 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1716 Diag(OA->getLocation(),
1717 diag::override_keyword_only_allowed_on_virtual_member_functions)
1718 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1719 D->dropAttr<OverrideAttr>();
1720 }
1721 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1722 Diag(FA->getLocation(),
1723 diag::override_keyword_only_allowed_on_virtual_member_functions)
1724 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1725 D->dropAttr<FinalAttr>();
1726 }
1727 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001728 return;
1729 }
Richard Smitha4b39652012-08-06 03:25:17 +00001730
1731 if (!OverridesAreKnown)
1732 return;
1733
1734 // C++11 [class.virtual]p5:
1735 // If a virtual function is marked with the virt-specifier override and
1736 // does not override a member function of a base class, the program is
1737 // ill-formed.
1738 bool HasOverriddenMethods =
1739 MD->begin_overridden_methods() != MD->end_overridden_methods();
1740 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1741 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1742 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001743}
1744
Richard Smitha4b39652012-08-06 03:25:17 +00001745/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001746/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001747/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001748bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1749 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001750 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001751 return false;
1752
1753 Diag(New->getLocation(), diag::err_final_function_overridden)
1754 << New->getDeclName();
1755 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1756 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001757}
1758
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001759static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001760 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1761 // FIXME: Destruction of ObjC lifetime types has side-effects.
1762 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1763 return !RD->isCompleteDefinition() ||
1764 !RD->hasTrivialDefaultConstructor() ||
1765 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001766 return false;
1767}
1768
John McCall76da55d2013-04-16 07:28:30 +00001769static AttributeList *getMSPropertyAttr(AttributeList *list) {
1770 for (AttributeList* it = list; it != 0; it = it->getNext())
1771 if (it->isDeclspecPropertyAttribute())
1772 return it;
1773 return 0;
1774}
1775
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001776/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1777/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001778/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001779/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1780/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001781NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001782Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001783 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001784 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001785 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001786 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001787 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1788 DeclarationName Name = NameInfo.getName();
1789 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001790
1791 // For anonymous bitfields, the location should point to the type.
1792 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001793 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001794
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001795 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001796
John McCall4bde1e12010-06-04 08:34:12 +00001797 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001798 assert(!DS.isFriendSpecified());
1799
Richard Smith1ab0d902011-06-25 02:28:38 +00001800 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001801
John McCalle402e722012-09-25 07:32:39 +00001802 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1803 // The Microsoft extension __interface only permits public member functions
1804 // and prohibits constructors, destructors, operators, non-public member
1805 // functions, static methods and data members.
1806 unsigned InvalidDecl;
1807 bool ShowDeclName = true;
1808 if (!isFunc)
1809 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1810 else if (AS != AS_public)
1811 InvalidDecl = 2;
1812 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1813 InvalidDecl = 3;
1814 else switch (Name.getNameKind()) {
1815 case DeclarationName::CXXConstructorName:
1816 InvalidDecl = 4;
1817 ShowDeclName = false;
1818 break;
1819
1820 case DeclarationName::CXXDestructorName:
1821 InvalidDecl = 5;
1822 ShowDeclName = false;
1823 break;
1824
1825 case DeclarationName::CXXOperatorName:
1826 case DeclarationName::CXXConversionFunctionName:
1827 InvalidDecl = 6;
1828 break;
1829
1830 default:
1831 InvalidDecl = 0;
1832 break;
1833 }
1834
1835 if (InvalidDecl) {
1836 if (ShowDeclName)
1837 Diag(Loc, diag::err_invalid_member_in_interface)
1838 << (InvalidDecl-1) << Name;
1839 else
1840 Diag(Loc, diag::err_invalid_member_in_interface)
1841 << (InvalidDecl-1) << "";
1842 return 0;
1843 }
1844 }
1845
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001846 // C++ 9.2p6: A member shall not be declared to have automatic storage
1847 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001848 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1849 // data members and cannot be applied to names declared const or static,
1850 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001851 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001852 case DeclSpec::SCS_unspecified:
1853 case DeclSpec::SCS_typedef:
1854 case DeclSpec::SCS_static:
1855 break;
1856 case DeclSpec::SCS_mutable:
1857 if (isFunc) {
1858 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Richard Smithec642442013-04-12 22:46:28 +00001860 // FIXME: It would be nicer if the keyword was ignored only for this
1861 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001862 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001863 }
1864 break;
1865 default:
1866 Diag(DS.getStorageClassSpecLoc(),
1867 diag::err_storageclass_invalid_for_member);
1868 D.getMutableDeclSpec().ClearStorageClassSpecs();
1869 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001870 }
1871
Sebastian Redl669d5d72008-11-14 23:42:31 +00001872 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1873 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001874 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001875
David Blaikie1d87fba2013-01-30 01:22:18 +00001876 if (DS.isConstexprSpecified() && isInstField) {
1877 SemaDiagnosticBuilder B =
1878 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1879 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1880 if (InitStyle == ICIS_NoInit) {
1881 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1882 D.getMutableDeclSpec().ClearConstexprSpec();
1883 const char *PrevSpec;
1884 unsigned DiagID;
1885 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1886 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001887 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001888 assert(!Failed && "Making a constexpr member const shouldn't fail");
1889 } else {
1890 B << 1;
1891 const char *PrevSpec;
1892 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001893 if (D.getMutableDeclSpec().SetStorageClassSpec(
1894 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001895 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001896 "This is the only DeclSpec that should fail to be applied");
1897 B << 1;
1898 } else {
1899 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1900 isInstField = false;
1901 }
1902 }
1903 }
1904
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001905 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001906 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001907 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001908
1909 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001910 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001911 Diag(Loc, diag::err_bad_variable_name)
1912 << Name;
1913 return 0;
1914 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001915
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001916 IdentifierInfo *II = Name.getAsIdentifierInfo();
1917
Douglas Gregorf2503652011-09-21 14:40:46 +00001918 // Member field could not be with "template" keyword.
1919 // So TemplateParameterLists should be empty in this case.
1920 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001921 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001922 if (TemplateParams->size()) {
1923 // There is no such thing as a member field template.
1924 Diag(D.getIdentifierLoc(), diag::err_template_member)
1925 << II
1926 << SourceRange(TemplateParams->getTemplateLoc(),
1927 TemplateParams->getRAngleLoc());
1928 } else {
1929 // There is an extraneous 'template<>' for this member.
1930 Diag(TemplateParams->getTemplateLoc(),
1931 diag::err_template_member_noparams)
1932 << II
1933 << SourceRange(TemplateParams->getTemplateLoc(),
1934 TemplateParams->getRAngleLoc());
1935 }
1936 return 0;
1937 }
1938
Douglas Gregor922fff22010-10-13 22:19:53 +00001939 if (SS.isSet() && !SS.isInvalid()) {
1940 // The user provided a superfluous scope specifier inside a class
1941 // definition:
1942 //
1943 // class X {
1944 // int X::member;
1945 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001946 if (DeclContext *DC = computeDeclContext(SS, false))
1947 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001948 else
1949 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1950 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001951
Douglas Gregor922fff22010-10-13 22:19:53 +00001952 SS.clear();
1953 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001954
John McCall76da55d2013-04-16 07:28:30 +00001955 AttributeList *MSPropertyAttr =
1956 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00001957 if (MSPropertyAttr) {
1958 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1959 BitWidth, InitStyle, AS, MSPropertyAttr);
1960 if (!Member)
1961 return 0;
1962 isInstField = false;
1963 } else {
1964 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1965 BitWidth, InitStyle, AS);
1966 assert(Member && "HandleField never returns null");
1967 }
1968 } else {
1969 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1970
1971 Member = HandleDeclarator(S, D, TemplateParameterLists);
1972 if (!Member)
1973 return 0;
1974
1975 // Non-instance-fields can't have a bitfield.
1976 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001977 if (Member->isInvalidDecl()) {
1978 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001979 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001980 // C++ 9.6p3: A bit-field shall not be a static member.
1981 // "static member 'A' cannot be a bit-field"
1982 Diag(Loc, diag::err_static_not_bitfield)
1983 << Name << BitWidth->getSourceRange();
1984 } else if (isa<TypedefDecl>(Member)) {
1985 // "typedef member 'x' cannot be a bit-field"
1986 Diag(Loc, diag::err_typedef_not_bitfield)
1987 << Name << BitWidth->getSourceRange();
1988 } else {
1989 // A function typedef ("typedef int f(); f a;").
1990 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1991 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001992 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001993 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001994 }
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Chris Lattner8b963ef2009-03-05 23:01:03 +00001996 BitWidth = 0;
1997 Member->setInvalidDecl();
1998 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001999
2000 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Douglas Gregor37b372b2009-08-20 22:52:58 +00002002 // If we have declared a member function template, set the access of the
2003 // templated declaration as well.
2004 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2005 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002006 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002007
Richard Smitha4b39652012-08-06 03:25:17 +00002008 if (VS.isOverrideSpecified())
2009 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2010 if (VS.isFinalSpecified())
2011 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002012
Douglas Gregorf5251602011-03-08 17:10:18 +00002013 if (VS.getLastLocation().isValid()) {
2014 // Update the end location of a method that has a virt-specifiers.
2015 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2016 MD->setRangeEnd(VS.getLastLocation());
2017 }
Richard Smitha4b39652012-08-06 03:25:17 +00002018
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002019 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002020
Douglas Gregor10bd3682008-11-17 22:58:34 +00002021 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002022
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002023 if (isInstField) {
2024 FieldDecl *FD = cast<FieldDecl>(Member);
2025 FieldCollector->Add(FD);
2026
2027 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2028 FD->getLocation())
2029 != DiagnosticsEngine::Ignored) {
2030 // Remember all explicit private FieldDecls that have a name, no side
2031 // effects and are not part of a dependent type declaration.
2032 if (!FD->isImplicit() && FD->getDeclName() &&
2033 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002034 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002035 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002036 !InitializationHasSideEffects(*FD))
2037 UnusedPrivateFields.insert(FD);
2038 }
2039 }
2040
John McCalld226f652010-08-21 09:40:31 +00002041 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002042}
2043
Hans Wennborg471f9852012-09-18 15:58:06 +00002044namespace {
2045 class UninitializedFieldVisitor
2046 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2047 Sema &S;
2048 ValueDecl *VD;
2049 public:
2050 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2051 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002052 S(S) {
2053 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2054 this->VD = IFD->getAnonField();
2055 else
2056 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002057 }
2058
2059 void HandleExpr(Expr *E) {
2060 if (!E) return;
2061
2062 // Expressions like x(x) sometimes lack the surrounding expressions
2063 // but need to be checked anyways.
2064 HandleValue(E);
2065 Visit(E);
2066 }
2067
2068 void HandleValue(Expr *E) {
2069 E = E->IgnoreParens();
2070
2071 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2072 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002073 return;
2074
2075 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2076 // or union.
2077 MemberExpr *FieldME = ME;
2078
Hans Wennborg471f9852012-09-18 15:58:06 +00002079 Expr *Base = E;
2080 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002081 ME = cast<MemberExpr>(Base);
2082
2083 if (isa<VarDecl>(ME->getMemberDecl()))
2084 return;
2085
2086 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2087 if (!FD->isAnonymousStructOrUnion())
2088 FieldME = ME;
2089
Hans Wennborg471f9852012-09-18 15:58:06 +00002090 Base = ME->getBase();
2091 }
2092
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002093 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00002094 unsigned diag = VD->getType()->isReferenceType()
2095 ? diag::warn_reference_field_is_uninit
2096 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002097 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002098 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002099 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002100 }
2101
2102 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2103 HandleValue(CO->getTrueExpr());
2104 HandleValue(CO->getFalseExpr());
2105 return;
2106 }
2107
2108 if (BinaryConditionalOperator *BCO =
2109 dyn_cast<BinaryConditionalOperator>(E)) {
2110 HandleValue(BCO->getCommon());
2111 HandleValue(BCO->getFalseExpr());
2112 return;
2113 }
2114
2115 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2116 switch (BO->getOpcode()) {
2117 default:
2118 return;
2119 case(BO_PtrMemD):
2120 case(BO_PtrMemI):
2121 HandleValue(BO->getLHS());
2122 return;
2123 case(BO_Comma):
2124 HandleValue(BO->getRHS());
2125 return;
2126 }
2127 }
2128 }
2129
2130 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2131 if (E->getCastKind() == CK_LValueToRValue)
2132 HandleValue(E->getSubExpr());
2133
2134 Inherited::VisitImplicitCastExpr(E);
2135 }
2136
2137 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2138 Expr *Callee = E->getCallee();
2139 if (isa<MemberExpr>(Callee))
2140 HandleValue(Callee);
2141
2142 Inherited::VisitCXXMemberCallExpr(E);
2143 }
2144 };
2145 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2146 ValueDecl *VD) {
2147 UninitializedFieldVisitor(S, VD).HandleExpr(E);
2148 }
2149} // namespace
2150
Richard Smith7a614d82011-06-11 17:19:42 +00002151/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002152/// in-class initializer for a non-static C++ class member, and after
2153/// instantiating an in-class initializer in a class template. Such actions
2154/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002155void
Richard Smithca523302012-06-10 03:12:00 +00002156Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002157 Expr *InitExpr) {
2158 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002159 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2160 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002161
2162 if (!InitExpr) {
2163 FD->setInvalidDecl();
2164 FD->removeInClassInitializer();
2165 return;
2166 }
2167
Peter Collingbournefef21892011-10-23 18:59:44 +00002168 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2169 FD->setInvalidDecl();
2170 FD->removeInClassInitializer();
2171 return;
2172 }
2173
Hans Wennborg471f9852012-09-18 15:58:06 +00002174 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2175 != DiagnosticsEngine::Ignored) {
2176 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2177 }
2178
Richard Smith7a614d82011-06-11 17:19:42 +00002179 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002180 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002181 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002182 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002183 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002184 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002185 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2186 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002187 if (Init.isInvalid()) {
2188 FD->setInvalidDecl();
2189 return;
2190 }
Richard Smith7a614d82011-06-11 17:19:42 +00002191 }
2192
Richard Smith41956372013-01-14 22:39:08 +00002193 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002194 // The initialization of each base and member constitutes a
2195 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002196 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002197 if (Init.isInvalid()) {
2198 FD->setInvalidDecl();
2199 return;
2200 }
2201
2202 InitExpr = Init.release();
2203
2204 FD->setInClassInitializer(InitExpr);
2205}
2206
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002207/// \brief Find the direct and/or virtual base specifiers that
2208/// correspond to the given base type, for use in base initialization
2209/// within a constructor.
2210static bool FindBaseInitializer(Sema &SemaRef,
2211 CXXRecordDecl *ClassDecl,
2212 QualType BaseType,
2213 const CXXBaseSpecifier *&DirectBaseSpec,
2214 const CXXBaseSpecifier *&VirtualBaseSpec) {
2215 // First, check for a direct base class.
2216 DirectBaseSpec = 0;
2217 for (CXXRecordDecl::base_class_const_iterator Base
2218 = ClassDecl->bases_begin();
2219 Base != ClassDecl->bases_end(); ++Base) {
2220 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2221 // We found a direct base of this type. That's what we're
2222 // initializing.
2223 DirectBaseSpec = &*Base;
2224 break;
2225 }
2226 }
2227
2228 // Check for a virtual base class.
2229 // FIXME: We might be able to short-circuit this if we know in advance that
2230 // there are no virtual bases.
2231 VirtualBaseSpec = 0;
2232 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2233 // We haven't found a base yet; search the class hierarchy for a
2234 // virtual base class.
2235 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2236 /*DetectVirtual=*/false);
2237 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2238 BaseType, Paths)) {
2239 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2240 Path != Paths.end(); ++Path) {
2241 if (Path->back().Base->isVirtual()) {
2242 VirtualBaseSpec = Path->back().Base;
2243 break;
2244 }
2245 }
2246 }
2247 }
2248
2249 return DirectBaseSpec || VirtualBaseSpec;
2250}
2251
Sebastian Redl6df65482011-09-24 17:48:25 +00002252/// \brief Handle a C++ member initializer using braced-init-list syntax.
2253MemInitResult
2254Sema::ActOnMemInitializer(Decl *ConstructorD,
2255 Scope *S,
2256 CXXScopeSpec &SS,
2257 IdentifierInfo *MemberOrBase,
2258 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002259 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002260 SourceLocation IdLoc,
2261 Expr *InitList,
2262 SourceLocation EllipsisLoc) {
2263 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002264 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002265 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002266}
2267
2268/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002269MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002270Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002271 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002272 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002273 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002274 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002275 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002276 SourceLocation IdLoc,
2277 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002278 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002279 SourceLocation RParenLoc,
2280 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002281 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002282 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002283 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002284 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002285}
2286
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002287namespace {
2288
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002289// Callback to only accept typo corrections that can be a valid C++ member
2290// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002291class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2292 public:
2293 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2294 : ClassDecl(ClassDecl) {}
2295
2296 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2297 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2298 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2299 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2300 else
2301 return isa<TypeDecl>(ND);
2302 }
2303 return false;
2304 }
2305
2306 private:
2307 CXXRecordDecl *ClassDecl;
2308};
2309
2310}
2311
Sebastian Redl6df65482011-09-24 17:48:25 +00002312/// \brief Handle a C++ member initializer.
2313MemInitResult
2314Sema::BuildMemInitializer(Decl *ConstructorD,
2315 Scope *S,
2316 CXXScopeSpec &SS,
2317 IdentifierInfo *MemberOrBase,
2318 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002319 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002320 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002321 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002322 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002323 if (!ConstructorD)
2324 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002325
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002326 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002327
2328 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002329 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002330 if (!Constructor) {
2331 // The user wrote a constructor initializer on a function that is
2332 // not a C++ constructor. Ignore the error for now, because we may
2333 // have more member initializers coming; we'll diagnose it just
2334 // once in ActOnMemInitializers.
2335 return true;
2336 }
2337
2338 CXXRecordDecl *ClassDecl = Constructor->getParent();
2339
2340 // C++ [class.base.init]p2:
2341 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002342 // constructor's class and, if not found in that scope, are looked
2343 // up in the scope containing the constructor's definition.
2344 // [Note: if the constructor's class contains a member with the
2345 // same name as a direct or virtual base class of the class, a
2346 // mem-initializer-id naming the member or base class and composed
2347 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002348 // mem-initializer-id for the hidden base class may be specified
2349 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002350 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002351 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002352 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002353 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002354 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002355 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002356 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2357 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002358 if (EllipsisLoc.isValid())
2359 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002360 << MemberOrBase
2361 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002362
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002363 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002364 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002365 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002366 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002367 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002368 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002369 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002370
2371 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002372 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002373 } else if (DS.getTypeSpecType() == TST_decltype) {
2374 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002375 } else {
2376 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2377 LookupParsedName(R, S, &SS);
2378
2379 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2380 if (!TyD) {
2381 if (R.isAmbiguous()) return true;
2382
John McCallfd225442010-04-09 19:01:14 +00002383 // We don't want access-control diagnostics here.
2384 R.suppressDiagnostics();
2385
Douglas Gregor7a886e12010-01-19 06:46:48 +00002386 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2387 bool NotUnknownSpecialization = false;
2388 DeclContext *DC = computeDeclContext(SS, false);
2389 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2390 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2391
2392 if (!NotUnknownSpecialization) {
2393 // When the scope specifier can refer to a member of an unknown
2394 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002395 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2396 SS.getWithLocInContext(Context),
2397 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002398 if (BaseType.isNull())
2399 return true;
2400
Douglas Gregor7a886e12010-01-19 06:46:48 +00002401 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002402 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002403 }
2404 }
2405
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002406 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002407 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002408 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002409 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002410 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002411 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002412 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2413 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002414 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002415 // We have found a non-static data member with a similar
2416 // name to what was typed; complain and initialize that
2417 // member.
2418 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2419 << MemberOrBase << true << CorrectedQuotedStr
2420 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2421 Diag(Member->getLocation(), diag::note_previous_decl)
2422 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002423
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002424 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002425 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002426 const CXXBaseSpecifier *DirectBaseSpec;
2427 const CXXBaseSpecifier *VirtualBaseSpec;
2428 if (FindBaseInitializer(*this, ClassDecl,
2429 Context.getTypeDeclType(Type),
2430 DirectBaseSpec, VirtualBaseSpec)) {
2431 // We have found a direct or virtual base class with a
2432 // similar name to what was typed; complain and initialize
2433 // that base class.
2434 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002435 << MemberOrBase << false << CorrectedQuotedStr
2436 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002437
2438 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2439 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002440 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002441 diag::note_base_class_specified_here)
2442 << BaseSpec->getType()
2443 << BaseSpec->getSourceRange();
2444
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002445 TyD = Type;
2446 }
2447 }
2448 }
2449
Douglas Gregor7a886e12010-01-19 06:46:48 +00002450 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002451 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002452 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002453 return true;
2454 }
John McCall2b194412009-12-21 10:41:20 +00002455 }
2456
Douglas Gregor7a886e12010-01-19 06:46:48 +00002457 if (BaseType.isNull()) {
2458 BaseType = Context.getTypeDeclType(TyD);
2459 if (SS.isSet()) {
2460 NestedNameSpecifier *Qualifier =
2461 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002462
Douglas Gregor7a886e12010-01-19 06:46:48 +00002463 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002464 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002465 }
John McCall2b194412009-12-21 10:41:20 +00002466 }
2467 }
Mike Stump1eb44332009-09-09 15:08:12 +00002468
John McCalla93c9342009-12-07 02:54:59 +00002469 if (!TInfo)
2470 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002471
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002472 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002473}
2474
Chandler Carruth81c64772011-09-03 01:14:15 +00002475/// Checks a member initializer expression for cases where reference (or
2476/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002477static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2478 Expr *Init,
2479 SourceLocation IdLoc) {
2480 QualType MemberTy = Member->getType();
2481
2482 // We only handle pointers and references currently.
2483 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2484 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2485 return;
2486
2487 const bool IsPointer = MemberTy->isPointerType();
2488 if (IsPointer) {
2489 if (const UnaryOperator *Op
2490 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2491 // The only case we're worried about with pointers requires taking the
2492 // address.
2493 if (Op->getOpcode() != UO_AddrOf)
2494 return;
2495
2496 Init = Op->getSubExpr();
2497 } else {
2498 // We only handle address-of expression initializers for pointers.
2499 return;
2500 }
2501 }
2502
Richard Smitha4bb99c2013-06-12 21:51:50 +00002503 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002504 // We only warn when referring to a non-reference parameter declaration.
2505 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2506 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002507 return;
2508
2509 S.Diag(Init->getExprLoc(),
2510 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2511 : diag::warn_bind_ref_member_to_parameter)
2512 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002513 } else {
2514 // Other initializers are fine.
2515 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002516 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002517
2518 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2519 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002520}
2521
John McCallf312b1e2010-08-26 23:41:50 +00002522MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002523Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002524 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002525 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2526 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2527 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002528 "Member must be a FieldDecl or IndirectFieldDecl");
2529
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002530 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002531 return true;
2532
Douglas Gregor464b2f02010-11-05 22:21:31 +00002533 if (Member->isInvalidDecl())
2534 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002535
John McCallb4190042009-11-04 23:02:40 +00002536 // Diagnose value-uses of fields to initialize themselves, e.g.
2537 // foo(foo)
2538 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002539 // TODO: implement -Wuninitialized and fold this into that framework.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002540 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002541 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002542 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002543 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002544 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002545 } else {
2546 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002547 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002548 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002549
Richard Trieude5e75c2012-06-14 23:11:34 +00002550 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2551 != DiagnosticsEngine::Ignored)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002552 for (unsigned i = 0, e = Args.size(); i != e; ++i)
Richard Trieude5e75c2012-06-14 23:11:34 +00002553 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002554 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002555 // initializing the i'th field, throw a warning if any of the >= i'th
2556 // fields are used, as they are not yet initialized.
2557 // Right now we are only handling the case where the i'th field uses
2558 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002559 // Also need to take into account that some fields may be initialized by
2560 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002561 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002562
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002563 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002564
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002565 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002566 // Can't check initialization for a member of dependent type or when
2567 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002568 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002569 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002570 bool InitList = false;
2571 if (isa<InitListExpr>(Init)) {
2572 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002573 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002574 }
2575
Chandler Carruth894aed92010-12-06 09:23:57 +00002576 // Initialize the member.
2577 InitializedEntity MemberEntity =
2578 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2579 : InitializedEntity::InitializeMember(IndirectMember, 0);
2580 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002581 InitList ? InitializationKind::CreateDirectList(IdLoc)
2582 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2583 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002584
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002585 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2586 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002587 if (MemberInit.isInvalid())
2588 return true;
2589
Richard Smith8a07cd32013-06-12 20:42:33 +00002590 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2591
Richard Smith41956372013-01-14 22:39:08 +00002592 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002593 // The initialization of each base and member constitutes a
2594 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002595 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002596 if (MemberInit.isInvalid())
2597 return true;
2598
Richard Smithc83c2302012-12-19 01:39:02 +00002599 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002600 }
2601
Chandler Carruth894aed92010-12-06 09:23:57 +00002602 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002603 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2604 InitRange.getBegin(), Init,
2605 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002606 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002607 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2608 InitRange.getBegin(), Init,
2609 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002610 }
Eli Friedman59c04372009-07-29 19:44:27 +00002611}
2612
John McCallf312b1e2010-08-26 23:41:50 +00002613MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002614Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002615 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002616 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002617 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002618 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002619 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002620 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002621
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002622 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002623 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002624 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2625 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002626 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002627 }
2628
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002629 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002630 // Initialize the object.
2631 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2632 QualType(ClassDecl->getTypeForDecl(), 0));
2633 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002634 InitList ? InitializationKind::CreateDirectList(NameLoc)
2635 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2636 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002637 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002638 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002639 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002640 if (DelegationInit.isInvalid())
2641 return true;
2642
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002643 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2644 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002645
Richard Smith41956372013-01-14 22:39:08 +00002646 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002647 // The initialization of each base and member constitutes a
2648 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002649 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2650 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002651 if (DelegationInit.isInvalid())
2652 return true;
2653
Eli Friedmand21016f2012-05-19 23:35:23 +00002654 // If we are in a dependent context, template instantiation will
2655 // perform this type-checking again. Just save the arguments that we
2656 // received in a ParenListExpr.
2657 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2658 // of the information that we have about the base
2659 // initializer. However, deconstructing the ASTs is a dicey process,
2660 // and this approach is far more likely to get the corner cases right.
2661 if (CurContext->isDependentContext())
2662 DelegationInit = Owned(Init);
2663
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002664 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002665 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002666 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002667}
2668
2669MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002670Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002671 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002672 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002673 SourceLocation BaseLoc
2674 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002675
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002676 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2677 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2678 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2679
2680 // C++ [class.base.init]p2:
2681 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002682 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002683 // of that class, the mem-initializer is ill-formed. A
2684 // mem-initializer-list can initialize a base class using any
2685 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002686 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002687
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002688 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002689 if (EllipsisLoc.isValid()) {
2690 // This is a pack expansion.
2691 if (!BaseType->containsUnexpandedParameterPack()) {
2692 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002693 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002694
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002695 EllipsisLoc = SourceLocation();
2696 }
2697 } else {
2698 // Check for any unexpanded parameter packs.
2699 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2700 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002701
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002702 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002703 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002704 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002705
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002706 // Check for direct and virtual base classes.
2707 const CXXBaseSpecifier *DirectBaseSpec = 0;
2708 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2709 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002710 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2711 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002712 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002713
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002714 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2715 VirtualBaseSpec);
2716
2717 // C++ [base.class.init]p2:
2718 // Unless the mem-initializer-id names a nonstatic data member of the
2719 // constructor's class or a direct or virtual base of that class, the
2720 // mem-initializer is ill-formed.
2721 if (!DirectBaseSpec && !VirtualBaseSpec) {
2722 // If the class has any dependent bases, then it's possible that
2723 // one of those types will resolve to the same type as
2724 // BaseType. Therefore, just treat this as a dependent base
2725 // class initialization. FIXME: Should we try to check the
2726 // initialization anyway? It seems odd.
2727 if (ClassDecl->hasAnyDependentBases())
2728 Dependent = true;
2729 else
2730 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2731 << BaseType << Context.getTypeDeclType(ClassDecl)
2732 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2733 }
2734 }
2735
2736 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002737 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002738
Sebastian Redl6df65482011-09-24 17:48:25 +00002739 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2740 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002741 InitRange.getBegin(), Init,
2742 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002743 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002744
2745 // C++ [base.class.init]p2:
2746 // If a mem-initializer-id is ambiguous because it designates both
2747 // a direct non-virtual base class and an inherited virtual base
2748 // class, the mem-initializer is ill-formed.
2749 if (DirectBaseSpec && VirtualBaseSpec)
2750 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002751 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002752
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002753 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002754 if (!BaseSpec)
2755 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2756
2757 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002758 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002759 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002760 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002761 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002762 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002763 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002764
2765 InitializedEntity BaseEntity =
2766 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2767 InitializationKind Kind =
2768 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2769 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2770 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002771 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2772 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002773 if (BaseInit.isInvalid())
2774 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002775
Richard Smith41956372013-01-14 22:39:08 +00002776 // C++11 [class.base.init]p7:
2777 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002778 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002779 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002780 if (BaseInit.isInvalid())
2781 return true;
2782
2783 // If we are in a dependent context, template instantiation will
2784 // perform this type-checking again. Just save the arguments that we
2785 // received in a ParenListExpr.
2786 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2787 // of the information that we have about the base
2788 // initializer. However, deconstructing the ASTs is a dicey process,
2789 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002790 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002791 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002792
Sean Huntcbb67482011-01-08 20:30:50 +00002793 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002794 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002795 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002796 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002797 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002798}
2799
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002800// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002801static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2802 if (T.isNull()) T = E->getType();
2803 QualType TargetType = SemaRef.BuildReferenceType(
2804 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002805 SourceLocation ExprLoc = E->getLocStart();
2806 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2807 TargetType, ExprLoc);
2808
2809 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2810 SourceRange(ExprLoc, ExprLoc),
2811 E->getSourceRange()).take();
2812}
2813
Anders Carlssone5ef7402010-04-23 03:10:23 +00002814/// ImplicitInitializerKind - How an implicit base or member initializer should
2815/// initialize its base or member.
2816enum ImplicitInitializerKind {
2817 IIK_Default,
2818 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002819 IIK_Move,
2820 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002821};
2822
Anders Carlssondefefd22010-04-23 02:00:02 +00002823static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002824BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002825 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002826 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002827 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002828 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002829 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002830 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2831 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002832
John McCall60d7b3a2010-08-24 06:29:42 +00002833 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002834
2835 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002836 case IIK_Inherit: {
2837 const CXXRecordDecl *Inherited =
2838 Constructor->getInheritedConstructor()->getParent();
2839 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2840 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2841 // C++11 [class.inhctor]p8:
2842 // Each expression in the expression-list is of the form
2843 // static_cast<T&&>(p), where p is the name of the corresponding
2844 // constructor parameter and T is the declared type of p.
2845 SmallVector<Expr*, 16> Args;
2846 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2847 ParmVarDecl *PD = Constructor->getParamDecl(I);
2848 ExprResult ArgExpr =
2849 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2850 VK_LValue, SourceLocation());
2851 if (ArgExpr.isInvalid())
2852 return true;
2853 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2854 }
2855
2856 InitializationKind InitKind = InitializationKind::CreateDirect(
2857 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002858 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002859 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2860 break;
2861 }
2862 }
2863 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002864 case IIK_Default: {
2865 InitializationKind InitKind
2866 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002867 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2868 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002869 break;
2870 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002871
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002872 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002873 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002874 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002875 ParmVarDecl *Param = Constructor->getParamDecl(0);
2876 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002877
Anders Carlssone5ef7402010-04-23 03:10:23 +00002878 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002879 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002880 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002881 Constructor->getLocation(), ParamType,
2882 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002883
Eli Friedman5f2987c2012-02-02 03:46:19 +00002884 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2885
Anders Carlssonc7957502010-04-24 22:02:54 +00002886 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002887 QualType ArgTy =
2888 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2889 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002890
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002891 if (Moving) {
2892 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2893 }
2894
John McCallf871d0c2010-08-07 06:22:56 +00002895 CXXCastPath BasePath;
2896 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002897 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2898 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002899 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002900 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002901
Anders Carlssone5ef7402010-04-23 03:10:23 +00002902 InitializationKind InitKind
2903 = InitializationKind::CreateDirect(Constructor->getLocation(),
2904 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002905 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2906 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002907 break;
2908 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002909 }
John McCall9ae2f072010-08-23 23:25:46 +00002910
Douglas Gregor53c374f2010-12-07 00:41:46 +00002911 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002912 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002913 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002914
Anders Carlssondefefd22010-04-23 02:00:02 +00002915 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002916 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002917 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2918 SourceLocation()),
2919 BaseSpec->isVirtual(),
2920 SourceLocation(),
2921 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002922 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002923 SourceLocation());
2924
Anders Carlssondefefd22010-04-23 02:00:02 +00002925 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002926}
2927
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002928static bool RefersToRValueRef(Expr *MemRef) {
2929 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2930 return Referenced->getType()->isRValueReferenceType();
2931}
2932
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002933static bool
2934BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002935 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002936 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002937 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002938 if (Field->isInvalidDecl())
2939 return true;
2940
Chandler Carruthf186b542010-06-29 23:50:44 +00002941 SourceLocation Loc = Constructor->getLocation();
2942
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002943 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2944 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002945 ParmVarDecl *Param = Constructor->getParamDecl(0);
2946 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002947
2948 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002949 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2950 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002951
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002952 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002953 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002954 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002955 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002956
Eli Friedman5f2987c2012-02-02 03:46:19 +00002957 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2958
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002959 if (Moving) {
2960 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2961 }
2962
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002963 // Build a reference to this field within the parameter.
2964 CXXScopeSpec SS;
2965 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2966 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002967 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2968 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002969 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002970 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002971 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002972 ParamType, Loc,
2973 /*IsArrow=*/false,
2974 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002975 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002976 /*FirstQualifierInScope=*/0,
2977 MemberLookup,
2978 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002979 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002980 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002981
2982 // C++11 [class.copy]p15:
2983 // - if a member m has rvalue reference type T&&, it is direct-initialized
2984 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002985 if (RefersToRValueRef(CtorArg.get())) {
2986 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002987 }
2988
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002989 // When the field we are copying is an array, create index variables for
2990 // each dimension of the array. We use these index variables to subscript
2991 // the source array, and other clients (e.g., CodeGen) will perform the
2992 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002993 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002994 QualType BaseType = Field->getType();
2995 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002996 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002997 while (const ConstantArrayType *Array
2998 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002999 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003000 // Create the iteration variable for this array index.
3001 IdentifierInfo *IterationVarName = 0;
3002 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003003 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003004 llvm::raw_svector_ostream OS(Str);
3005 OS << "__i" << IndexVariables.size();
3006 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3007 }
3008 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003009 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003010 IterationVarName, SizeType,
3011 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003012 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003013 IndexVariables.push_back(IterationVar);
3014
3015 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003016 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003017 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003018 assert(!IterationVarRef.isInvalid() &&
3019 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003020 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3021 assert(!IterationVarRef.isInvalid() &&
3022 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003023
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003024 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003025 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003026 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003027 Loc);
3028 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003029 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003030
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003031 BaseType = Array->getElementType();
3032 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003033
3034 // The array subscript expression is an lvalue, which is wrong for moving.
3035 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003036 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003037
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003038 // Construct the entity that we will be initializing. For an array, this
3039 // will be first element in the array, which may require several levels
3040 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003041 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003042 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003043 if (Indirect)
3044 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3045 else
3046 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003047 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3048 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3049 0,
3050 Entities.back()));
3051
3052 // Direct-initialize to use the copy constructor.
3053 InitializationKind InitKind =
3054 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3055
Sebastian Redl74e611a2011-09-04 18:14:28 +00003056 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003057 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003058
John McCall60d7b3a2010-08-24 06:29:42 +00003059 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003060 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003061 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003062 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003063 if (MemberInit.isInvalid())
3064 return true;
3065
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003066 if (Indirect) {
3067 assert(IndexVariables.size() == 0 &&
3068 "Indirect field improperly initialized");
3069 CXXMemberInit
3070 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3071 Loc, Loc,
3072 MemberInit.takeAs<Expr>(),
3073 Loc);
3074 } else
3075 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3076 Loc, MemberInit.takeAs<Expr>(),
3077 Loc,
3078 IndexVariables.data(),
3079 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003080 return false;
3081 }
3082
Richard Smith07b0fdc2013-03-18 21:12:30 +00003083 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3084 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003085
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003086 QualType FieldBaseElementType =
3087 SemaRef.Context.getBaseElementType(Field->getType());
3088
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003089 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003090 InitializedEntity InitEntity
3091 = Indirect? InitializedEntity::InitializeMember(Indirect)
3092 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003093 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003094 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003095
3096 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3097 ExprResult MemberInit =
3098 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003099
Douglas Gregor53c374f2010-12-07 00:41:46 +00003100 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003101 if (MemberInit.isInvalid())
3102 return true;
3103
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003104 if (Indirect)
3105 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3106 Indirect, Loc,
3107 Loc,
3108 MemberInit.get(),
3109 Loc);
3110 else
3111 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3112 Field, Loc, Loc,
3113 MemberInit.get(),
3114 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003115 return false;
3116 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003117
Sean Hunt1f2f3842011-05-17 00:19:05 +00003118 if (!Field->getParent()->isUnion()) {
3119 if (FieldBaseElementType->isReferenceType()) {
3120 SemaRef.Diag(Constructor->getLocation(),
3121 diag::err_uninitialized_member_in_ctor)
3122 << (int)Constructor->isImplicit()
3123 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3124 << 0 << Field->getDeclName();
3125 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3126 return true;
3127 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003128
Sean Hunt1f2f3842011-05-17 00:19:05 +00003129 if (FieldBaseElementType.isConstQualified()) {
3130 SemaRef.Diag(Constructor->getLocation(),
3131 diag::err_uninitialized_member_in_ctor)
3132 << (int)Constructor->isImplicit()
3133 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3134 << 1 << Field->getDeclName();
3135 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3136 return true;
3137 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003138 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003139
David Blaikie4e4d0842012-03-11 07:00:24 +00003140 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003141 FieldBaseElementType->isObjCRetainableType() &&
3142 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3143 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003144 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003145 // Default-initialize Objective-C pointers to NULL.
3146 CXXMemberInit
3147 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3148 Loc, Loc,
3149 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3150 Loc);
3151 return false;
3152 }
3153
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003154 // Nothing to initialize.
3155 CXXMemberInit = 0;
3156 return false;
3157}
John McCallf1860e52010-05-20 23:23:51 +00003158
3159namespace {
3160struct BaseAndFieldInfo {
3161 Sema &S;
3162 CXXConstructorDecl *Ctor;
3163 bool AnyErrorsInInits;
3164 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003165 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003166 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003167
3168 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3169 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003170 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3171 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003172 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003173 else if (Generated && Ctor->isMoveConstructor())
3174 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003175 else if (Ctor->getInheritedConstructor())
3176 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003177 else
3178 IIK = IIK_Default;
3179 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003180
3181 bool isImplicitCopyOrMove() const {
3182 switch (IIK) {
3183 case IIK_Copy:
3184 case IIK_Move:
3185 return true;
3186
3187 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003188 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003189 return false;
3190 }
David Blaikie30263482012-01-20 21:50:17 +00003191
3192 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003193 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003194
3195 bool addFieldInitializer(CXXCtorInitializer *Init) {
3196 AllToInit.push_back(Init);
3197
3198 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003199 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003200 S.UnusedPrivateFields.remove(Init->getAnyMember());
3201
3202 return false;
3203 }
John McCallf1860e52010-05-20 23:23:51 +00003204};
3205}
3206
Richard Smitha4950662011-09-19 13:34:43 +00003207/// \brief Determine whether the given indirect field declaration is somewhere
3208/// within an anonymous union.
3209static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3210 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3211 CEnd = F->chain_end();
3212 C != CEnd; ++C)
3213 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3214 if (Record->isUnion())
3215 return true;
3216
3217 return false;
3218}
3219
Douglas Gregorddb21472011-11-02 23:04:16 +00003220/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3221/// array type.
3222static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3223 if (T->isIncompleteArrayType())
3224 return true;
3225
3226 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3227 if (!ArrayT->getSize())
3228 return true;
3229
3230 T = ArrayT->getElementType();
3231 }
3232
3233 return false;
3234}
3235
Richard Smith7a614d82011-06-11 17:19:42 +00003236static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003237 FieldDecl *Field,
3238 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003239
Chandler Carruthe861c602010-06-30 02:59:29 +00003240 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003241 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3242 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003243
Richard Smith0b8220a2012-08-07 21:30:42 +00003244 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003245 // has a brace-or-equal-initializer, the entity is initialized as specified
3246 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003247 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003248 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3249 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003250 CXXCtorInitializer *Init;
3251 if (Indirect)
3252 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3253 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003254 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003255 SourceLocation());
3256 else
3257 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3258 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003259 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003260 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003261 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003262 }
3263
Richard Smithc115f632011-09-18 11:14:50 +00003264 // Don't build an implicit initializer for union members if none was
3265 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003266 if (Field->getParent()->isUnion() ||
3267 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003268 return false;
3269
Douglas Gregorddb21472011-11-02 23:04:16 +00003270 // Don't initialize incomplete or zero-length arrays.
3271 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3272 return false;
3273
John McCallf1860e52010-05-20 23:23:51 +00003274 // Don't try to build an implicit initializer if there were semantic
3275 // errors in any of the initializers (and therefore we might be
3276 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003277 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003278 return false;
3279
Sean Huntcbb67482011-01-08 20:30:50 +00003280 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003281 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3282 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003283 return true;
John McCallf1860e52010-05-20 23:23:51 +00003284
Richard Smith0b8220a2012-08-07 21:30:42 +00003285 if (!Init)
3286 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003287
Richard Smith0b8220a2012-08-07 21:30:42 +00003288 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003289}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003290
3291bool
3292Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3293 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003294 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003295 Constructor->setNumCtorInitializers(1);
3296 CXXCtorInitializer **initializer =
3297 new (Context) CXXCtorInitializer*[1];
3298 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3299 Constructor->setCtorInitializers(initializer);
3300
Sean Huntb76af9c2011-05-03 23:05:34 +00003301 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003302 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003303 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3304 }
3305
Sean Huntc1598702011-05-05 00:05:47 +00003306 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003307
Sean Hunt059ce0d2011-05-01 07:04:31 +00003308 return false;
3309}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003310
David Blaikie93c86172013-01-17 05:26:25 +00003311bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3312 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003313 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003314 // Just store the initializers as written, they will be checked during
3315 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003316 if (!Initializers.empty()) {
3317 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003318 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003319 new (Context) CXXCtorInitializer*[Initializers.size()];
3320 memcpy(baseOrMemberInitializers, Initializers.data(),
3321 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003322 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003323 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003324
3325 // Let template instantiation know whether we had errors.
3326 if (AnyErrors)
3327 Constructor->setInvalidDecl();
3328
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003329 return false;
3330 }
3331
John McCallf1860e52010-05-20 23:23:51 +00003332 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003333
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003334 // We need to build the initializer AST according to order of construction
3335 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003336 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003337 if (!ClassDecl)
3338 return true;
3339
Eli Friedman80c30da2009-11-09 19:20:36 +00003340 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003341
David Blaikie93c86172013-01-17 05:26:25 +00003342 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003343 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003344
3345 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003346 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003347 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003348 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003349 }
3350
Anders Carlsson711f34a2010-04-21 19:52:01 +00003351 // Keep track of the direct virtual bases.
3352 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3353 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3354 E = ClassDecl->bases_end(); I != E; ++I) {
3355 if (I->isVirtual())
3356 DirectVBases.insert(I);
3357 }
3358
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003359 // Push virtual bases before others.
3360 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3361 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3362
Sean Huntcbb67482011-01-08 20:30:50 +00003363 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003364 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3365 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003366 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003367 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003368 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003369 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003370 VBase, IsInheritedVirtualBase,
3371 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003372 HadError = true;
3373 continue;
3374 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003375
John McCallf1860e52010-05-20 23:23:51 +00003376 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003377 }
3378 }
Mike Stump1eb44332009-09-09 15:08:12 +00003379
John McCallf1860e52010-05-20 23:23:51 +00003380 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003381 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3382 E = ClassDecl->bases_end(); Base != E; ++Base) {
3383 // Virtuals are in the virtual base list and already constructed.
3384 if (Base->isVirtual())
3385 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003386
Sean Huntcbb67482011-01-08 20:30:50 +00003387 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003388 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3389 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003390 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003391 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003392 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003393 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003394 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003395 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003396 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003397 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003398
John McCallf1860e52010-05-20 23:23:51 +00003399 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003400 }
3401 }
Mike Stump1eb44332009-09-09 15:08:12 +00003402
John McCallf1860e52010-05-20 23:23:51 +00003403 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003404 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3405 MemEnd = ClassDecl->decls_end();
3406 Mem != MemEnd; ++Mem) {
3407 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003408 // C++ [class.bit]p2:
3409 // A declaration for a bit-field that omits the identifier declares an
3410 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3411 // initialized.
3412 if (F->isUnnamedBitfield())
3413 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003414
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003415 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003416 // handle anonymous struct/union fields based on their individual
3417 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003418 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003419 continue;
3420
3421 if (CollectFieldInitializer(*this, Info, F))
3422 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003423 continue;
3424 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003425
3426 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003427 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003428 continue;
3429
3430 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3431 if (F->getType()->isIncompleteArrayType()) {
3432 assert(ClassDecl->hasFlexibleArrayMember() &&
3433 "Incomplete array type is not valid");
3434 continue;
3435 }
3436
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003437 // Initialize each field of an anonymous struct individually.
3438 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3439 HadError = true;
3440
3441 continue;
3442 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003443 }
Mike Stump1eb44332009-09-09 15:08:12 +00003444
David Blaikie93c86172013-01-17 05:26:25 +00003445 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003446 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003447 Constructor->setNumCtorInitializers(NumInitializers);
3448 CXXCtorInitializer **baseOrMemberInitializers =
3449 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003450 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003451 NumInitializers * sizeof(CXXCtorInitializer*));
3452 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003453
John McCallef027fe2010-03-16 21:39:52 +00003454 // Constructors implicitly reference the base and member
3455 // destructors.
3456 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3457 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003458 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003459
3460 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003461}
3462
David Blaikieee000bb2013-01-17 08:49:22 +00003463static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003464 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003465 const RecordDecl *RD = RT->getDecl();
3466 if (RD->isAnonymousStructOrUnion()) {
3467 for (RecordDecl::field_iterator Field = RD->field_begin(),
3468 E = RD->field_end(); Field != E; ++Field)
3469 PopulateKeysForFields(*Field, IdealInits);
3470 return;
3471 }
Eli Friedman6347f422009-07-21 19:28:10 +00003472 }
David Blaikieee000bb2013-01-17 08:49:22 +00003473 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003474}
3475
Anders Carlssonea356fb2010-04-02 05:42:15 +00003476static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003477 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003478}
3479
Anders Carlssonea356fb2010-04-02 05:42:15 +00003480static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003481 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003482 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003483 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003484
David Blaikieee000bb2013-01-17 08:49:22 +00003485 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003486}
3487
David Blaikie93c86172013-01-17 05:26:25 +00003488static void DiagnoseBaseOrMemInitializerOrder(
3489 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3490 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003491 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003492 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003493
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003494 // Don't check initializers order unless the warning is enabled at the
3495 // location of at least one initializer.
3496 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003497 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003498 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003499 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3500 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003501 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003502 ShouldCheckOrder = true;
3503 break;
3504 }
3505 }
3506 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003507 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003508
John McCalld6ca8da2010-04-10 07:37:23 +00003509 // Build the list of bases and members in the order that they'll
3510 // actually be initialized. The explicit initializers should be in
3511 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003512 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003513
Anders Carlsson071d6102010-04-02 03:38:04 +00003514 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3515
John McCalld6ca8da2010-04-10 07:37:23 +00003516 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003517 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003518 ClassDecl->vbases_begin(),
3519 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003520 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003521
John McCalld6ca8da2010-04-10 07:37:23 +00003522 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003523 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003524 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003525 if (Base->isVirtual())
3526 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003527 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003528 }
Mike Stump1eb44332009-09-09 15:08:12 +00003529
John McCalld6ca8da2010-04-10 07:37:23 +00003530 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003531 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003532 E = ClassDecl->field_end(); Field != E; ++Field) {
3533 if (Field->isUnnamedBitfield())
3534 continue;
3535
David Blaikieee000bb2013-01-17 08:49:22 +00003536 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003537 }
3538
John McCalld6ca8da2010-04-10 07:37:23 +00003539 unsigned NumIdealInits = IdealInitKeys.size();
3540 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003541
Sean Huntcbb67482011-01-08 20:30:50 +00003542 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003543 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003544 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003545 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003546
3547 // Scan forward to try to find this initializer in the idealized
3548 // initializers list.
3549 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3550 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003551 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003552
3553 // If we didn't find this initializer, it must be because we
3554 // scanned past it on a previous iteration. That can only
3555 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003556 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003557 Sema::SemaDiagnosticBuilder D =
3558 SemaRef.Diag(PrevInit->getSourceLocation(),
3559 diag::warn_initializer_out_of_order);
3560
Francois Pichet00eb3f92010-12-04 09:14:42 +00003561 if (PrevInit->isAnyMemberInitializer())
3562 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003563 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003564 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003565
Francois Pichet00eb3f92010-12-04 09:14:42 +00003566 if (Init->isAnyMemberInitializer())
3567 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003568 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003569 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003570
3571 // Move back to the initializer's location in the ideal list.
3572 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3573 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003574 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003575
3576 assert(IdealIndex != NumIdealInits &&
3577 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003578 }
John McCalld6ca8da2010-04-10 07:37:23 +00003579
3580 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003581 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003582}
3583
John McCall3c3ccdb2010-04-10 09:28:51 +00003584namespace {
3585bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003586 CXXCtorInitializer *Init,
3587 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003588 if (!PrevInit) {
3589 PrevInit = Init;
3590 return false;
3591 }
3592
Douglas Gregordc392c12013-03-25 23:28:23 +00003593 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003594 S.Diag(Init->getSourceLocation(),
3595 diag::err_multiple_mem_initialization)
3596 << Field->getDeclName()
3597 << Init->getSourceRange();
3598 else {
John McCallf4c73712011-01-19 06:33:43 +00003599 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003600 assert(BaseClass && "neither field nor base");
3601 S.Diag(Init->getSourceLocation(),
3602 diag::err_multiple_base_initialization)
3603 << QualType(BaseClass, 0)
3604 << Init->getSourceRange();
3605 }
3606 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3607 << 0 << PrevInit->getSourceRange();
3608
3609 return true;
3610}
3611
Sean Huntcbb67482011-01-08 20:30:50 +00003612typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003613typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3614
3615bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003616 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003617 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003618 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003619 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003620 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003621
3622 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003623 if (Parent->isUnion()) {
3624 UnionEntry &En = Unions[Parent];
3625 if (En.first && En.first != Child) {
3626 S.Diag(Init->getSourceLocation(),
3627 diag::err_multiple_mem_union_initialization)
3628 << Field->getDeclName()
3629 << Init->getSourceRange();
3630 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3631 << 0 << En.second->getSourceRange();
3632 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003633 }
3634 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003635 En.first = Child;
3636 En.second = Init;
3637 }
David Blaikie6fe29652011-11-17 06:01:57 +00003638 if (!Parent->isAnonymousStructOrUnion())
3639 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003640 }
3641
3642 Child = Parent;
3643 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003644 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003645
3646 return false;
3647}
3648}
3649
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003650/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003651void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003652 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003653 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003654 bool AnyErrors) {
3655 if (!ConstructorDecl)
3656 return;
3657
3658 AdjustDeclIfTemplate(ConstructorDecl);
3659
3660 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003661 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003662
3663 if (!Constructor) {
3664 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3665 return;
3666 }
3667
John McCall3c3ccdb2010-04-10 09:28:51 +00003668 // Mapping for the duplicate initializers check.
3669 // For member initializers, this is keyed with a FieldDecl*.
3670 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003671 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003672
3673 // Mapping for the inconsistent anonymous-union initializers check.
3674 RedundantUnionMap MemberUnions;
3675
Anders Carlssonea356fb2010-04-02 05:42:15 +00003676 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003677 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003678 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003679
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003680 // Set the source order index.
3681 Init->setSourceOrder(i);
3682
Francois Pichet00eb3f92010-12-04 09:14:42 +00003683 if (Init->isAnyMemberInitializer()) {
3684 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003685 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3686 CheckRedundantUnionInit(*this, Init, MemberUnions))
3687 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003688 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003689 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3690 if (CheckRedundantInit(*this, Init, Members[Key]))
3691 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003692 } else {
3693 assert(Init->isDelegatingInitializer());
3694 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003695 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003696 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003697 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003698 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003699 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003700 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003701 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003702 // Return immediately as the initializer is set.
3703 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003704 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003705 }
3706
Anders Carlssonea356fb2010-04-02 05:42:15 +00003707 if (HadError)
3708 return;
3709
David Blaikie93c86172013-01-17 05:26:25 +00003710 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003711
David Blaikie93c86172013-01-17 05:26:25 +00003712 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003713}
3714
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003715void
John McCallef027fe2010-03-16 21:39:52 +00003716Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3717 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003718 // Ignore dependent contexts. Also ignore unions, since their members never
3719 // have destructors implicitly called.
3720 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003721 return;
John McCall58e6f342010-03-16 05:22:47 +00003722
3723 // FIXME: all the access-control diagnostics are positioned on the
3724 // field/base declaration. That's probably good; that said, the
3725 // user might reasonably want to know why the destructor is being
3726 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003727
Anders Carlsson9f853df2009-11-17 04:44:12 +00003728 // Non-static data members.
3729 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3730 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003731 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003732 if (Field->isInvalidDecl())
3733 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003734
3735 // Don't destroy incomplete or zero-length arrays.
3736 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3737 continue;
3738
Anders Carlsson9f853df2009-11-17 04:44:12 +00003739 QualType FieldType = Context.getBaseElementType(Field->getType());
3740
3741 const RecordType* RT = FieldType->getAs<RecordType>();
3742 if (!RT)
3743 continue;
3744
3745 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003746 if (FieldClassDecl->isInvalidDecl())
3747 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003748 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003749 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003750 // The destructor for an implicit anonymous union member is never invoked.
3751 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3752 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003753
Douglas Gregordb89f282010-07-01 22:47:18 +00003754 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003755 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003756 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003757 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003758 << Field->getDeclName()
3759 << FieldType);
3760
Eli Friedman5f2987c2012-02-02 03:46:19 +00003761 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003762 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003763 }
3764
John McCall58e6f342010-03-16 05:22:47 +00003765 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3766
Anders Carlsson9f853df2009-11-17 04:44:12 +00003767 // Bases.
3768 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3769 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003770 // Bases are always records in a well-formed non-dependent class.
3771 const RecordType *RT = Base->getType()->getAs<RecordType>();
3772
3773 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003774 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003775 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003776
John McCall58e6f342010-03-16 05:22:47 +00003777 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003778 // If our base class is invalid, we probably can't get its dtor anyway.
3779 if (BaseClassDecl->isInvalidDecl())
3780 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003781 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003782 continue;
John McCall58e6f342010-03-16 05:22:47 +00003783
Douglas Gregordb89f282010-07-01 22:47:18 +00003784 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003785 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003786
3787 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003788 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003789 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003790 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003791 << Base->getSourceRange(),
3792 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003793
Eli Friedman5f2987c2012-02-02 03:46:19 +00003794 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003795 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003796 }
3797
3798 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003799 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3800 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003801
3802 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003803 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003804
3805 // Ignore direct virtual bases.
3806 if (DirectVirtualBases.count(RT))
3807 continue;
3808
John McCall58e6f342010-03-16 05:22:47 +00003809 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003810 // If our base class is invalid, we probably can't get its dtor anyway.
3811 if (BaseClassDecl->isInvalidDecl())
3812 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003813 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003814 continue;
John McCall58e6f342010-03-16 05:22:47 +00003815
Douglas Gregordb89f282010-07-01 22:47:18 +00003816 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003817 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00003818 if (CheckDestructorAccess(
3819 ClassDecl->getLocation(), Dtor,
3820 PDiag(diag::err_access_dtor_vbase)
3821 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3822 Context.getTypeDeclType(ClassDecl)) ==
3823 AR_accessible) {
3824 CheckDerivedToBaseConversion(
3825 Context.getTypeDeclType(ClassDecl), VBase->getType(),
3826 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3827 SourceRange(), DeclarationName(), 0);
3828 }
John McCall58e6f342010-03-16 05:22:47 +00003829
Eli Friedman5f2987c2012-02-02 03:46:19 +00003830 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003831 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003832 }
3833}
3834
John McCalld226f652010-08-21 09:40:31 +00003835void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003836 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003837 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003838
Mike Stump1eb44332009-09-09 15:08:12 +00003839 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003840 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003841 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003842}
3843
Mike Stump1eb44332009-09-09 15:08:12 +00003844bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003845 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003846 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3847 unsigned DiagID;
3848 AbstractDiagSelID SelID;
3849
3850 public:
3851 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3852 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3853
3854 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003855 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003856 if (SelID == -1)
3857 S.Diag(Loc, DiagID) << T;
3858 else
3859 S.Diag(Loc, DiagID) << SelID << T;
3860 }
3861 } Diagnoser(DiagID, SelID);
3862
3863 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003864}
3865
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003866bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003867 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003868 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003869 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003870
Anders Carlsson11f21a02009-03-23 19:10:31 +00003871 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003872 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003873
Ted Kremenek6217b802009-07-29 21:53:49 +00003874 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003875 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003876 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003877 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003878
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003879 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003880 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003881 }
Mike Stump1eb44332009-09-09 15:08:12 +00003882
Ted Kremenek6217b802009-07-29 21:53:49 +00003883 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003884 if (!RT)
3885 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003886
John McCall86ff3082010-02-04 22:26:26 +00003887 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003888
John McCall94c3b562010-08-18 09:41:07 +00003889 // We can't answer whether something is abstract until it has a
3890 // definition. If it's currently being defined, we'll walk back
3891 // over all the declarations when we have a full definition.
3892 const CXXRecordDecl *Def = RD->getDefinition();
3893 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003894 return false;
3895
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003896 if (!RD->isAbstract())
3897 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003898
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003899 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003900 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003901
John McCall94c3b562010-08-18 09:41:07 +00003902 return true;
3903}
3904
3905void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3906 // Check if we've already emitted the list of pure virtual functions
3907 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003908 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003909 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003910
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003911 CXXFinalOverriderMap FinalOverriders;
3912 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003913
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003914 // Keep a set of seen pure methods so we won't diagnose the same method
3915 // more than once.
3916 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3917
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003918 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3919 MEnd = FinalOverriders.end();
3920 M != MEnd;
3921 ++M) {
3922 for (OverridingMethods::iterator SO = M->second.begin(),
3923 SOEnd = M->second.end();
3924 SO != SOEnd; ++SO) {
3925 // C++ [class.abstract]p4:
3926 // A class is abstract if it contains or inherits at least one
3927 // pure virtual function for which the final overrider is pure
3928 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003929
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003930 //
3931 if (SO->second.size() != 1)
3932 continue;
3933
3934 if (!SO->second.front().Method->isPure())
3935 continue;
3936
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003937 if (!SeenPureMethods.insert(SO->second.front().Method))
3938 continue;
3939
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003940 Diag(SO->second.front().Method->getLocation(),
3941 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003942 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003943 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003944 }
3945
3946 if (!PureVirtualClassDiagSet)
3947 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3948 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003949}
3950
Anders Carlsson8211eff2009-03-24 01:19:16 +00003951namespace {
John McCall94c3b562010-08-18 09:41:07 +00003952struct AbstractUsageInfo {
3953 Sema &S;
3954 CXXRecordDecl *Record;
3955 CanQualType AbstractType;
3956 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003957
John McCall94c3b562010-08-18 09:41:07 +00003958 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3959 : S(S), Record(Record),
3960 AbstractType(S.Context.getCanonicalType(
3961 S.Context.getTypeDeclType(Record))),
3962 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003963
John McCall94c3b562010-08-18 09:41:07 +00003964 void DiagnoseAbstractType() {
3965 if (Invalid) return;
3966 S.DiagnoseAbstractType(Record);
3967 Invalid = true;
3968 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003969
John McCall94c3b562010-08-18 09:41:07 +00003970 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3971};
3972
3973struct CheckAbstractUsage {
3974 AbstractUsageInfo &Info;
3975 const NamedDecl *Ctx;
3976
3977 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3978 : Info(Info), Ctx(Ctx) {}
3979
3980 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3981 switch (TL.getTypeLocClass()) {
3982#define ABSTRACT_TYPELOC(CLASS, PARENT)
3983#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003984 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003985#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003986 }
John McCall94c3b562010-08-18 09:41:07 +00003987 }
Mike Stump1eb44332009-09-09 15:08:12 +00003988
John McCall94c3b562010-08-18 09:41:07 +00003989 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3990 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3991 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003992 if (!TL.getArg(I))
3993 continue;
3994
John McCall94c3b562010-08-18 09:41:07 +00003995 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3996 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003997 }
John McCall94c3b562010-08-18 09:41:07 +00003998 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003999
John McCall94c3b562010-08-18 09:41:07 +00004000 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4001 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4002 }
Mike Stump1eb44332009-09-09 15:08:12 +00004003
John McCall94c3b562010-08-18 09:41:07 +00004004 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4005 // Visit the type parameters from a permissive context.
4006 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4007 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4008 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4009 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4010 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4011 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004012 }
John McCall94c3b562010-08-18 09:41:07 +00004013 }
Mike Stump1eb44332009-09-09 15:08:12 +00004014
John McCall94c3b562010-08-18 09:41:07 +00004015 // Visit pointee types from a permissive context.
4016#define CheckPolymorphic(Type) \
4017 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4018 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4019 }
4020 CheckPolymorphic(PointerTypeLoc)
4021 CheckPolymorphic(ReferenceTypeLoc)
4022 CheckPolymorphic(MemberPointerTypeLoc)
4023 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004024 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004025
John McCall94c3b562010-08-18 09:41:07 +00004026 /// Handle all the types we haven't given a more specific
4027 /// implementation for above.
4028 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4029 // Every other kind of type that we haven't called out already
4030 // that has an inner type is either (1) sugar or (2) contains that
4031 // inner type in some way as a subobject.
4032 if (TypeLoc Next = TL.getNextTypeLoc())
4033 return Visit(Next, Sel);
4034
4035 // If there's no inner type and we're in a permissive context,
4036 // don't diagnose.
4037 if (Sel == Sema::AbstractNone) return;
4038
4039 // Check whether the type matches the abstract type.
4040 QualType T = TL.getType();
4041 if (T->isArrayType()) {
4042 Sel = Sema::AbstractArrayType;
4043 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004044 }
John McCall94c3b562010-08-18 09:41:07 +00004045 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4046 if (CT != Info.AbstractType) return;
4047
4048 // It matched; do some magic.
4049 if (Sel == Sema::AbstractArrayType) {
4050 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4051 << T << TL.getSourceRange();
4052 } else {
4053 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4054 << Sel << T << TL.getSourceRange();
4055 }
4056 Info.DiagnoseAbstractType();
4057 }
4058};
4059
4060void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4061 Sema::AbstractDiagSelID Sel) {
4062 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4063}
4064
4065}
4066
4067/// Check for invalid uses of an abstract type in a method declaration.
4068static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4069 CXXMethodDecl *MD) {
4070 // No need to do the check on definitions, which require that
4071 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004072 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004073 return;
4074
4075 // For safety's sake, just ignore it if we don't have type source
4076 // information. This should never happen for non-implicit methods,
4077 // but...
4078 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4079 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4080}
4081
4082/// Check for invalid uses of an abstract type within a class definition.
4083static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4084 CXXRecordDecl *RD) {
4085 for (CXXRecordDecl::decl_iterator
4086 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4087 Decl *D = *I;
4088 if (D->isImplicit()) continue;
4089
4090 // Methods and method templates.
4091 if (isa<CXXMethodDecl>(D)) {
4092 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4093 } else if (isa<FunctionTemplateDecl>(D)) {
4094 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4095 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4096
4097 // Fields and static variables.
4098 } else if (isa<FieldDecl>(D)) {
4099 FieldDecl *FD = cast<FieldDecl>(D);
4100 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4101 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4102 } else if (isa<VarDecl>(D)) {
4103 VarDecl *VD = cast<VarDecl>(D);
4104 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4105 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4106
4107 // Nested classes and class templates.
4108 } else if (isa<CXXRecordDecl>(D)) {
4109 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4110 } else if (isa<ClassTemplateDecl>(D)) {
4111 CheckAbstractClassUsage(Info,
4112 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4113 }
4114 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004115}
4116
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004117/// \brief Perform semantic checks on a class definition that has been
4118/// completing, introducing implicitly-declared members, checking for
4119/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004120void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004121 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004122 return;
4123
John McCall94c3b562010-08-18 09:41:07 +00004124 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4125 AbstractUsageInfo Info(*this, Record);
4126 CheckAbstractClassUsage(Info, Record);
4127 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004128
4129 // If this is not an aggregate type and has no user-declared constructor,
4130 // complain about any non-static data members of reference or const scalar
4131 // type, since they will never get initializers.
4132 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004133 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4134 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004135 bool Complained = false;
4136 for (RecordDecl::field_iterator F = Record->field_begin(),
4137 FEnd = Record->field_end();
4138 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004139 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004140 continue;
4141
Douglas Gregor325e5932010-04-15 00:00:53 +00004142 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004143 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004144 if (!Complained) {
4145 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4146 << Record->getTagKind() << Record;
4147 Complained = true;
4148 }
4149
4150 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4151 << F->getType()->isReferenceType()
4152 << F->getDeclName();
4153 }
4154 }
4155 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004156
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004157 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004158 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004159
4160 if (Record->getIdentifier()) {
4161 // C++ [class.mem]p13:
4162 // If T is the name of a class, then each of the following shall have a
4163 // name different from T:
4164 // - every member of every anonymous union that is a member of class T.
4165 //
4166 // C++ [class.mem]p14:
4167 // In addition, if class T has a user-declared constructor (12.1), every
4168 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004169 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4170 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4171 ++I) {
4172 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004173 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4174 isa<IndirectFieldDecl>(D)) {
4175 Diag(D->getLocation(), diag::err_member_name_of_class)
4176 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004177 break;
4178 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004179 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004180 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004181
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004182 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004183 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004184 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004185 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004186 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4187 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4188 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004189
David Blaikieb6b5b972012-09-21 03:21:07 +00004190 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4191 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4192 DiagnoseAbstractType(Record);
4193 }
4194
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004195 if (!Record->isDependentType()) {
4196 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4197 MEnd = Record->method_end();
4198 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004199 // See if a method overloads virtual methods in a base
4200 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004201 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004202 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004203
4204 // Check whether the explicitly-defaulted special members are valid.
4205 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4206 CheckExplicitlyDefaultedSpecialMember(*M);
4207
4208 // For an explicitly defaulted or deleted special member, we defer
4209 // determining triviality until the class is complete. That time is now!
4210 if (!M->isImplicit() && !M->isUserProvided()) {
4211 CXXSpecialMember CSM = getSpecialMember(*M);
4212 if (CSM != CXXInvalid) {
4213 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4214
4215 // Inform the class that we've finished declaring this member.
4216 Record->finishedDefaultedOrDeletedMember(*M);
4217 }
4218 }
4219 }
4220 }
4221
4222 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4223 // function that is not a constructor declares that member function to be
4224 // const. [...] The class of which that function is a member shall be
4225 // a literal type.
4226 //
4227 // If the class has virtual bases, any constexpr members will already have
4228 // been diagnosed by the checks performed on the member declaration, so
4229 // suppress this (less useful) diagnostic.
4230 //
4231 // We delay this until we know whether an explicitly-defaulted (or deleted)
4232 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004233 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004234 !Record->isLiteral() && !Record->getNumVBases()) {
4235 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4236 MEnd = Record->method_end();
4237 M != MEnd; ++M) {
4238 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4239 switch (Record->getTemplateSpecializationKind()) {
4240 case TSK_ImplicitInstantiation:
4241 case TSK_ExplicitInstantiationDeclaration:
4242 case TSK_ExplicitInstantiationDefinition:
4243 // If a template instantiates to a non-literal type, but its members
4244 // instantiate to constexpr functions, the template is technically
4245 // ill-formed, but we allow it for sanity.
4246 continue;
4247
4248 case TSK_Undeclared:
4249 case TSK_ExplicitSpecialization:
4250 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4251 diag::err_constexpr_method_non_literal);
4252 break;
4253 }
4254
4255 // Only produce one error per class.
4256 break;
4257 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004258 }
4259 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004260
Richard Smith07b0fdc2013-03-18 21:12:30 +00004261 // Declare inheriting constructors. We do this eagerly here because:
4262 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004263 // constructors from different classes.
4264 // - The lazy declaration of the other implicit constructors is so as to not
4265 // waste space and performance on classes that are not meant to be
4266 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004267 // have inheriting constructors.
4268 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004269}
4270
Richard Smith7756afa2012-06-10 05:43:50 +00004271/// Is the special member function which would be selected to perform the
4272/// specified operation on the specified class type a constexpr constructor?
4273static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4274 Sema::CXXSpecialMember CSM,
4275 bool ConstArg) {
4276 Sema::SpecialMemberOverloadResult *SMOR =
4277 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4278 false, false, false, false);
4279 if (!SMOR || !SMOR->getMethod())
4280 // A constructor we wouldn't select can't be "involved in initializing"
4281 // anything.
4282 return true;
4283 return SMOR->getMethod()->isConstexpr();
4284}
4285
4286/// Determine whether the specified special member function would be constexpr
4287/// if it were implicitly defined.
4288static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4289 Sema::CXXSpecialMember CSM,
4290 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004291 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004292 return false;
4293
4294 // C++11 [dcl.constexpr]p4:
4295 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004296 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004297 switch (CSM) {
4298 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004299 // Since default constructor lookup is essentially trivial (and cannot
4300 // involve, for instance, template instantiation), we compute whether a
4301 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4302 //
4303 // This is important for performance; we need to know whether the default
4304 // constructor is constexpr to determine whether the type is a literal type.
4305 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4306
Richard Smith7756afa2012-06-10 05:43:50 +00004307 case Sema::CXXCopyConstructor:
4308 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004309 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004310 break;
4311
4312 case Sema::CXXCopyAssignment:
4313 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004314 if (!S.getLangOpts().CPlusPlus1y)
4315 return false;
4316 // In C++1y, we need to perform overload resolution.
4317 Ctor = false;
4318 break;
4319
Richard Smith7756afa2012-06-10 05:43:50 +00004320 case Sema::CXXDestructor:
4321 case Sema::CXXInvalid:
4322 return false;
4323 }
4324
4325 // -- if the class is a non-empty union, or for each non-empty anonymous
4326 // union member of a non-union class, exactly one non-static data member
4327 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004328 //
4329 // If we squint, this is guaranteed, since exactly one non-static data member
4330 // will be initialized (if the constructor isn't deleted), we just don't know
4331 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004332 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004333 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004334
4335 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004336 if (Ctor && ClassDecl->getNumVBases())
4337 return false;
4338
4339 // C++1y [class.copy]p26:
4340 // -- [the class] is a literal type, and
4341 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004342 return false;
4343
4344 // -- every constructor involved in initializing [...] base class
4345 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004346 // -- the assignment operator selected to copy/move each direct base
4347 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004348 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4349 BEnd = ClassDecl->bases_end();
4350 B != BEnd; ++B) {
4351 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4352 if (!BaseType) continue;
4353
4354 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4355 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4356 return false;
4357 }
4358
4359 // -- every constructor involved in initializing non-static data members
4360 // [...] shall be a constexpr constructor;
4361 // -- every non-static data member and base class sub-object shall be
4362 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004363 // -- for each non-stastic data member of X that is of class type (or array
4364 // thereof), the assignment operator selected to copy/move that member is
4365 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004366 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4367 FEnd = ClassDecl->field_end();
4368 F != FEnd; ++F) {
4369 if (F->isInvalidDecl())
4370 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004371 if (const RecordType *RecordTy =
4372 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004373 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4374 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4375 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004376 }
4377 }
4378
4379 // All OK, it's constexpr!
4380 return true;
4381}
4382
Richard Smithb9d0b762012-07-27 04:22:15 +00004383static Sema::ImplicitExceptionSpecification
4384computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4385 switch (S.getSpecialMember(MD)) {
4386 case Sema::CXXDefaultConstructor:
4387 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4388 case Sema::CXXCopyConstructor:
4389 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4390 case Sema::CXXCopyAssignment:
4391 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4392 case Sema::CXXMoveConstructor:
4393 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4394 case Sema::CXXMoveAssignment:
4395 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4396 case Sema::CXXDestructor:
4397 return S.ComputeDefaultedDtorExceptionSpec(MD);
4398 case Sema::CXXInvalid:
4399 break;
4400 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004401 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4402 "only special members have implicit exception specs");
4403 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004404}
4405
Richard Smithdd25e802012-07-30 23:48:14 +00004406static void
4407updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4408 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4409 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4410 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004411 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4412 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004413}
4414
Richard Smithb9d0b762012-07-27 04:22:15 +00004415void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4416 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4417 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4418 return;
4419
Richard Smithdd25e802012-07-30 23:48:14 +00004420 // Evaluate the exception specification.
4421 ImplicitExceptionSpecification ExceptSpec =
4422 computeImplicitExceptionSpec(*this, Loc, MD);
4423
4424 // Update the type of the special member to use it.
4425 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4426
4427 // A user-provided destructor can be defined outside the class. When that
4428 // happens, be sure to update the exception specification on both
4429 // declarations.
4430 const FunctionProtoType *CanonicalFPT =
4431 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4432 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4433 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4434 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004435}
4436
Richard Smith3003e1d2012-05-15 04:39:51 +00004437void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4438 CXXRecordDecl *RD = MD->getParent();
4439 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004440
Richard Smith3003e1d2012-05-15 04:39:51 +00004441 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4442 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004443
4444 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004445 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004446 bool First = MD == MD->getCanonicalDecl();
4447
4448 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004449
4450 // C++11 [dcl.fct.def.default]p1:
4451 // A function that is explicitly defaulted shall
4452 // -- be a special member function (checked elsewhere),
4453 // -- have the same type (except for ref-qualifiers, and except that a
4454 // copy operation can take a non-const reference) as an implicit
4455 // declaration, and
4456 // -- not have default arguments.
4457 unsigned ExpectedParams = 1;
4458 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4459 ExpectedParams = 0;
4460 if (MD->getNumParams() != ExpectedParams) {
4461 // This also checks for default arguments: a copy or move constructor with a
4462 // default argument is classified as a default constructor, and assignment
4463 // operations and destructors can't have default arguments.
4464 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4465 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004466 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004467 } else if (MD->isVariadic()) {
4468 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4469 << CSM << MD->getSourceRange();
4470 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004471 }
4472
Richard Smith3003e1d2012-05-15 04:39:51 +00004473 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004474
Richard Smith7756afa2012-06-10 05:43:50 +00004475 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004476 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004477 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004478 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004479 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004480
Richard Smith3003e1d2012-05-15 04:39:51 +00004481 QualType ReturnType = Context.VoidTy;
4482 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4483 // Check for return type matching.
4484 ReturnType = Type->getResultType();
4485 QualType ExpectedReturnType =
4486 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4487 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4488 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4489 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4490 HadError = true;
4491 }
4492
4493 // A defaulted special member cannot have cv-qualifiers.
4494 if (Type->getTypeQuals()) {
4495 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004496 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004497 HadError = true;
4498 }
4499 }
4500
4501 // Check for parameter type matching.
4502 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004503 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004504 if (ExpectedParams && ArgType->isReferenceType()) {
4505 // Argument must be reference to possibly-const T.
4506 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004507 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004508
4509 if (ReferentType.isVolatileQualified()) {
4510 Diag(MD->getLocation(),
4511 diag::err_defaulted_special_member_volatile_param) << CSM;
4512 HadError = true;
4513 }
4514
Richard Smith7756afa2012-06-10 05:43:50 +00004515 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004516 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4517 Diag(MD->getLocation(),
4518 diag::err_defaulted_special_member_copy_const_param)
4519 << (CSM == CXXCopyAssignment);
4520 // FIXME: Explain why this special member can't be const.
4521 } else {
4522 Diag(MD->getLocation(),
4523 diag::err_defaulted_special_member_move_const_param)
4524 << (CSM == CXXMoveAssignment);
4525 }
4526 HadError = true;
4527 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004528 } else if (ExpectedParams) {
4529 // A copy assignment operator can take its argument by value, but a
4530 // defaulted one cannot.
4531 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004532 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004533 HadError = true;
4534 }
Sean Huntbe631222011-05-17 20:44:43 +00004535
Richard Smith61802452011-12-22 02:22:31 +00004536 // C++11 [dcl.fct.def.default]p2:
4537 // An explicitly-defaulted function may be declared constexpr only if it
4538 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004539 // Do not apply this rule to members of class templates, since core issue 1358
4540 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004541 // functions which cannot be constexpr (for non-constructors in C++11 and for
4542 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004543 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4544 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004545 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4546 : isa<CXXConstructorDecl>(MD)) &&
4547 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004548 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4549 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004550 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004551 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004552 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004553
Richard Smith61802452011-12-22 02:22:31 +00004554 // and may have an explicit exception-specification only if it is compatible
4555 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004556 if (Type->hasExceptionSpec()) {
4557 // Delay the check if this is the first declaration of the special member,
4558 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004559 if (First) {
4560 // If the exception specification needs to be instantiated, do so now,
4561 // before we clobber it with an EST_Unevaluated specification below.
4562 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4563 InstantiateExceptionSpec(MD->getLocStart(), MD);
4564 Type = MD->getType()->getAs<FunctionProtoType>();
4565 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004566 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004567 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004568 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4569 }
Richard Smith61802452011-12-22 02:22:31 +00004570
4571 // If a function is explicitly defaulted on its first declaration,
4572 if (First) {
4573 // -- it is implicitly considered to be constexpr if the implicit
4574 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004575 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004576
Richard Smith3003e1d2012-05-15 04:39:51 +00004577 // -- it is implicitly considered to have the same exception-specification
4578 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004579 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4580 EPI.ExceptionSpecType = EST_Unevaluated;
4581 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004582 MD->setType(Context.getFunctionType(ReturnType,
4583 ArrayRef<QualType>(&ArgType,
4584 ExpectedParams),
4585 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004586 }
4587
Richard Smith3003e1d2012-05-15 04:39:51 +00004588 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004589 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004590 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004591 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004592 // C++11 [dcl.fct.def.default]p4:
4593 // [For a] user-provided explicitly-defaulted function [...] if such a
4594 // function is implicitly defined as deleted, the program is ill-formed.
4595 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4596 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004597 }
4598 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004599
Richard Smith3003e1d2012-05-15 04:39:51 +00004600 if (HadError)
4601 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004602}
4603
Richard Smith1d28caf2012-12-11 01:14:52 +00004604/// Check whether the exception specification provided for an
4605/// explicitly-defaulted special member matches the exception specification
4606/// that would have been generated for an implicit special member, per
4607/// C++11 [dcl.fct.def.default]p2.
4608void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4609 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4610 // Compute the implicit exception specification.
4611 FunctionProtoType::ExtProtoInfo EPI;
4612 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4613 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004614 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004615
4616 // Ensure that it matches.
4617 CheckEquivalentExceptionSpec(
4618 PDiag(diag::err_incorrect_defaulted_exception_spec)
4619 << getSpecialMember(MD), PDiag(),
4620 ImplicitType, SourceLocation(),
4621 SpecifiedType, MD->getLocation());
4622}
4623
4624void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4625 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4626 I != N; ++I)
4627 CheckExplicitlyDefaultedMemberExceptionSpec(
4628 DelayedDefaultedMemberExceptionSpecs[I].first,
4629 DelayedDefaultedMemberExceptionSpecs[I].second);
4630
4631 DelayedDefaultedMemberExceptionSpecs.clear();
4632}
4633
Richard Smith7d5088a2012-02-18 02:02:13 +00004634namespace {
4635struct SpecialMemberDeletionInfo {
4636 Sema &S;
4637 CXXMethodDecl *MD;
4638 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004639 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004640
4641 // Properties of the special member, computed for convenience.
4642 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4643 SourceLocation Loc;
4644
4645 bool AllFieldsAreConst;
4646
4647 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004648 Sema::CXXSpecialMember CSM, bool Diagnose)
4649 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004650 IsConstructor(false), IsAssignment(false), IsMove(false),
4651 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4652 AllFieldsAreConst(true) {
4653 switch (CSM) {
4654 case Sema::CXXDefaultConstructor:
4655 case Sema::CXXCopyConstructor:
4656 IsConstructor = true;
4657 break;
4658 case Sema::CXXMoveConstructor:
4659 IsConstructor = true;
4660 IsMove = true;
4661 break;
4662 case Sema::CXXCopyAssignment:
4663 IsAssignment = true;
4664 break;
4665 case Sema::CXXMoveAssignment:
4666 IsAssignment = true;
4667 IsMove = true;
4668 break;
4669 case Sema::CXXDestructor:
4670 break;
4671 case Sema::CXXInvalid:
4672 llvm_unreachable("invalid special member kind");
4673 }
4674
4675 if (MD->getNumParams()) {
4676 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4677 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4678 }
4679 }
4680
4681 bool inUnion() const { return MD->getParent()->isUnion(); }
4682
4683 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004684 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4685 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004686 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004687 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4688 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4689 Quals = 0;
4690 return S.LookupSpecialMember(Class, CSM,
4691 ConstArg || (Quals & Qualifiers::Const),
4692 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004693 MD->getRefQualifier() == RQ_RValue,
4694 TQ & Qualifiers::Const,
4695 TQ & Qualifiers::Volatile);
4696 }
4697
Richard Smith6c4c36c2012-03-30 20:53:28 +00004698 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004699
Richard Smith6c4c36c2012-03-30 20:53:28 +00004700 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004701 bool shouldDeleteForField(FieldDecl *FD);
4702 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004703
Richard Smith517bb842012-07-18 03:51:16 +00004704 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4705 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004706 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4707 Sema::SpecialMemberOverloadResult *SMOR,
4708 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004709
4710 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004711};
4712}
4713
John McCall12d8d802012-04-09 20:53:23 +00004714/// Is the given special member inaccessible when used on the given
4715/// sub-object.
4716bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4717 CXXMethodDecl *target) {
4718 /// If we're operating on a base class, the object type is the
4719 /// type of this special member.
4720 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004721 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004722 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4723 objectTy = S.Context.getTypeDeclType(MD->getParent());
4724 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4725
4726 // If we're operating on a field, the object type is the type of the field.
4727 } else {
4728 objectTy = S.Context.getTypeDeclType(target->getParent());
4729 }
4730
4731 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4732}
4733
Richard Smith6c4c36c2012-03-30 20:53:28 +00004734/// Check whether we should delete a special member due to the implicit
4735/// definition containing a call to a special member of a subobject.
4736bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4737 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4738 bool IsDtorCallInCtor) {
4739 CXXMethodDecl *Decl = SMOR->getMethod();
4740 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4741
4742 int DiagKind = -1;
4743
4744 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4745 DiagKind = !Decl ? 0 : 1;
4746 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4747 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004748 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004749 DiagKind = 3;
4750 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4751 !Decl->isTrivial()) {
4752 // A member of a union must have a trivial corresponding special member.
4753 // As a weird special case, a destructor call from a union's constructor
4754 // must be accessible and non-deleted, but need not be trivial. Such a
4755 // destructor is never actually called, but is semantically checked as
4756 // if it were.
4757 DiagKind = 4;
4758 }
4759
4760 if (DiagKind == -1)
4761 return false;
4762
4763 if (Diagnose) {
4764 if (Field) {
4765 S.Diag(Field->getLocation(),
4766 diag::note_deleted_special_member_class_subobject)
4767 << CSM << MD->getParent() << /*IsField*/true
4768 << Field << DiagKind << IsDtorCallInCtor;
4769 } else {
4770 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4771 S.Diag(Base->getLocStart(),
4772 diag::note_deleted_special_member_class_subobject)
4773 << CSM << MD->getParent() << /*IsField*/false
4774 << Base->getType() << DiagKind << IsDtorCallInCtor;
4775 }
4776
4777 if (DiagKind == 1)
4778 S.NoteDeletedFunction(Decl);
4779 // FIXME: Explain inaccessibility if DiagKind == 3.
4780 }
4781
4782 return true;
4783}
4784
Richard Smith9a561d52012-02-26 09:11:52 +00004785/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004786/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004787bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004788 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004789 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004790
4791 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004792 // -- any direct or virtual base class, or non-static data member with no
4793 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004794 // either M has no default constructor or overload resolution as applied
4795 // to M's default constructor results in an ambiguity or in a function
4796 // that is deleted or inaccessible
4797 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4798 // -- a direct or virtual base class B that cannot be copied/moved because
4799 // overload resolution, as applied to B's corresponding special member,
4800 // results in an ambiguity or a function that is deleted or inaccessible
4801 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004802 // C++11 [class.dtor]p5:
4803 // -- any direct or virtual base class [...] has a type with a destructor
4804 // that is deleted or inaccessible
4805 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004806 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004807 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004808 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004809
Richard Smith6c4c36c2012-03-30 20:53:28 +00004810 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4811 // -- any direct or virtual base class or non-static data member has a
4812 // type with a destructor that is deleted or inaccessible
4813 if (IsConstructor) {
4814 Sema::SpecialMemberOverloadResult *SMOR =
4815 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4816 false, false, false, false, false);
4817 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4818 return true;
4819 }
4820
Richard Smith9a561d52012-02-26 09:11:52 +00004821 return false;
4822}
4823
4824/// Check whether we should delete a special member function due to the class
4825/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004826bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004827 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004828 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004829}
4830
4831/// Check whether we should delete a special member function due to the class
4832/// having a particular non-static data member.
4833bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4834 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4835 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4836
4837 if (CSM == Sema::CXXDefaultConstructor) {
4838 // For a default constructor, all references must be initialized in-class
4839 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004840 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4841 if (Diagnose)
4842 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4843 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004844 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004845 }
Richard Smith79363f52012-02-27 06:07:25 +00004846 // C++11 [class.ctor]p5: any non-variant non-static data member of
4847 // const-qualified type (or array thereof) with no
4848 // brace-or-equal-initializer does not have a user-provided default
4849 // constructor.
4850 if (!inUnion() && FieldType.isConstQualified() &&
4851 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004852 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4853 if (Diagnose)
4854 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004855 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004856 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004857 }
4858
4859 if (inUnion() && !FieldType.isConstQualified())
4860 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004861 } else if (CSM == Sema::CXXCopyConstructor) {
4862 // For a copy constructor, data members must not be of rvalue reference
4863 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004864 if (FieldType->isRValueReferenceType()) {
4865 if (Diagnose)
4866 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4867 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004868 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004869 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004870 } else if (IsAssignment) {
4871 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004872 if (FieldType->isReferenceType()) {
4873 if (Diagnose)
4874 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4875 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004876 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004877 }
4878 if (!FieldRecord && FieldType.isConstQualified()) {
4879 // C++11 [class.copy]p23:
4880 // -- a non-static data member of const non-class type (or array thereof)
4881 if (Diagnose)
4882 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004883 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004884 return true;
4885 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004886 }
4887
4888 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004889 // Some additional restrictions exist on the variant members.
4890 if (!inUnion() && FieldRecord->isUnion() &&
4891 FieldRecord->isAnonymousStructOrUnion()) {
4892 bool AllVariantFieldsAreConst = true;
4893
Richard Smithdf8dc862012-03-29 19:00:10 +00004894 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004895 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4896 UE = FieldRecord->field_end();
4897 UI != UE; ++UI) {
4898 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004899
4900 if (!UnionFieldType.isConstQualified())
4901 AllVariantFieldsAreConst = false;
4902
Richard Smith9a561d52012-02-26 09:11:52 +00004903 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4904 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004905 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4906 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004907 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004908 }
4909
4910 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004911 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004912 FieldRecord->field_begin() != FieldRecord->field_end()) {
4913 if (Diagnose)
4914 S.Diag(FieldRecord->getLocation(),
4915 diag::note_deleted_default_ctor_all_const)
4916 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004917 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004918 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004919
Richard Smithdf8dc862012-03-29 19:00:10 +00004920 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004921 // This is technically non-conformant, but sanity demands it.
4922 return false;
4923 }
4924
Richard Smith517bb842012-07-18 03:51:16 +00004925 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4926 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004927 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004928 }
4929
4930 return false;
4931}
4932
4933/// C++11 [class.ctor] p5:
4934/// A defaulted default constructor for a class X is defined as deleted if
4935/// X is a union and all of its variant members are of const-qualified type.
4936bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004937 // This is a silly definition, because it gives an empty union a deleted
4938 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004939 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4940 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4941 if (Diagnose)
4942 S.Diag(MD->getParent()->getLocation(),
4943 diag::note_deleted_default_ctor_all_const)
4944 << MD->getParent() << /*not anonymous union*/0;
4945 return true;
4946 }
4947 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004948}
4949
4950/// Determine whether a defaulted special member function should be defined as
4951/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4952/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004953bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4954 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004955 if (MD->isInvalidDecl())
4956 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004957 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004958 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004959 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004960 return false;
4961
Richard Smith7d5088a2012-02-18 02:02:13 +00004962 // C++11 [expr.lambda.prim]p19:
4963 // The closure type associated with a lambda-expression has a
4964 // deleted (8.4.3) default constructor and a deleted copy
4965 // assignment operator.
4966 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004967 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4968 if (Diagnose)
4969 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004970 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004971 }
4972
Richard Smith5bdaac52012-04-02 20:59:25 +00004973 // For an anonymous struct or union, the copy and assignment special members
4974 // will never be used, so skip the check. For an anonymous union declared at
4975 // namespace scope, the constructor and destructor are used.
4976 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4977 RD->isAnonymousStructOrUnion())
4978 return false;
4979
Richard Smith6c4c36c2012-03-30 20:53:28 +00004980 // C++11 [class.copy]p7, p18:
4981 // If the class definition declares a move constructor or move assignment
4982 // operator, an implicitly declared copy constructor or copy assignment
4983 // operator is defined as deleted.
4984 if (MD->isImplicit() &&
4985 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4986 CXXMethodDecl *UserDeclaredMove = 0;
4987
4988 // In Microsoft mode, a user-declared move only causes the deletion of the
4989 // corresponding copy operation, not both copy operations.
4990 if (RD->hasUserDeclaredMoveConstructor() &&
4991 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4992 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004993
4994 // Find any user-declared move constructor.
4995 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4996 E = RD->ctor_end(); I != E; ++I) {
4997 if (I->isMoveConstructor()) {
4998 UserDeclaredMove = *I;
4999 break;
5000 }
5001 }
Richard Smith1c931be2012-04-02 18:40:40 +00005002 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005003 } else if (RD->hasUserDeclaredMoveAssignment() &&
5004 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5005 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005006
5007 // Find any user-declared move assignment operator.
5008 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5009 E = RD->method_end(); I != E; ++I) {
5010 if (I->isMoveAssignmentOperator()) {
5011 UserDeclaredMove = *I;
5012 break;
5013 }
5014 }
Richard Smith1c931be2012-04-02 18:40:40 +00005015 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005016 }
5017
5018 if (UserDeclaredMove) {
5019 Diag(UserDeclaredMove->getLocation(),
5020 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005021 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005022 << UserDeclaredMove->isMoveAssignmentOperator();
5023 return true;
5024 }
5025 }
Sean Hunte16da072011-10-10 06:18:57 +00005026
Richard Smith5bdaac52012-04-02 20:59:25 +00005027 // Do access control from the special member function
5028 ContextRAII MethodContext(*this, MD);
5029
Richard Smith9a561d52012-02-26 09:11:52 +00005030 // C++11 [class.dtor]p5:
5031 // -- for a virtual destructor, lookup of the non-array deallocation function
5032 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005033 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005034 FunctionDecl *OperatorDelete = 0;
5035 DeclarationName Name =
5036 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5037 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005038 OperatorDelete, false)) {
5039 if (Diagnose)
5040 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005041 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005042 }
Richard Smith9a561d52012-02-26 09:11:52 +00005043 }
5044
Richard Smith6c4c36c2012-03-30 20:53:28 +00005045 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005046
Sean Huntcdee3fe2011-05-11 22:34:38 +00005047 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005048 BE = RD->bases_end(); BI != BE; ++BI)
5049 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005050 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005051 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005052
5053 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005054 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00005055 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005056 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005057
5058 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005059 FE = RD->field_end(); FI != FE; ++FI)
5060 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005061 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005062 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005063
Richard Smith7d5088a2012-02-18 02:02:13 +00005064 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005065 return true;
5066
5067 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005068}
5069
Richard Smithac713512012-12-08 02:53:02 +00005070/// Perform lookup for a special member of the specified kind, and determine
5071/// whether it is trivial. If the triviality can be determined without the
5072/// lookup, skip it. This is intended for use when determining whether a
5073/// special member of a containing object is trivial, and thus does not ever
5074/// perform overload resolution for default constructors.
5075///
5076/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5077/// member that was most likely to be intended to be trivial, if any.
5078static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5079 Sema::CXXSpecialMember CSM, unsigned Quals,
5080 CXXMethodDecl **Selected) {
5081 if (Selected)
5082 *Selected = 0;
5083
5084 switch (CSM) {
5085 case Sema::CXXInvalid:
5086 llvm_unreachable("not a special member");
5087
5088 case Sema::CXXDefaultConstructor:
5089 // C++11 [class.ctor]p5:
5090 // A default constructor is trivial if:
5091 // - all the [direct subobjects] have trivial default constructors
5092 //
5093 // Note, no overload resolution is performed in this case.
5094 if (RD->hasTrivialDefaultConstructor())
5095 return true;
5096
5097 if (Selected) {
5098 // If there's a default constructor which could have been trivial, dig it
5099 // out. Otherwise, if there's any user-provided default constructor, point
5100 // to that as an example of why there's not a trivial one.
5101 CXXConstructorDecl *DefCtor = 0;
5102 if (RD->needsImplicitDefaultConstructor())
5103 S.DeclareImplicitDefaultConstructor(RD);
5104 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5105 CE = RD->ctor_end(); CI != CE; ++CI) {
5106 if (!CI->isDefaultConstructor())
5107 continue;
5108 DefCtor = *CI;
5109 if (!DefCtor->isUserProvided())
5110 break;
5111 }
5112
5113 *Selected = DefCtor;
5114 }
5115
5116 return false;
5117
5118 case Sema::CXXDestructor:
5119 // C++11 [class.dtor]p5:
5120 // A destructor is trivial if:
5121 // - all the direct [subobjects] have trivial destructors
5122 if (RD->hasTrivialDestructor())
5123 return true;
5124
5125 if (Selected) {
5126 if (RD->needsImplicitDestructor())
5127 S.DeclareImplicitDestructor(RD);
5128 *Selected = RD->getDestructor();
5129 }
5130
5131 return false;
5132
5133 case Sema::CXXCopyConstructor:
5134 // C++11 [class.copy]p12:
5135 // A copy constructor is trivial if:
5136 // - the constructor selected to copy each direct [subobject] is trivial
5137 if (RD->hasTrivialCopyConstructor()) {
5138 if (Quals == Qualifiers::Const)
5139 // We must either select the trivial copy constructor or reach an
5140 // ambiguity; no need to actually perform overload resolution.
5141 return true;
5142 } else if (!Selected) {
5143 return false;
5144 }
5145 // In C++98, we are not supposed to perform overload resolution here, but we
5146 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5147 // cases like B as having a non-trivial copy constructor:
5148 // struct A { template<typename T> A(T&); };
5149 // struct B { mutable A a; };
5150 goto NeedOverloadResolution;
5151
5152 case Sema::CXXCopyAssignment:
5153 // C++11 [class.copy]p25:
5154 // A copy assignment operator is trivial if:
5155 // - the assignment operator selected to copy each direct [subobject] is
5156 // trivial
5157 if (RD->hasTrivialCopyAssignment()) {
5158 if (Quals == Qualifiers::Const)
5159 return true;
5160 } else if (!Selected) {
5161 return false;
5162 }
5163 // In C++98, we are not supposed to perform overload resolution here, but we
5164 // treat that as a language defect.
5165 goto NeedOverloadResolution;
5166
5167 case Sema::CXXMoveConstructor:
5168 case Sema::CXXMoveAssignment:
5169 NeedOverloadResolution:
5170 Sema::SpecialMemberOverloadResult *SMOR =
5171 S.LookupSpecialMember(RD, CSM,
5172 Quals & Qualifiers::Const,
5173 Quals & Qualifiers::Volatile,
5174 /*RValueThis*/false, /*ConstThis*/false,
5175 /*VolatileThis*/false);
5176
5177 // The standard doesn't describe how to behave if the lookup is ambiguous.
5178 // We treat it as not making the member non-trivial, just like the standard
5179 // mandates for the default constructor. This should rarely matter, because
5180 // the member will also be deleted.
5181 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5182 return true;
5183
5184 if (!SMOR->getMethod()) {
5185 assert(SMOR->getKind() ==
5186 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5187 return false;
5188 }
5189
5190 // We deliberately don't check if we found a deleted special member. We're
5191 // not supposed to!
5192 if (Selected)
5193 *Selected = SMOR->getMethod();
5194 return SMOR->getMethod()->isTrivial();
5195 }
5196
5197 llvm_unreachable("unknown special method kind");
5198}
5199
Benjamin Kramera574c892013-02-15 12:30:38 +00005200static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005201 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5202 CI != CE; ++CI)
5203 if (!CI->isImplicit())
5204 return *CI;
5205
5206 // Look for constructor templates.
5207 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5208 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5209 if (CXXConstructorDecl *CD =
5210 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5211 return CD;
5212 }
5213
5214 return 0;
5215}
5216
5217/// The kind of subobject we are checking for triviality. The values of this
5218/// enumeration are used in diagnostics.
5219enum TrivialSubobjectKind {
5220 /// The subobject is a base class.
5221 TSK_BaseClass,
5222 /// The subobject is a non-static data member.
5223 TSK_Field,
5224 /// The object is actually the complete object.
5225 TSK_CompleteObject
5226};
5227
5228/// Check whether the special member selected for a given type would be trivial.
5229static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5230 QualType SubType,
5231 Sema::CXXSpecialMember CSM,
5232 TrivialSubobjectKind Kind,
5233 bool Diagnose) {
5234 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5235 if (!SubRD)
5236 return true;
5237
5238 CXXMethodDecl *Selected;
5239 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5240 Diagnose ? &Selected : 0))
5241 return true;
5242
5243 if (Diagnose) {
5244 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5245 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5246 << Kind << SubType.getUnqualifiedType();
5247 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5248 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5249 } else if (!Selected)
5250 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5251 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5252 else if (Selected->isUserProvided()) {
5253 if (Kind == TSK_CompleteObject)
5254 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5255 << Kind << SubType.getUnqualifiedType() << CSM;
5256 else {
5257 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5258 << Kind << SubType.getUnqualifiedType() << CSM;
5259 S.Diag(Selected->getLocation(), diag::note_declared_at);
5260 }
5261 } else {
5262 if (Kind != TSK_CompleteObject)
5263 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5264 << Kind << SubType.getUnqualifiedType() << CSM;
5265
5266 // Explain why the defaulted or deleted special member isn't trivial.
5267 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5268 }
5269 }
5270
5271 return false;
5272}
5273
5274/// Check whether the members of a class type allow a special member to be
5275/// trivial.
5276static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5277 Sema::CXXSpecialMember CSM,
5278 bool ConstArg, bool Diagnose) {
5279 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5280 FE = RD->field_end(); FI != FE; ++FI) {
5281 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5282 continue;
5283
5284 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5285
5286 // Pretend anonymous struct or union members are members of this class.
5287 if (FI->isAnonymousStructOrUnion()) {
5288 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5289 CSM, ConstArg, Diagnose))
5290 return false;
5291 continue;
5292 }
5293
5294 // C++11 [class.ctor]p5:
5295 // A default constructor is trivial if [...]
5296 // -- no non-static data member of its class has a
5297 // brace-or-equal-initializer
5298 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5299 if (Diagnose)
5300 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5301 return false;
5302 }
5303
5304 // Objective C ARC 4.3.5:
5305 // [...] nontrivally ownership-qualified types are [...] not trivially
5306 // default constructible, copy constructible, move constructible, copy
5307 // assignable, move assignable, or destructible [...]
5308 if (S.getLangOpts().ObjCAutoRefCount &&
5309 FieldType.hasNonTrivialObjCLifetime()) {
5310 if (Diagnose)
5311 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5312 << RD << FieldType.getObjCLifetime();
5313 return false;
5314 }
5315
5316 if (ConstArg && !FI->isMutable())
5317 FieldType.addConst();
5318 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5319 TSK_Field, Diagnose))
5320 return false;
5321 }
5322
5323 return true;
5324}
5325
5326/// Diagnose why the specified class does not have a trivial special member of
5327/// the given kind.
5328void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5329 QualType Ty = Context.getRecordType(RD);
5330 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5331 Ty.addConst();
5332
5333 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5334 TSK_CompleteObject, /*Diagnose*/true);
5335}
5336
5337/// Determine whether a defaulted or deleted special member function is trivial,
5338/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5339/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5340bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5341 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005342 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5343
5344 CXXRecordDecl *RD = MD->getParent();
5345
5346 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005347
5348 // C++11 [class.copy]p12, p25:
5349 // A [special member] is trivial if its declared parameter type is the same
5350 // as if it had been implicitly declared [...]
5351 switch (CSM) {
5352 case CXXDefaultConstructor:
5353 case CXXDestructor:
5354 // Trivial default constructors and destructors cannot have parameters.
5355 break;
5356
5357 case CXXCopyConstructor:
5358 case CXXCopyAssignment: {
5359 // Trivial copy operations always have const, non-volatile parameter types.
5360 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005361 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005362 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5363 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5364 if (Diagnose)
5365 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5366 << Param0->getSourceRange() << Param0->getType()
5367 << Context.getLValueReferenceType(
5368 Context.getRecordType(RD).withConst());
5369 return false;
5370 }
5371 break;
5372 }
5373
5374 case CXXMoveConstructor:
5375 case CXXMoveAssignment: {
5376 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005377 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005378 const RValueReferenceType *RT =
5379 Param0->getType()->getAs<RValueReferenceType>();
5380 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5381 if (Diagnose)
5382 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5383 << Param0->getSourceRange() << Param0->getType()
5384 << Context.getRValueReferenceType(Context.getRecordType(RD));
5385 return false;
5386 }
5387 break;
5388 }
5389
5390 case CXXInvalid:
5391 llvm_unreachable("not a special member");
5392 }
5393
5394 // FIXME: We require that the parameter-declaration-clause is equivalent to
5395 // that of an implicit declaration, not just that the declared parameter type
5396 // matches, in order to prevent absuridities like a function simultaneously
5397 // being a trivial copy constructor and a non-trivial default constructor.
5398 // This issue has not yet been assigned a core issue number.
5399 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5400 if (Diagnose)
5401 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5402 diag::note_nontrivial_default_arg)
5403 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5404 return false;
5405 }
5406 if (MD->isVariadic()) {
5407 if (Diagnose)
5408 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5409 return false;
5410 }
5411
5412 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5413 // A copy/move [constructor or assignment operator] is trivial if
5414 // -- the [member] selected to copy/move each direct base class subobject
5415 // is trivial
5416 //
5417 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5418 // A [default constructor or destructor] is trivial if
5419 // -- all the direct base classes have trivial [default constructors or
5420 // destructors]
5421 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5422 BE = RD->bases_end(); BI != BE; ++BI)
5423 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5424 ConstArg ? BI->getType().withConst()
5425 : BI->getType(),
5426 CSM, TSK_BaseClass, Diagnose))
5427 return false;
5428
5429 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5430 // A copy/move [constructor or assignment operator] for a class X is
5431 // trivial if
5432 // -- for each non-static data member of X that is of class type (or array
5433 // thereof), the constructor selected to copy/move that member is
5434 // trivial
5435 //
5436 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5437 // A [default constructor or destructor] is trivial if
5438 // -- for all of the non-static data members of its class that are of class
5439 // type (or array thereof), each such class has a trivial [default
5440 // constructor or destructor]
5441 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5442 return false;
5443
5444 // C++11 [class.dtor]p5:
5445 // A destructor is trivial if [...]
5446 // -- the destructor is not virtual
5447 if (CSM == CXXDestructor && MD->isVirtual()) {
5448 if (Diagnose)
5449 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5450 return false;
5451 }
5452
5453 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5454 // A [special member] for class X is trivial if [...]
5455 // -- class X has no virtual functions and no virtual base classes
5456 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5457 if (!Diagnose)
5458 return false;
5459
5460 if (RD->getNumVBases()) {
5461 // Check for virtual bases. We already know that the corresponding
5462 // member in all bases is trivial, so vbases must all be direct.
5463 CXXBaseSpecifier &BS = *RD->vbases_begin();
5464 assert(BS.isVirtual());
5465 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5466 return false;
5467 }
5468
5469 // Must have a virtual method.
5470 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5471 ME = RD->method_end(); MI != ME; ++MI) {
5472 if (MI->isVirtual()) {
5473 SourceLocation MLoc = MI->getLocStart();
5474 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5475 return false;
5476 }
5477 }
5478
5479 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5480 }
5481
5482 // Looks like it's trivial!
5483 return true;
5484}
5485
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005486/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005487namespace {
5488 struct FindHiddenVirtualMethodData {
5489 Sema *S;
5490 CXXMethodDecl *Method;
5491 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005492 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005493 };
5494}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005495
David Blaikie5f750682012-10-19 00:53:08 +00005496/// \brief Check whether any most overriden method from MD in Methods
5497static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5498 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5499 if (MD->size_overridden_methods() == 0)
5500 return Methods.count(MD->getCanonicalDecl());
5501 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5502 E = MD->end_overridden_methods();
5503 I != E; ++I)
5504 if (CheckMostOverridenMethods(*I, Methods))
5505 return true;
5506 return false;
5507}
5508
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005509/// \brief Member lookup function that determines whether a given C++
5510/// method overloads virtual methods in a base class without overriding any,
5511/// to be used with CXXRecordDecl::lookupInBases().
5512static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5513 CXXBasePath &Path,
5514 void *UserData) {
5515 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5516
5517 FindHiddenVirtualMethodData &Data
5518 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5519
5520 DeclarationName Name = Data.Method->getDeclName();
5521 assert(Name.getNameKind() == DeclarationName::Identifier);
5522
5523 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005524 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005525 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005526 !Path.Decls.empty();
5527 Path.Decls = Path.Decls.slice(1)) {
5528 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005529 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005530 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005531 foundSameNameMethod = true;
5532 // Interested only in hidden virtual methods.
5533 if (!MD->isVirtual())
5534 continue;
5535 // If the method we are checking overrides a method from its base
5536 // don't warn about the other overloaded methods.
5537 if (!Data.S->IsOverload(Data.Method, MD, false))
5538 return true;
5539 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005540 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005541 overloadedMethods.push_back(MD);
5542 }
5543 }
5544
5545 if (foundSameNameMethod)
5546 Data.OverloadedMethods.append(overloadedMethods.begin(),
5547 overloadedMethods.end());
5548 return foundSameNameMethod;
5549}
5550
David Blaikie5f750682012-10-19 00:53:08 +00005551/// \brief Add the most overriden methods from MD to Methods
5552static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5553 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5554 if (MD->size_overridden_methods() == 0)
5555 Methods.insert(MD->getCanonicalDecl());
5556 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5557 E = MD->end_overridden_methods();
5558 I != E; ++I)
5559 AddMostOverridenMethods(*I, Methods);
5560}
5561
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005562/// \brief See if a method overloads virtual methods in a base class without
5563/// overriding any.
5564void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5565 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005566 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005567 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005568 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005569 return;
5570
5571 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5572 /*bool RecordPaths=*/false,
5573 /*bool DetectVirtual=*/false);
5574 FindHiddenVirtualMethodData Data;
5575 Data.Method = MD;
5576 Data.S = this;
5577
5578 // Keep the base methods that were overriden or introduced in the subclass
5579 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005580 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5581 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5582 NamedDecl *ND = *I;
5583 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005584 ND = shad->getTargetDecl();
5585 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5586 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005587 }
5588
5589 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5590 !Data.OverloadedMethods.empty()) {
5591 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5592 << MD << (Data.OverloadedMethods.size() > 1);
5593
5594 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5595 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005596 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005597 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005598 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5599 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005600 }
5601 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005602}
5603
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005604void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005605 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005606 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005607 SourceLocation RBrac,
5608 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005609 if (!TagDecl)
5610 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005611
Douglas Gregor42af25f2009-05-11 19:58:34 +00005612 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005613
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005614 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5615 if (l->getKind() != AttributeList::AT_Visibility)
5616 continue;
5617 l->setInvalid();
5618 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5619 l->getName();
5620 }
5621
David Blaikie77b6de02011-09-22 02:58:26 +00005622 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005623 // strict aliasing violation!
5624 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005625 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005626
Douglas Gregor23c94db2010-07-02 17:43:08 +00005627 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005628 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005629}
5630
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005631/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5632/// special functions, such as the default constructor, copy
5633/// constructor, or destructor, to the given C++ class (C++
5634/// [special]p1). This routine can only be executed just before the
5635/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005636void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005637 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005638 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005639
Richard Smithbc2a35d2012-12-08 08:32:28 +00005640 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005641 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005642
Richard Smithbc2a35d2012-12-08 08:32:28 +00005643 // If the properties or semantics of the copy constructor couldn't be
5644 // determined while the class was being declared, force a declaration
5645 // of it now.
5646 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5647 DeclareImplicitCopyConstructor(ClassDecl);
5648 }
5649
Richard Smith80ad52f2013-01-02 11:42:31 +00005650 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005651 ++ASTContext::NumImplicitMoveConstructors;
5652
Richard Smithbc2a35d2012-12-08 08:32:28 +00005653 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5654 DeclareImplicitMoveConstructor(ClassDecl);
5655 }
5656
Douglas Gregora376d102010-07-02 21:50:04 +00005657 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5658 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005659
5660 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005661 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005662 // it shows up in the right place in the vtable and that we diagnose
5663 // problems with the implicit exception specification.
5664 if (ClassDecl->isDynamicClass() ||
5665 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005666 DeclareImplicitCopyAssignment(ClassDecl);
5667 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005668
Richard Smith80ad52f2013-01-02 11:42:31 +00005669 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005670 ++ASTContext::NumImplicitMoveAssignmentOperators;
5671
5672 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005673 if (ClassDecl->isDynamicClass() ||
5674 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005675 DeclareImplicitMoveAssignment(ClassDecl);
5676 }
5677
Douglas Gregor4923aa22010-07-02 20:37:36 +00005678 if (!ClassDecl->hasUserDeclaredDestructor()) {
5679 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005680
5681 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005682 // have to declare the destructor immediately. This ensures that, e.g., it
5683 // shows up in the right place in the vtable and that we diagnose problems
5684 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005685 if (ClassDecl->isDynamicClass() ||
5686 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005687 DeclareImplicitDestructor(ClassDecl);
5688 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005689}
5690
Francois Pichet8387e2a2011-04-22 22:18:13 +00005691void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5692 if (!D)
5693 return;
5694
5695 int NumParamList = D->getNumTemplateParameterLists();
5696 for (int i = 0; i < NumParamList; i++) {
5697 TemplateParameterList* Params = D->getTemplateParameterList(i);
5698 for (TemplateParameterList::iterator Param = Params->begin(),
5699 ParamEnd = Params->end();
5700 Param != ParamEnd; ++Param) {
5701 NamedDecl *Named = cast<NamedDecl>(*Param);
5702 if (Named->getDeclName()) {
5703 S->AddDecl(Named);
5704 IdResolver.AddDecl(Named);
5705 }
5706 }
5707 }
5708}
5709
John McCalld226f652010-08-21 09:40:31 +00005710void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005711 if (!D)
5712 return;
5713
5714 TemplateParameterList *Params = 0;
5715 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5716 Params = Template->getTemplateParameters();
5717 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5718 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5719 Params = PartialSpec->getTemplateParameters();
5720 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005721 return;
5722
Douglas Gregor6569d682009-05-27 23:11:45 +00005723 for (TemplateParameterList::iterator Param = Params->begin(),
5724 ParamEnd = Params->end();
5725 Param != ParamEnd; ++Param) {
5726 NamedDecl *Named = cast<NamedDecl>(*Param);
5727 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005728 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005729 IdResolver.AddDecl(Named);
5730 }
5731 }
5732}
5733
John McCalld226f652010-08-21 09:40:31 +00005734void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005735 if (!RecordD) return;
5736 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005737 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005738 PushDeclContext(S, Record);
5739}
5740
John McCalld226f652010-08-21 09:40:31 +00005741void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005742 if (!RecordD) return;
5743 PopDeclContext();
5744}
5745
Douglas Gregor72b505b2008-12-16 21:30:33 +00005746/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5747/// parsing a top-level (non-nested) C++ class, and we are now
5748/// parsing those parts of the given Method declaration that could
5749/// not be parsed earlier (C++ [class.mem]p2), such as default
5750/// arguments. This action should enter the scope of the given
5751/// Method declaration as if we had just parsed the qualified method
5752/// name. However, it should not bring the parameters into scope;
5753/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005754void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005755}
5756
5757/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5758/// C++ method declaration. We're (re-)introducing the given
5759/// function parameter into scope for use in parsing later parts of
5760/// the method declaration. For example, we could see an
5761/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005762void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005763 if (!ParamD)
5764 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005765
John McCalld226f652010-08-21 09:40:31 +00005766 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005767
5768 // If this parameter has an unparsed default argument, clear it out
5769 // to make way for the parsed default argument.
5770 if (Param->hasUnparsedDefaultArg())
5771 Param->setDefaultArg(0);
5772
John McCalld226f652010-08-21 09:40:31 +00005773 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005774 if (Param->getDeclName())
5775 IdResolver.AddDecl(Param);
5776}
5777
5778/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5779/// processing the delayed method declaration for Method. The method
5780/// declaration is now considered finished. There may be a separate
5781/// ActOnStartOfFunctionDef action later (not necessarily
5782/// immediately!) for this method, if it was also defined inside the
5783/// class body.
John McCalld226f652010-08-21 09:40:31 +00005784void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005785 if (!MethodD)
5786 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005787
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005788 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005789
John McCalld226f652010-08-21 09:40:31 +00005790 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005791
5792 // Now that we have our default arguments, check the constructor
5793 // again. It could produce additional diagnostics or affect whether
5794 // the class has implicitly-declared destructors, among other
5795 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005796 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5797 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005798
5799 // Check the default arguments, which we may have added.
5800 if (!Method->isInvalidDecl())
5801 CheckCXXDefaultArguments(Method);
5802}
5803
Douglas Gregor42a552f2008-11-05 20:51:48 +00005804/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005805/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005806/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005807/// emit diagnostics and set the invalid bit to true. In any case, the type
5808/// will be updated to reflect a well-formed type for the constructor and
5809/// returned.
5810QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005811 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005812 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005813
5814 // C++ [class.ctor]p3:
5815 // A constructor shall not be virtual (10.3) or static (9.4). A
5816 // constructor can be invoked for a const, volatile or const
5817 // volatile object. A constructor shall not be declared const,
5818 // volatile, or const volatile (9.3.2).
5819 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005820 if (!D.isInvalidType())
5821 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5822 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5823 << SourceRange(D.getIdentifierLoc());
5824 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005825 }
John McCalld931b082010-08-26 03:08:43 +00005826 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005827 if (!D.isInvalidType())
5828 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5829 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5830 << SourceRange(D.getIdentifierLoc());
5831 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005832 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005833 }
Mike Stump1eb44332009-09-09 15:08:12 +00005834
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005835 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005836 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005837 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005838 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5839 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005840 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005841 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5842 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005843 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005844 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5845 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005846 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005847 }
Mike Stump1eb44332009-09-09 15:08:12 +00005848
Douglas Gregorc938c162011-01-26 05:01:58 +00005849 // C++0x [class.ctor]p4:
5850 // A constructor shall not be declared with a ref-qualifier.
5851 if (FTI.hasRefQualifier()) {
5852 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5853 << FTI.RefQualifierIsLValueRef
5854 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5855 D.setInvalidType();
5856 }
5857
Douglas Gregor42a552f2008-11-05 20:51:48 +00005858 // Rebuild the function type "R" without any type qualifiers (in
5859 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005860 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005861 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005862 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5863 return R;
5864
5865 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5866 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005867 EPI.RefQualifier = RQ_None;
5868
Richard Smith07b0fdc2013-03-18 21:12:30 +00005869 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005870}
5871
Douglas Gregor72b505b2008-12-16 21:30:33 +00005872/// CheckConstructor - Checks a fully-formed constructor for
5873/// well-formedness, issuing any diagnostics required. Returns true if
5874/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005875void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005876 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005877 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5878 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005879 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005880
5881 // C++ [class.copy]p3:
5882 // A declaration of a constructor for a class X is ill-formed if
5883 // its first parameter is of type (optionally cv-qualified) X and
5884 // either there are no other parameters or else all other
5885 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005886 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005887 ((Constructor->getNumParams() == 1) ||
5888 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005889 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5890 Constructor->getTemplateSpecializationKind()
5891 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005892 QualType ParamType = Constructor->getParamDecl(0)->getType();
5893 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5894 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005895 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005896 const char *ConstRef
5897 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5898 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005899 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005900 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005901
5902 // FIXME: Rather that making the constructor invalid, we should endeavor
5903 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005904 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005905 }
5906 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005907}
5908
John McCall15442822010-08-04 01:04:25 +00005909/// CheckDestructor - Checks a fully-formed destructor definition for
5910/// well-formedness, issuing any diagnostics required. Returns true
5911/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005912bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005913 CXXRecordDecl *RD = Destructor->getParent();
5914
Peter Collingbournef51cfb82013-05-20 14:12:25 +00005915 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005916 SourceLocation Loc;
5917
5918 if (!Destructor->isImplicit())
5919 Loc = Destructor->getLocation();
5920 else
5921 Loc = RD->getLocation();
5922
5923 // If we have a virtual destructor, look up the deallocation function
5924 FunctionDecl *OperatorDelete = 0;
5925 DeclarationName Name =
5926 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005927 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005928 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005929
Eli Friedman5f2987c2012-02-02 03:46:19 +00005930 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005931
5932 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005933 }
Anders Carlsson37909802009-11-30 21:24:50 +00005934
5935 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005936}
5937
Mike Stump1eb44332009-09-09 15:08:12 +00005938static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005939FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5940 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5941 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005942 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005943}
5944
Douglas Gregor42a552f2008-11-05 20:51:48 +00005945/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5946/// the well-formednes of the destructor declarator @p D with type @p
5947/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005948/// emit diagnostics and set the declarator to invalid. Even if this happens,
5949/// will be updated to reflect a well-formed type for the destructor and
5950/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005951QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005952 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005953 // C++ [class.dtor]p1:
5954 // [...] A typedef-name that names a class is a class-name
5955 // (7.1.3); however, a typedef-name that names a class shall not
5956 // be used as the identifier in the declarator for a destructor
5957 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005958 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005959 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005960 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005961 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005962 else if (const TemplateSpecializationType *TST =
5963 DeclaratorType->getAs<TemplateSpecializationType>())
5964 if (TST->isTypeAlias())
5965 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5966 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005967
5968 // C++ [class.dtor]p2:
5969 // A destructor is used to destroy objects of its class type. A
5970 // destructor takes no parameters, and no return type can be
5971 // specified for it (not even void). The address of a destructor
5972 // shall not be taken. A destructor shall not be static. A
5973 // destructor can be invoked for a const, volatile or const
5974 // volatile object. A destructor shall not be declared const,
5975 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005976 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005977 if (!D.isInvalidType())
5978 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5979 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005980 << SourceRange(D.getIdentifierLoc())
5981 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5982
John McCalld931b082010-08-26 03:08:43 +00005983 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005984 }
Chris Lattner65401802009-04-25 08:28:21 +00005985 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005986 // Destructors don't have return types, but the parser will
5987 // happily parse something like:
5988 //
5989 // class X {
5990 // float ~X();
5991 // };
5992 //
5993 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005994 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5995 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5996 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005997 }
Mike Stump1eb44332009-09-09 15:08:12 +00005998
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005999 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006000 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006001 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006002 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6003 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006004 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006005 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6006 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006007 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006008 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6009 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006010 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006011 }
6012
Douglas Gregorc938c162011-01-26 05:01:58 +00006013 // C++0x [class.dtor]p2:
6014 // A destructor shall not be declared with a ref-qualifier.
6015 if (FTI.hasRefQualifier()) {
6016 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6017 << FTI.RefQualifierIsLValueRef
6018 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6019 D.setInvalidType();
6020 }
6021
Douglas Gregor42a552f2008-11-05 20:51:48 +00006022 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006023 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006024 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6025
6026 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006027 FTI.freeArgs();
6028 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006029 }
6030
Mike Stump1eb44332009-09-09 15:08:12 +00006031 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006032 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006033 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006034 D.setInvalidType();
6035 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006036
6037 // Rebuild the function type "R" without any type qualifiers or
6038 // parameters (in case any of the errors above fired) and with
6039 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006040 // types.
John McCalle23cf432010-12-14 08:05:40 +00006041 if (!D.isInvalidType())
6042 return R;
6043
Douglas Gregord92ec472010-07-01 05:10:53 +00006044 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006045 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6046 EPI.Variadic = false;
6047 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006048 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006049 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006050}
6051
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006052/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6053/// well-formednes of the conversion function declarator @p D with
6054/// type @p R. If there are any errors in the declarator, this routine
6055/// will emit diagnostics and return true. Otherwise, it will return
6056/// false. Either way, the type @p R will be updated to reflect a
6057/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006058void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006059 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006060 // C++ [class.conv.fct]p1:
6061 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006062 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006063 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006064 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006065 if (!D.isInvalidType())
6066 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006067 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6068 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006069 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006070 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006071 }
John McCalla3f81372010-04-13 00:04:31 +00006072
6073 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6074
Chris Lattner6e475012009-04-25 08:35:12 +00006075 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006076 // Conversion functions don't have return types, but the parser will
6077 // happily parse something like:
6078 //
6079 // class X {
6080 // float operator bool();
6081 // };
6082 //
6083 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006084 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6085 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6086 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006087 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006088 }
6089
John McCalla3f81372010-04-13 00:04:31 +00006090 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6091
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006092 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006093 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006094 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6095
6096 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006097 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006098 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006099 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006100 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006101 D.setInvalidType();
6102 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006103
John McCalla3f81372010-04-13 00:04:31 +00006104 // Diagnose "&operator bool()" and other such nonsense. This
6105 // is actually a gcc extension which we don't support.
6106 if (Proto->getResultType() != ConvType) {
6107 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6108 << Proto->getResultType();
6109 D.setInvalidType();
6110 ConvType = Proto->getResultType();
6111 }
6112
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006113 // C++ [class.conv.fct]p4:
6114 // The conversion-type-id shall not represent a function type nor
6115 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006116 if (ConvType->isArrayType()) {
6117 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6118 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006119 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006120 } else if (ConvType->isFunctionType()) {
6121 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6122 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006123 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006124 }
6125
6126 // Rebuild the function type "R" without any parameters (in case any
6127 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006128 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006129 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006130 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006131
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006132 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006133 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006134 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006135 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006136 diag::warn_cxx98_compat_explicit_conversion_functions :
6137 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006138 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006139}
6140
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006141/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6142/// the declaration of the given C++ conversion function. This routine
6143/// is responsible for recording the conversion function in the C++
6144/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006145Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006146 assert(Conversion && "Expected to receive a conversion function declaration");
6147
Douglas Gregor9d350972008-12-12 08:25:50 +00006148 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006149
6150 // Make sure we aren't redeclaring the conversion function.
6151 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006152
6153 // C++ [class.conv.fct]p1:
6154 // [...] A conversion function is never used to convert a
6155 // (possibly cv-qualified) object to the (possibly cv-qualified)
6156 // same object type (or a reference to it), to a (possibly
6157 // cv-qualified) base class of that type (or a reference to it),
6158 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006159 // FIXME: Suppress this warning if the conversion function ends up being a
6160 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006161 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006162 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006163 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006164 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006165 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6166 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006167 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006168 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006169 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6170 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006171 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006172 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006173 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006174 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006175 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006176 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006177 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006178 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006179 }
6180
Douglas Gregore80622f2010-09-29 04:25:11 +00006181 if (FunctionTemplateDecl *ConversionTemplate
6182 = Conversion->getDescribedFunctionTemplate())
6183 return ConversionTemplate;
6184
John McCalld226f652010-08-21 09:40:31 +00006185 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006186}
6187
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006188//===----------------------------------------------------------------------===//
6189// Namespace Handling
6190//===----------------------------------------------------------------------===//
6191
Richard Smithd1a55a62012-10-04 22:13:39 +00006192/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6193/// reopened.
6194static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6195 SourceLocation Loc,
6196 IdentifierInfo *II, bool *IsInline,
6197 NamespaceDecl *PrevNS) {
6198 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006199
Richard Smithc969e6a2012-10-05 01:46:25 +00006200 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6201 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6202 // inline namespaces, with the intention of bringing names into namespace std.
6203 //
6204 // We support this just well enough to get that case working; this is not
6205 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006206 if (*IsInline && II && II->getName().startswith("__atomic") &&
6207 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006208 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006209 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6210 NS = NS->getPreviousDecl())
6211 NS->setInline(*IsInline);
6212 // Patch up the lookup table for the containing namespace. This isn't really
6213 // correct, but it's good enough for this particular case.
6214 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6215 E = PrevNS->decls_end(); I != E; ++I)
6216 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6217 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6218 return;
6219 }
6220
6221 if (PrevNS->isInline())
6222 // The user probably just forgot the 'inline', so suggest that it
6223 // be added back.
6224 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6225 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6226 else
6227 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6228 << IsInline;
6229
6230 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6231 *IsInline = PrevNS->isInline();
6232}
John McCallea318642010-08-26 09:15:37 +00006233
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006234/// ActOnStartNamespaceDef - This is called at the start of a namespace
6235/// definition.
John McCalld226f652010-08-21 09:40:31 +00006236Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006237 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006238 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006239 SourceLocation IdentLoc,
6240 IdentifierInfo *II,
6241 SourceLocation LBrace,
6242 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006243 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6244 // For anonymous namespace, take the location of the left brace.
6245 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006246 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006247 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006248 bool IsStd = false;
6249 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006250 Scope *DeclRegionScope = NamespcScope->getParent();
6251
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006252 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006253 if (II) {
6254 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006255 // The identifier in an original-namespace-definition shall not
6256 // have been previously defined in the declarative region in
6257 // which the original-namespace-definition appears. The
6258 // identifier in an original-namespace-definition is the name of
6259 // the namespace. Subsequently in that declarative region, it is
6260 // treated as an original-namespace-name.
6261 //
6262 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006263 // look through using directives, just look for any ordinary names.
6264
6265 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006266 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6267 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006268 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006269 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6270 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6271 ++I) {
6272 if ((*I)->getIdentifierNamespace() & IDNS) {
6273 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006274 break;
6275 }
6276 }
6277
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006278 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6279
6280 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006281 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006282 if (IsInline != PrevNS->isInline())
6283 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6284 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006285 } else if (PrevDecl) {
6286 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006287 Diag(Loc, diag::err_redefinition_different_kind)
6288 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006289 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006290 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006291 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006292 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006293 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006294 // This is the first "real" definition of the namespace "std", so update
6295 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006296 PrevNS = getStdNamespace();
6297 IsStd = true;
6298 AddToKnown = !IsInline;
6299 } else {
6300 // We've seen this namespace for the first time.
6301 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006302 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006303 } else {
John McCall9aeed322009-10-01 00:25:31 +00006304 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006305
6306 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006307 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006308 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006309 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006310 } else {
6311 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006312 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006313 }
6314
Richard Smithd1a55a62012-10-04 22:13:39 +00006315 if (PrevNS && IsInline != PrevNS->isInline())
6316 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6317 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006318 }
6319
6320 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6321 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006322 if (IsInvalid)
6323 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006324
6325 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006326
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006327 // FIXME: Should we be merging attributes?
6328 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006329 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006330
6331 if (IsStd)
6332 StdNamespace = Namespc;
6333 if (AddToKnown)
6334 KnownNamespaces[Namespc] = false;
6335
6336 if (II) {
6337 PushOnScopeChains(Namespc, DeclRegionScope);
6338 } else {
6339 // Link the anonymous namespace into its parent.
6340 DeclContext *Parent = CurContext->getRedeclContext();
6341 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6342 TU->setAnonymousNamespace(Namespc);
6343 } else {
6344 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006345 }
John McCall9aeed322009-10-01 00:25:31 +00006346
Douglas Gregora4181472010-03-24 00:46:35 +00006347 CurContext->addDecl(Namespc);
6348
John McCall9aeed322009-10-01 00:25:31 +00006349 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6350 // behaves as if it were replaced by
6351 // namespace unique { /* empty body */ }
6352 // using namespace unique;
6353 // namespace unique { namespace-body }
6354 // where all occurrences of 'unique' in a translation unit are
6355 // replaced by the same identifier and this identifier differs
6356 // from all other identifiers in the entire program.
6357
6358 // We just create the namespace with an empty name and then add an
6359 // implicit using declaration, just like the standard suggests.
6360 //
6361 // CodeGen enforces the "universally unique" aspect by giving all
6362 // declarations semantically contained within an anonymous
6363 // namespace internal linkage.
6364
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006365 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006366 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006367 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006368 /* 'using' */ LBrace,
6369 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006370 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006371 /* identifier */ SourceLocation(),
6372 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006373 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006374 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006375 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006376 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006377 }
6378
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006379 ActOnDocumentableDecl(Namespc);
6380
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006381 // Although we could have an invalid decl (i.e. the namespace name is a
6382 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006383 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6384 // for the namespace has the declarations that showed up in that particular
6385 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006386 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006387 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006388}
6389
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006390/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6391/// is a namespace alias, returns the namespace it points to.
6392static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6393 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6394 return AD->getNamespace();
6395 return dyn_cast_or_null<NamespaceDecl>(D);
6396}
6397
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006398/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6399/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006400void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006401 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6402 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006403 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006404 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006405 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006406 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006407}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006408
John McCall384aff82010-08-25 07:42:41 +00006409CXXRecordDecl *Sema::getStdBadAlloc() const {
6410 return cast_or_null<CXXRecordDecl>(
6411 StdBadAlloc.get(Context.getExternalSource()));
6412}
6413
6414NamespaceDecl *Sema::getStdNamespace() const {
6415 return cast_or_null<NamespaceDecl>(
6416 StdNamespace.get(Context.getExternalSource()));
6417}
6418
Douglas Gregor66992202010-06-29 17:53:46 +00006419/// \brief Retrieve the special "std" namespace, which may require us to
6420/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006421NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006422 if (!StdNamespace) {
6423 // The "std" namespace has not yet been defined, so build one implicitly.
6424 StdNamespace = NamespaceDecl::Create(Context,
6425 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006426 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006427 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006428 &PP.getIdentifierTable().get("std"),
6429 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006430 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006431 }
6432
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006433 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006434}
6435
Sebastian Redl395e04d2012-01-17 22:49:33 +00006436bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006437 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006438 "Looking for std::initializer_list outside of C++.");
6439
6440 // We're looking for implicit instantiations of
6441 // template <typename E> class std::initializer_list.
6442
6443 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6444 return false;
6445
Sebastian Redl84760e32012-01-17 22:49:58 +00006446 ClassTemplateDecl *Template = 0;
6447 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006448
Sebastian Redl84760e32012-01-17 22:49:58 +00006449 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006450
Sebastian Redl84760e32012-01-17 22:49:58 +00006451 ClassTemplateSpecializationDecl *Specialization =
6452 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6453 if (!Specialization)
6454 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006455
Sebastian Redl84760e32012-01-17 22:49:58 +00006456 Template = Specialization->getSpecializedTemplate();
6457 Arguments = Specialization->getTemplateArgs().data();
6458 } else if (const TemplateSpecializationType *TST =
6459 Ty->getAs<TemplateSpecializationType>()) {
6460 Template = dyn_cast_or_null<ClassTemplateDecl>(
6461 TST->getTemplateName().getAsTemplateDecl());
6462 Arguments = TST->getArgs();
6463 }
6464 if (!Template)
6465 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006466
6467 if (!StdInitializerList) {
6468 // Haven't recognized std::initializer_list yet, maybe this is it.
6469 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6470 if (TemplateClass->getIdentifier() !=
6471 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006472 !getStdNamespace()->InEnclosingNamespaceSetOf(
6473 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006474 return false;
6475 // This is a template called std::initializer_list, but is it the right
6476 // template?
6477 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006478 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006479 return false;
6480 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6481 return false;
6482
6483 // It's the right template.
6484 StdInitializerList = Template;
6485 }
6486
6487 if (Template != StdInitializerList)
6488 return false;
6489
6490 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006491 if (Element)
6492 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006493 return true;
6494}
6495
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006496static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6497 NamespaceDecl *Std = S.getStdNamespace();
6498 if (!Std) {
6499 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6500 return 0;
6501 }
6502
6503 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6504 Loc, Sema::LookupOrdinaryName);
6505 if (!S.LookupQualifiedName(Result, Std)) {
6506 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6507 return 0;
6508 }
6509 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6510 if (!Template) {
6511 Result.suppressDiagnostics();
6512 // We found something weird. Complain about the first thing we found.
6513 NamedDecl *Found = *Result.begin();
6514 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6515 return 0;
6516 }
6517
6518 // We found some template called std::initializer_list. Now verify that it's
6519 // correct.
6520 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006521 if (Params->getMinRequiredArguments() != 1 ||
6522 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006523 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6524 return 0;
6525 }
6526
6527 return Template;
6528}
6529
6530QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6531 if (!StdInitializerList) {
6532 StdInitializerList = LookupStdInitializerList(*this, Loc);
6533 if (!StdInitializerList)
6534 return QualType();
6535 }
6536
6537 TemplateArgumentListInfo Args(Loc, Loc);
6538 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6539 Context.getTrivialTypeSourceInfo(Element,
6540 Loc)));
6541 return Context.getCanonicalType(
6542 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6543}
6544
Sebastian Redl98d36062012-01-17 22:50:14 +00006545bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6546 // C++ [dcl.init.list]p2:
6547 // A constructor is an initializer-list constructor if its first parameter
6548 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6549 // std::initializer_list<E> for some type E, and either there are no other
6550 // parameters or else all other parameters have default arguments.
6551 if (Ctor->getNumParams() < 1 ||
6552 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6553 return false;
6554
6555 QualType ArgType = Ctor->getParamDecl(0)->getType();
6556 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6557 ArgType = RT->getPointeeType().getUnqualifiedType();
6558
6559 return isStdInitializerList(ArgType, 0);
6560}
6561
Douglas Gregor9172aa62011-03-26 22:25:30 +00006562/// \brief Determine whether a using statement is in a context where it will be
6563/// apply in all contexts.
6564static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6565 switch (CurContext->getDeclKind()) {
6566 case Decl::TranslationUnit:
6567 return true;
6568 case Decl::LinkageSpec:
6569 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6570 default:
6571 return false;
6572 }
6573}
6574
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006575namespace {
6576
6577// Callback to only accept typo corrections that are namespaces.
6578class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6579 public:
6580 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6581 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6582 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6583 }
6584 return false;
6585 }
6586};
6587
6588}
6589
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006590static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6591 CXXScopeSpec &SS,
6592 SourceLocation IdentLoc,
6593 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006594 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006595 R.clear();
6596 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006597 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006598 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006599 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6600 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006601 if (DeclContext *DC = S.computeDeclContext(SS, false))
6602 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6603 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006604 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6605 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006606 else
6607 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6608 << Ident << CorrectedQuotedStr
6609 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006610
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006611 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6612 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006613
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006614 R.addDecl(Corrected.getCorrectionDecl());
6615 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006616 }
6617 return false;
6618}
6619
John McCalld226f652010-08-21 09:40:31 +00006620Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006621 SourceLocation UsingLoc,
6622 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006623 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006624 SourceLocation IdentLoc,
6625 IdentifierInfo *NamespcName,
6626 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006627 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6628 assert(NamespcName && "Invalid NamespcName.");
6629 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006630
6631 // This can only happen along a recovery path.
6632 while (S->getFlags() & Scope::TemplateParamScope)
6633 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006634 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006635
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006636 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006637 NestedNameSpecifier *Qualifier = 0;
6638 if (SS.isSet())
6639 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6640
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006641 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006642 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6643 LookupParsedName(R, S, &SS);
6644 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006645 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006646
Douglas Gregor66992202010-06-29 17:53:46 +00006647 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006648 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006649 // Allow "using namespace std;" or "using namespace ::std;" even if
6650 // "std" hasn't been defined yet, for GCC compatibility.
6651 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6652 NamespcName->isStr("std")) {
6653 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006654 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006655 R.resolveKind();
6656 }
6657 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006658 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006659 }
6660
John McCallf36e02d2009-10-09 21:13:30 +00006661 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006662 NamedDecl *Named = R.getFoundDecl();
6663 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6664 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006665 // C++ [namespace.udir]p1:
6666 // A using-directive specifies that the names in the nominated
6667 // namespace can be used in the scope in which the
6668 // using-directive appears after the using-directive. During
6669 // unqualified name lookup (3.4.1), the names appear as if they
6670 // were declared in the nearest enclosing namespace which
6671 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006672 // namespace. [Note: in this context, "contains" means "contains
6673 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006674
6675 // Find enclosing context containing both using-directive and
6676 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006677 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006678 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6679 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6680 CommonAncestor = CommonAncestor->getParent();
6681
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006682 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006683 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006684 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006685
Douglas Gregor9172aa62011-03-26 22:25:30 +00006686 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006687 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006688 Diag(IdentLoc, diag::warn_using_directive_in_header);
6689 }
6690
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006691 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006692 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006693 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006694 }
6695
Richard Smith6b3d3e52013-02-20 19:22:51 +00006696 if (UDir)
6697 ProcessDeclAttributeList(S, UDir, AttrList);
6698
John McCalld226f652010-08-21 09:40:31 +00006699 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006700}
6701
6702void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006703 // If the scope has an associated entity and the using directive is at
6704 // namespace or translation unit scope, add the UsingDirectiveDecl into
6705 // its lookup structure so qualified name lookup can find it.
6706 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6707 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006708 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006709 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006710 // Otherwise, it is at block sope. The using-directives will affect lookup
6711 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006712 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006713}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006714
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006715
John McCalld226f652010-08-21 09:40:31 +00006716Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006717 AccessSpecifier AS,
6718 bool HasUsingKeyword,
6719 SourceLocation UsingLoc,
6720 CXXScopeSpec &SS,
6721 UnqualifiedId &Name,
6722 AttributeList *AttrList,
6723 bool IsTypeName,
6724 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006725 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006726
Douglas Gregor12c118a2009-11-04 16:30:06 +00006727 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006728 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006729 case UnqualifiedId::IK_Identifier:
6730 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006731 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006732 case UnqualifiedId::IK_ConversionFunctionId:
6733 break;
6734
6735 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006736 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006737 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006738 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006739 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006740 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006741 diag::err_using_decl_constructor)
6742 << SS.getRange();
6743
Richard Smith80ad52f2013-01-02 11:42:31 +00006744 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006745
John McCalld226f652010-08-21 09:40:31 +00006746 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006747
6748 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006749 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006750 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006751 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006752
6753 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006754 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006755 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006756 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006757 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006758
6759 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6760 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006761 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006762 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006763
Richard Smith07b0fdc2013-03-18 21:12:30 +00006764 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006765 // TODO: store that the declaration was written without 'using' and
6766 // talk about access decls instead of using decls in the
6767 // diagnostics.
6768 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006769 UsingLoc = Name.getLocStart();
Richard Smith1b2209f2013-06-13 02:12:17 +00006770
6771 Diag(UsingLoc,
6772 getLangOpts().CPlusPlus11 ? diag::err_access_decl
6773 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006774 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006775 }
6776
Douglas Gregor56c04582010-12-16 00:46:58 +00006777 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6778 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6779 return 0;
6780
John McCall9488ea12009-11-17 05:59:44 +00006781 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006782 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006783 /* IsInstantiation */ false,
6784 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006785 if (UD)
6786 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006787
John McCalld226f652010-08-21 09:40:31 +00006788 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006789}
6790
Douglas Gregor09acc982010-07-07 23:08:52 +00006791/// \brief Determine whether a using declaration considers the given
6792/// declarations as "equivalent", e.g., if they are redeclarations of
6793/// the same entity or are both typedefs of the same type.
6794static bool
6795IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6796 bool &SuppressRedeclaration) {
6797 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6798 SuppressRedeclaration = false;
6799 return true;
6800 }
6801
Richard Smith162e1c12011-04-15 14:24:37 +00006802 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6803 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006804 SuppressRedeclaration = true;
6805 return Context.hasSameType(TD1->getUnderlyingType(),
6806 TD2->getUnderlyingType());
6807 }
6808
6809 return false;
6810}
6811
6812
John McCall9f54ad42009-12-10 09:41:52 +00006813/// Determines whether to create a using shadow decl for a particular
6814/// decl, given the set of decls existing prior to this using lookup.
6815bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6816 const LookupResult &Previous) {
6817 // Diagnose finding a decl which is not from a base class of the
6818 // current class. We do this now because there are cases where this
6819 // function will silently decide not to build a shadow decl, which
6820 // will pre-empt further diagnostics.
6821 //
6822 // We don't need to do this in C++0x because we do the check once on
6823 // the qualifier.
6824 //
6825 // FIXME: diagnose the following if we care enough:
6826 // struct A { int foo; };
6827 // struct B : A { using A::foo; };
6828 // template <class T> struct C : A {};
6829 // template <class T> struct D : C<T> { using B::foo; } // <---
6830 // This is invalid (during instantiation) in C++03 because B::foo
6831 // resolves to the using decl in B, which is not a base class of D<T>.
6832 // We can't diagnose it immediately because C<T> is an unknown
6833 // specialization. The UsingShadowDecl in D<T> then points directly
6834 // to A::foo, which will look well-formed when we instantiate.
6835 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006836 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006837 DeclContext *OrigDC = Orig->getDeclContext();
6838
6839 // Handle enums and anonymous structs.
6840 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6841 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6842 while (OrigRec->isAnonymousStructOrUnion())
6843 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6844
6845 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6846 if (OrigDC == CurContext) {
6847 Diag(Using->getLocation(),
6848 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006849 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006850 Diag(Orig->getLocation(), diag::note_using_decl_target);
6851 return true;
6852 }
6853
Douglas Gregordc355712011-02-25 00:36:19 +00006854 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006855 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006856 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006857 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006858 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006859 Diag(Orig->getLocation(), diag::note_using_decl_target);
6860 return true;
6861 }
6862 }
6863
6864 if (Previous.empty()) return false;
6865
6866 NamedDecl *Target = Orig;
6867 if (isa<UsingShadowDecl>(Target))
6868 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6869
John McCalld7533ec2009-12-11 02:33:26 +00006870 // If the target happens to be one of the previous declarations, we
6871 // don't have a conflict.
6872 //
6873 // FIXME: but we might be increasing its access, in which case we
6874 // should redeclare it.
6875 NamedDecl *NonTag = 0, *Tag = 0;
6876 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6877 I != E; ++I) {
6878 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006879 bool Result;
6880 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6881 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006882
6883 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6884 }
6885
John McCall9f54ad42009-12-10 09:41:52 +00006886 if (Target->isFunctionOrFunctionTemplate()) {
6887 FunctionDecl *FD;
6888 if (isa<FunctionTemplateDecl>(Target))
6889 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6890 else
6891 FD = cast<FunctionDecl>(Target);
6892
6893 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006894 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006895 case Ovl_Overload:
6896 return false;
6897
6898 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006899 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006900 break;
6901
6902 // We found a decl with the exact signature.
6903 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006904 // If we're in a record, we want to hide the target, so we
6905 // return true (without a diagnostic) to tell the caller not to
6906 // build a shadow decl.
6907 if (CurContext->isRecord())
6908 return true;
6909
6910 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006911 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006912 break;
6913 }
6914
6915 Diag(Target->getLocation(), diag::note_using_decl_target);
6916 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6917 return true;
6918 }
6919
6920 // Target is not a function.
6921
John McCall9f54ad42009-12-10 09:41:52 +00006922 if (isa<TagDecl>(Target)) {
6923 // No conflict between a tag and a non-tag.
6924 if (!Tag) return false;
6925
John McCall41ce66f2009-12-10 19:51:03 +00006926 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006927 Diag(Target->getLocation(), diag::note_using_decl_target);
6928 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6929 return true;
6930 }
6931
6932 // No conflict between a tag and a non-tag.
6933 if (!NonTag) return false;
6934
John McCall41ce66f2009-12-10 19:51:03 +00006935 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006936 Diag(Target->getLocation(), diag::note_using_decl_target);
6937 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6938 return true;
6939}
6940
John McCall9488ea12009-11-17 05:59:44 +00006941/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006942UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006943 UsingDecl *UD,
6944 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006945
6946 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006947 NamedDecl *Target = Orig;
6948 if (isa<UsingShadowDecl>(Target)) {
6949 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6950 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006951 }
6952
6953 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006954 = UsingShadowDecl::Create(Context, CurContext,
6955 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006956 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006957
6958 Shadow->setAccess(UD->getAccess());
6959 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6960 Shadow->setInvalidDecl();
6961
John McCall9488ea12009-11-17 05:59:44 +00006962 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006963 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006964 else
John McCall604e7f12009-12-08 07:46:18 +00006965 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006966
John McCall604e7f12009-12-08 07:46:18 +00006967
John McCall9f54ad42009-12-10 09:41:52 +00006968 return Shadow;
6969}
John McCall604e7f12009-12-08 07:46:18 +00006970
John McCall9f54ad42009-12-10 09:41:52 +00006971/// Hides a using shadow declaration. This is required by the current
6972/// using-decl implementation when a resolvable using declaration in a
6973/// class is followed by a declaration which would hide or override
6974/// one or more of the using decl's targets; for example:
6975///
6976/// struct Base { void foo(int); };
6977/// struct Derived : Base {
6978/// using Base::foo;
6979/// void foo(int);
6980/// };
6981///
6982/// The governing language is C++03 [namespace.udecl]p12:
6983///
6984/// When a using-declaration brings names from a base class into a
6985/// derived class scope, member functions in the derived class
6986/// override and/or hide member functions with the same name and
6987/// parameter types in a base class (rather than conflicting).
6988///
6989/// There are two ways to implement this:
6990/// (1) optimistically create shadow decls when they're not hidden
6991/// by existing declarations, or
6992/// (2) don't create any shadow decls (or at least don't make them
6993/// visible) until we've fully parsed/instantiated the class.
6994/// The problem with (1) is that we might have to retroactively remove
6995/// a shadow decl, which requires several O(n) operations because the
6996/// decl structures are (very reasonably) not designed for removal.
6997/// (2) avoids this but is very fiddly and phase-dependent.
6998void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006999 if (Shadow->getDeclName().getNameKind() ==
7000 DeclarationName::CXXConversionFunctionName)
7001 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7002
John McCall9f54ad42009-12-10 09:41:52 +00007003 // Remove it from the DeclContext...
7004 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007005
John McCall9f54ad42009-12-10 09:41:52 +00007006 // ...and the scope, if applicable...
7007 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007008 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007009 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007010 }
7011
John McCall9f54ad42009-12-10 09:41:52 +00007012 // ...and the using decl.
7013 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7014
7015 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007016 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007017}
7018
John McCall7ba107a2009-11-18 02:36:19 +00007019/// Builds a using declaration.
7020///
7021/// \param IsInstantiation - Whether this call arises from an
7022/// instantiation of an unresolved using declaration. We treat
7023/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007024NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7025 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007026 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007027 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007028 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007029 bool IsInstantiation,
7030 bool IsTypeName,
7031 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007032 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007033 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007034 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007035
Anders Carlsson550b14b2009-08-28 05:49:21 +00007036 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007037
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007038 if (SS.isEmpty()) {
7039 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007040 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007041 }
Mike Stump1eb44332009-09-09 15:08:12 +00007042
John McCall9f54ad42009-12-10 09:41:52 +00007043 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007044 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007045 ForRedeclaration);
7046 Previous.setHideTags(false);
7047 if (S) {
7048 LookupName(Previous, S);
7049
7050 // It is really dumb that we have to do this.
7051 LookupResult::Filter F = Previous.makeFilter();
7052 while (F.hasNext()) {
7053 NamedDecl *D = F.next();
7054 if (!isDeclInScope(D, CurContext, S))
7055 F.erase();
7056 }
7057 F.done();
7058 } else {
7059 assert(IsInstantiation && "no scope in non-instantiation");
7060 assert(CurContext->isRecord() && "scope not record in instantiation");
7061 LookupQualifiedName(Previous, CurContext);
7062 }
7063
John McCall9f54ad42009-12-10 09:41:52 +00007064 // Check for invalid redeclarations.
7065 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7066 return 0;
7067
7068 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007069 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7070 return 0;
7071
John McCallaf8e6ed2009-11-12 03:15:40 +00007072 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007073 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007074 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007075 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00007076 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00007077 // FIXME: not all declaration name kinds are legal here
7078 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7079 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007080 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007081 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007082 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007083 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7084 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007085 }
John McCalled976492009-12-04 22:46:56 +00007086 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007087 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7088 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007089 }
John McCalled976492009-12-04 22:46:56 +00007090 D->setAccess(AS);
7091 CurContext->addDecl(D);
7092
7093 if (!LookupContext) return D;
7094 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007095
John McCall77bb1aa2010-05-01 00:40:08 +00007096 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007097 UD->setInvalidDecl();
7098 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007099 }
7100
Richard Smithc5a89a12012-04-02 01:30:27 +00007101 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007102 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007103 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007104 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007105 return UD;
7106 }
7107
7108 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007109
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007110 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007111
John McCall604e7f12009-12-08 07:46:18 +00007112 // Unlike most lookups, we don't always want to hide tag
7113 // declarations: tag names are visible through the using declaration
7114 // even if hidden by ordinary names, *except* in a dependent context
7115 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007116 if (!IsInstantiation)
7117 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007118
John McCallb9abd8722012-04-07 03:04:20 +00007119 // For the purposes of this lookup, we have a base object type
7120 // equal to that of the current context.
7121 if (CurContext->isRecord()) {
7122 R.setBaseObjectType(
7123 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7124 }
7125
John McCalla24dc2e2009-11-17 02:14:36 +00007126 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007127
John McCallf36e02d2009-10-09 21:13:30 +00007128 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00007129 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007130 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007131 UD->setInvalidDecl();
7132 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007133 }
7134
John McCalled976492009-12-04 22:46:56 +00007135 if (R.isAmbiguous()) {
7136 UD->setInvalidDecl();
7137 return UD;
7138 }
Mike Stump1eb44332009-09-09 15:08:12 +00007139
John McCall7ba107a2009-11-18 02:36:19 +00007140 if (IsTypeName) {
7141 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007142 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007143 Diag(IdentLoc, diag::err_using_typename_non_type);
7144 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7145 Diag((*I)->getUnderlyingDecl()->getLocation(),
7146 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007147 UD->setInvalidDecl();
7148 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007149 }
7150 } else {
7151 // If we asked for a non-typename and we got a type, error out,
7152 // but only if this is an instantiation of an unresolved using
7153 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007154 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007155 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7156 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007157 UD->setInvalidDecl();
7158 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007159 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007160 }
7161
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007162 // C++0x N2914 [namespace.udecl]p6:
7163 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007164 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007165 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7166 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007167 UD->setInvalidDecl();
7168 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007169 }
Mike Stump1eb44332009-09-09 15:08:12 +00007170
John McCall9f54ad42009-12-10 09:41:52 +00007171 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7172 if (!CheckUsingShadowDecl(UD, *I, Previous))
7173 BuildUsingShadowDecl(S, UD, *I);
7174 }
John McCall9488ea12009-11-17 05:59:44 +00007175
7176 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007177}
7178
Sebastian Redlf677ea32011-02-05 19:23:19 +00007179/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007180bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7181 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007182
Douglas Gregordc355712011-02-25 00:36:19 +00007183 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007184 assert(SourceType &&
7185 "Using decl naming constructor doesn't have type in scope spec.");
7186 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7187
7188 // Check whether the named type is a direct base class.
7189 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7190 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7191 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7192 BaseIt != BaseE; ++BaseIt) {
7193 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7194 if (CanonicalSourceType == BaseType)
7195 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007196 if (BaseIt->getType()->isDependentType())
7197 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007198 }
7199
7200 if (BaseIt == BaseE) {
7201 // Did not find SourceType in the bases.
7202 Diag(UD->getUsingLocation(),
7203 diag::err_using_decl_constructor_not_in_direct_base)
7204 << UD->getNameInfo().getSourceRange()
7205 << QualType(SourceType, 0) << TargetClass;
7206 return true;
7207 }
7208
Richard Smithc5a89a12012-04-02 01:30:27 +00007209 if (!CurContext->isDependentContext())
7210 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007211
7212 return false;
7213}
7214
John McCall9f54ad42009-12-10 09:41:52 +00007215/// Checks that the given using declaration is not an invalid
7216/// redeclaration. Note that this is checking only for the using decl
7217/// itself, not for any ill-formedness among the UsingShadowDecls.
7218bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7219 bool isTypeName,
7220 const CXXScopeSpec &SS,
7221 SourceLocation NameLoc,
7222 const LookupResult &Prev) {
7223 // C++03 [namespace.udecl]p8:
7224 // C++0x [namespace.udecl]p10:
7225 // A using-declaration is a declaration and can therefore be used
7226 // repeatedly where (and only where) multiple declarations are
7227 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007228 //
John McCall8a726212010-11-29 18:01:58 +00007229 // That's in non-member contexts.
7230 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007231 return false;
7232
7233 NestedNameSpecifier *Qual
7234 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7235
7236 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7237 NamedDecl *D = *I;
7238
7239 bool DTypename;
7240 NestedNameSpecifier *DQual;
7241 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7242 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007243 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007244 } else if (UnresolvedUsingValueDecl *UD
7245 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7246 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007247 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007248 } else if (UnresolvedUsingTypenameDecl *UD
7249 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7250 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007251 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007252 } else continue;
7253
7254 // using decls differ if one says 'typename' and the other doesn't.
7255 // FIXME: non-dependent using decls?
7256 if (isTypeName != DTypename) continue;
7257
7258 // using decls differ if they name different scopes (but note that
7259 // template instantiation can cause this check to trigger when it
7260 // didn't before instantiation).
7261 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7262 Context.getCanonicalNestedNameSpecifier(DQual))
7263 continue;
7264
7265 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007266 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007267 return true;
7268 }
7269
7270 return false;
7271}
7272
John McCall604e7f12009-12-08 07:46:18 +00007273
John McCalled976492009-12-04 22:46:56 +00007274/// Checks that the given nested-name qualifier used in a using decl
7275/// in the current context is appropriately related to the current
7276/// scope. If an error is found, diagnoses it and returns true.
7277bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7278 const CXXScopeSpec &SS,
7279 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007280 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007281
John McCall604e7f12009-12-08 07:46:18 +00007282 if (!CurContext->isRecord()) {
7283 // C++03 [namespace.udecl]p3:
7284 // C++0x [namespace.udecl]p8:
7285 // A using-declaration for a class member shall be a member-declaration.
7286
7287 // If we weren't able to compute a valid scope, it must be a
7288 // dependent class scope.
7289 if (!NamedContext || NamedContext->isRecord()) {
7290 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7291 << SS.getRange();
7292 return true;
7293 }
7294
7295 // Otherwise, everything is known to be fine.
7296 return false;
7297 }
7298
7299 // The current scope is a record.
7300
7301 // If the named context is dependent, we can't decide much.
7302 if (!NamedContext) {
7303 // FIXME: in C++0x, we can diagnose if we can prove that the
7304 // nested-name-specifier does not refer to a base class, which is
7305 // still possible in some cases.
7306
7307 // Otherwise we have to conservatively report that things might be
7308 // okay.
7309 return false;
7310 }
7311
7312 if (!NamedContext->isRecord()) {
7313 // Ideally this would point at the last name in the specifier,
7314 // but we don't have that level of source info.
7315 Diag(SS.getRange().getBegin(),
7316 diag::err_using_decl_nested_name_specifier_is_not_class)
7317 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7318 return true;
7319 }
7320
Douglas Gregor6fb07292010-12-21 07:41:49 +00007321 if (!NamedContext->isDependentContext() &&
7322 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7323 return true;
7324
Richard Smith80ad52f2013-01-02 11:42:31 +00007325 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007326 // C++0x [namespace.udecl]p3:
7327 // In a using-declaration used as a member-declaration, the
7328 // nested-name-specifier shall name a base class of the class
7329 // being defined.
7330
7331 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7332 cast<CXXRecordDecl>(NamedContext))) {
7333 if (CurContext == NamedContext) {
7334 Diag(NameLoc,
7335 diag::err_using_decl_nested_name_specifier_is_current_class)
7336 << SS.getRange();
7337 return true;
7338 }
7339
7340 Diag(SS.getRange().getBegin(),
7341 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7342 << (NestedNameSpecifier*) SS.getScopeRep()
7343 << cast<CXXRecordDecl>(CurContext)
7344 << SS.getRange();
7345 return true;
7346 }
7347
7348 return false;
7349 }
7350
7351 // C++03 [namespace.udecl]p4:
7352 // A using-declaration used as a member-declaration shall refer
7353 // to a member of a base class of the class being defined [etc.].
7354
7355 // Salient point: SS doesn't have to name a base class as long as
7356 // lookup only finds members from base classes. Therefore we can
7357 // diagnose here only if we can prove that that can't happen,
7358 // i.e. if the class hierarchies provably don't intersect.
7359
7360 // TODO: it would be nice if "definitely valid" results were cached
7361 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7362 // need to be repeated.
7363
7364 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007365 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007366
7367 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7368 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7369 Data->Bases.insert(Base);
7370 return true;
7371 }
7372
7373 bool hasDependentBases(const CXXRecordDecl *Class) {
7374 return !Class->forallBases(collect, this);
7375 }
7376
7377 /// Returns true if the base is dependent or is one of the
7378 /// accumulated base classes.
7379 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7380 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7381 return !Data->Bases.count(Base);
7382 }
7383
7384 bool mightShareBases(const CXXRecordDecl *Class) {
7385 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7386 }
7387 };
7388
7389 UserData Data;
7390
7391 // Returns false if we find a dependent base.
7392 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7393 return false;
7394
7395 // Returns false if the class has a dependent base or if it or one
7396 // of its bases is present in the base set of the current context.
7397 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7398 return false;
7399
7400 Diag(SS.getRange().getBegin(),
7401 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7402 << (NestedNameSpecifier*) SS.getScopeRep()
7403 << cast<CXXRecordDecl>(CurContext)
7404 << SS.getRange();
7405
7406 return true;
John McCalled976492009-12-04 22:46:56 +00007407}
7408
Richard Smith162e1c12011-04-15 14:24:37 +00007409Decl *Sema::ActOnAliasDeclaration(Scope *S,
7410 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007411 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007412 SourceLocation UsingLoc,
7413 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007414 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007415 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007416 // Skip up to the relevant declaration scope.
7417 while (S->getFlags() & Scope::TemplateParamScope)
7418 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007419 assert((S->getFlags() & Scope::DeclScope) &&
7420 "got alias-declaration outside of declaration scope");
7421
7422 if (Type.isInvalid())
7423 return 0;
7424
7425 bool Invalid = false;
7426 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7427 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007428 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007429
7430 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7431 return 0;
7432
7433 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007434 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007435 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007436 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7437 TInfo->getTypeLoc().getBeginLoc());
7438 }
Richard Smith162e1c12011-04-15 14:24:37 +00007439
7440 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7441 LookupName(Previous, S);
7442
7443 // Warn about shadowing the name of a template parameter.
7444 if (Previous.isSingleResult() &&
7445 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007446 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007447 Previous.clear();
7448 }
7449
7450 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7451 "name in alias declaration must be an identifier");
7452 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7453 Name.StartLocation,
7454 Name.Identifier, TInfo);
7455
7456 NewTD->setAccess(AS);
7457
7458 if (Invalid)
7459 NewTD->setInvalidDecl();
7460
Richard Smith6b3d3e52013-02-20 19:22:51 +00007461 ProcessDeclAttributeList(S, NewTD, AttrList);
7462
Richard Smith3e4c6c42011-05-05 21:57:07 +00007463 CheckTypedefForVariablyModifiedType(S, NewTD);
7464 Invalid |= NewTD->isInvalidDecl();
7465
Richard Smith162e1c12011-04-15 14:24:37 +00007466 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007467
7468 NamedDecl *NewND;
7469 if (TemplateParamLists.size()) {
7470 TypeAliasTemplateDecl *OldDecl = 0;
7471 TemplateParameterList *OldTemplateParams = 0;
7472
7473 if (TemplateParamLists.size() != 1) {
7474 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007475 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7476 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007477 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007478 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007479
7480 // Only consider previous declarations in the same scope.
7481 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7482 /*ExplicitInstantiationOrSpecialization*/false);
7483 if (!Previous.empty()) {
7484 Redeclaration = true;
7485
7486 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7487 if (!OldDecl && !Invalid) {
7488 Diag(UsingLoc, diag::err_redefinition_different_kind)
7489 << Name.Identifier;
7490
7491 NamedDecl *OldD = Previous.getRepresentativeDecl();
7492 if (OldD->getLocation().isValid())
7493 Diag(OldD->getLocation(), diag::note_previous_definition);
7494
7495 Invalid = true;
7496 }
7497
7498 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7499 if (TemplateParameterListsAreEqual(TemplateParams,
7500 OldDecl->getTemplateParameters(),
7501 /*Complain=*/true,
7502 TPL_TemplateMatch))
7503 OldTemplateParams = OldDecl->getTemplateParameters();
7504 else
7505 Invalid = true;
7506
7507 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7508 if (!Invalid &&
7509 !Context.hasSameType(OldTD->getUnderlyingType(),
7510 NewTD->getUnderlyingType())) {
7511 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7512 // but we can't reasonably accept it.
7513 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7514 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7515 if (OldTD->getLocation().isValid())
7516 Diag(OldTD->getLocation(), diag::note_previous_definition);
7517 Invalid = true;
7518 }
7519 }
7520 }
7521
7522 // Merge any previous default template arguments into our parameters,
7523 // and check the parameter list.
7524 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7525 TPC_TypeAliasTemplate))
7526 return 0;
7527
7528 TypeAliasTemplateDecl *NewDecl =
7529 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7530 Name.Identifier, TemplateParams,
7531 NewTD);
7532
7533 NewDecl->setAccess(AS);
7534
7535 if (Invalid)
7536 NewDecl->setInvalidDecl();
7537 else if (OldDecl)
7538 NewDecl->setPreviousDeclaration(OldDecl);
7539
7540 NewND = NewDecl;
7541 } else {
7542 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7543 NewND = NewTD;
7544 }
Richard Smith162e1c12011-04-15 14:24:37 +00007545
7546 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007547 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007548
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007549 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007550 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007551}
7552
John McCalld226f652010-08-21 09:40:31 +00007553Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007554 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007555 SourceLocation AliasLoc,
7556 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007557 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007558 SourceLocation IdentLoc,
7559 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007560
Anders Carlsson81c85c42009-03-28 23:53:49 +00007561 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007562 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7563 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007564
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007565 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007566 NamedDecl *PrevDecl
7567 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7568 ForRedeclaration);
7569 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7570 PrevDecl = 0;
7571
7572 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007573 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007574 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007575 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007576 // FIXME: At some point, we'll want to create the (redundant)
7577 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007578 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007579 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007580 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007581 }
Mike Stump1eb44332009-09-09 15:08:12 +00007582
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007583 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7584 diag::err_redefinition_different_kind;
7585 Diag(AliasLoc, DiagID) << Alias;
7586 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007587 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007588 }
7589
John McCalla24dc2e2009-11-17 02:14:36 +00007590 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007591 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007592
John McCallf36e02d2009-10-09 21:13:30 +00007593 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007594 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007595 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007596 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007597 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007598 }
Mike Stump1eb44332009-09-09 15:08:12 +00007599
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007600 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007601 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007602 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007603 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007604
John McCall3dbd3d52010-02-16 06:53:13 +00007605 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007606 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007607}
7608
Sean Hunt001cad92011-05-10 00:49:42 +00007609Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007610Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7611 CXXMethodDecl *MD) {
7612 CXXRecordDecl *ClassDecl = MD->getParent();
7613
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007614 // C++ [except.spec]p14:
7615 // An implicitly declared special member function (Clause 12) shall have an
7616 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007617 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007618 if (ClassDecl->isInvalidDecl())
7619 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007620
Sebastian Redl60618fa2011-03-12 11:50:43 +00007621 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007622 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7623 BEnd = ClassDecl->bases_end();
7624 B != BEnd; ++B) {
7625 if (B->isVirtual()) // Handled below.
7626 continue;
7627
Douglas Gregor18274032010-07-03 00:47:00 +00007628 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7629 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007630 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7631 // If this is a deleted function, add it anyway. This might be conformant
7632 // with the standard. This might not. I'm not sure. It might not matter.
7633 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007634 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007635 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007636 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007637
7638 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007639 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7640 BEnd = ClassDecl->vbases_end();
7641 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007642 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7643 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007644 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7645 // If this is a deleted function, add it anyway. This might be conformant
7646 // with the standard. This might not. I'm not sure. It might not matter.
7647 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007648 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007649 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007650 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007651
7652 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007653 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7654 FEnd = ClassDecl->field_end();
7655 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007656 if (F->hasInClassInitializer()) {
7657 if (Expr *E = F->getInClassInitializer())
7658 ExceptSpec.CalledExpr(E);
7659 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007660 // DR1351:
7661 // If the brace-or-equal-initializer of a non-static data member
7662 // invokes a defaulted default constructor of its class or of an
7663 // enclosing class in a potentially evaluated subexpression, the
7664 // program is ill-formed.
7665 //
7666 // This resolution is unworkable: the exception specification of the
7667 // default constructor can be needed in an unevaluated context, in
7668 // particular, in the operand of a noexcept-expression, and we can be
7669 // unable to compute an exception specification for an enclosed class.
7670 //
7671 // We do not allow an in-class initializer to require the evaluation
7672 // of the exception specification for any in-class initializer whose
7673 // definition is not lexically complete.
7674 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007675 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007676 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007677 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7678 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7679 // If this is a deleted function, add it anyway. This might be conformant
7680 // with the standard. This might not. I'm not sure. It might not matter.
7681 // In particular, the problem is that this function never gets called. It
7682 // might just be ill-formed because this function attempts to refer to
7683 // a deleted function here.
7684 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007685 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007686 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007687 }
John McCalle23cf432010-12-14 08:05:40 +00007688
Sean Hunt001cad92011-05-10 00:49:42 +00007689 return ExceptSpec;
7690}
7691
Richard Smith07b0fdc2013-03-18 21:12:30 +00007692Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007693Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7694 CXXRecordDecl *ClassDecl = CD->getParent();
7695
7696 // C++ [except.spec]p14:
7697 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007698 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007699 if (ClassDecl->isInvalidDecl())
7700 return ExceptSpec;
7701
7702 // Inherited constructor.
7703 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7704 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7705 // FIXME: Copying or moving the parameters could add extra exceptions to the
7706 // set, as could the default arguments for the inherited constructor. This
7707 // will be addressed when we implement the resolution of core issue 1351.
7708 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7709
7710 // Direct base-class constructors.
7711 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7712 BEnd = ClassDecl->bases_end();
7713 B != BEnd; ++B) {
7714 if (B->isVirtual()) // Handled below.
7715 continue;
7716
7717 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7718 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7719 if (BaseClassDecl == InheritedDecl)
7720 continue;
7721 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7722 if (Constructor)
7723 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7724 }
7725 }
7726
7727 // Virtual base-class constructors.
7728 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7729 BEnd = ClassDecl->vbases_end();
7730 B != BEnd; ++B) {
7731 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7732 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7733 if (BaseClassDecl == InheritedDecl)
7734 continue;
7735 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7736 if (Constructor)
7737 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7738 }
7739 }
7740
7741 // Field constructors.
7742 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7743 FEnd = ClassDecl->field_end();
7744 F != FEnd; ++F) {
7745 if (F->hasInClassInitializer()) {
7746 if (Expr *E = F->getInClassInitializer())
7747 ExceptSpec.CalledExpr(E);
7748 else if (!F->isInvalidDecl())
7749 Diag(CD->getLocation(),
7750 diag::err_in_class_initializer_references_def_ctor) << CD;
7751 } else if (const RecordType *RecordTy
7752 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7753 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7754 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7755 if (Constructor)
7756 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7757 }
7758 }
7759
Richard Smith07b0fdc2013-03-18 21:12:30 +00007760 return ExceptSpec;
7761}
7762
Richard Smithafb49182012-11-29 01:34:07 +00007763namespace {
7764/// RAII object to register a special member as being currently declared.
7765struct DeclaringSpecialMember {
7766 Sema &S;
7767 Sema::SpecialMemberDecl D;
7768 bool WasAlreadyBeingDeclared;
7769
7770 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7771 : S(S), D(RD, CSM) {
7772 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7773 if (WasAlreadyBeingDeclared)
7774 // This almost never happens, but if it does, ensure that our cache
7775 // doesn't contain a stale result.
7776 S.SpecialMemberCache.clear();
7777
7778 // FIXME: Register a note to be produced if we encounter an error while
7779 // declaring the special member.
7780 }
7781 ~DeclaringSpecialMember() {
7782 if (!WasAlreadyBeingDeclared)
7783 S.SpecialMembersBeingDeclared.erase(D);
7784 }
7785
7786 /// \brief Are we already trying to declare this special member?
7787 bool isAlreadyBeingDeclared() const {
7788 return WasAlreadyBeingDeclared;
7789 }
7790};
7791}
7792
Sean Hunt001cad92011-05-10 00:49:42 +00007793CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7794 CXXRecordDecl *ClassDecl) {
7795 // C++ [class.ctor]p5:
7796 // A default constructor for a class X is a constructor of class X
7797 // that can be called without an argument. If there is no
7798 // user-declared constructor for class X, a default constructor is
7799 // implicitly declared. An implicitly-declared default constructor
7800 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007801 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007802 "Should not build implicit default constructor!");
7803
Richard Smithafb49182012-11-29 01:34:07 +00007804 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7805 if (DSM.isAlreadyBeingDeclared())
7806 return 0;
7807
Richard Smith7756afa2012-06-10 05:43:50 +00007808 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7809 CXXDefaultConstructor,
7810 false);
7811
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007812 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007813 CanQualType ClassType
7814 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007815 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007816 DeclarationName Name
7817 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007818 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007819 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007820 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007821 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007822 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007823 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007824 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007825 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007826
7827 // Build an exception specification pointing back at this constructor.
7828 FunctionProtoType::ExtProtoInfo EPI;
7829 EPI.ExceptionSpecType = EST_Unevaluated;
7830 EPI.ExceptionSpecDecl = DefaultCon;
Dmitri Gribenko55431692013-05-05 00:41:58 +00007831 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007832
Richard Smithbc2a35d2012-12-08 08:32:28 +00007833 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7834 // constructors is easy to compute.
7835 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7836
7837 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007838 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007839
Douglas Gregor18274032010-07-03 00:47:00 +00007840 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007841 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007842
Douglas Gregor23c94db2010-07-02 17:43:08 +00007843 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007844 PushOnScopeChains(DefaultCon, S, false);
7845 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007846
Douglas Gregor32df23e2010-07-01 22:02:46 +00007847 return DefaultCon;
7848}
7849
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007850void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7851 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007852 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007853 !Constructor->doesThisDeclarationHaveABody() &&
7854 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007855 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007856
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007857 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007858 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007859
Eli Friedman9a14db32012-10-18 20:14:08 +00007860 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007861 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007862 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007863 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007864 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007865 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007866 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007867 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007868 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007869
7870 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007871 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007872
7873 Constructor->setUsed();
7874 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007875
7876 if (ASTMutationListener *L = getASTMutationListener()) {
7877 L->CompletedImplicitDefinition(Constructor);
7878 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007879}
7880
Richard Smith7a614d82011-06-11 17:19:42 +00007881void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007882 // Check that any explicitly-defaulted methods have exception specifications
7883 // compatible with their implicit exception specifications.
7884 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007885}
7886
Richard Smith4841ca52013-04-10 05:48:59 +00007887namespace {
7888/// Information on inheriting constructors to declare.
7889class InheritingConstructorInfo {
7890public:
7891 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7892 : SemaRef(SemaRef), Derived(Derived) {
7893 // Mark the constructors that we already have in the derived class.
7894 //
7895 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7896 // unless there is a user-declared constructor with the same signature in
7897 // the class where the using-declaration appears.
7898 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7899 }
7900
7901 void inheritAll(CXXRecordDecl *RD) {
7902 visitAll(RD, &InheritingConstructorInfo::inherit);
7903 }
7904
7905private:
7906 /// Information about an inheriting constructor.
7907 struct InheritingConstructor {
7908 InheritingConstructor()
7909 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7910
7911 /// If \c true, a constructor with this signature is already declared
7912 /// in the derived class.
7913 bool DeclaredInDerived;
7914
7915 /// The constructor which is inherited.
7916 const CXXConstructorDecl *BaseCtor;
7917
7918 /// The derived constructor we declared.
7919 CXXConstructorDecl *DerivedCtor;
7920 };
7921
7922 /// Inheriting constructors with a given canonical type. There can be at
7923 /// most one such non-template constructor, and any number of templated
7924 /// constructors.
7925 struct InheritingConstructorsForType {
7926 InheritingConstructor NonTemplate;
7927 llvm::SmallVector<
7928 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7929
7930 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7931 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7932 TemplateParameterList *ParamList = FTD->getTemplateParameters();
7933 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7934 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7935 false, S.TPL_TemplateMatch))
7936 return Templates[I].second;
7937 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7938 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007939 }
Richard Smith4841ca52013-04-10 05:48:59 +00007940
7941 return NonTemplate;
7942 }
7943 };
7944
7945 /// Get or create the inheriting constructor record for a constructor.
7946 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7947 QualType CtorType) {
7948 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7949 .getEntry(SemaRef, Ctor);
7950 }
7951
7952 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7953
7954 /// Process all constructors for a class.
7955 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7956 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7957 CtorE = RD->ctor_end();
7958 CtorIt != CtorE; ++CtorIt)
7959 (this->*Callback)(*CtorIt);
7960 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7961 I(RD->decls_begin()), E(RD->decls_end());
7962 I != E; ++I) {
7963 const FunctionDecl *FD = (*I)->getTemplatedDecl();
7964 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7965 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007966 }
7967 }
Richard Smith4841ca52013-04-10 05:48:59 +00007968
7969 /// Note that a constructor (or constructor template) was declared in Derived.
7970 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7971 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7972 }
7973
7974 /// Inherit a single constructor.
7975 void inherit(const CXXConstructorDecl *Ctor) {
7976 const FunctionProtoType *CtorType =
7977 Ctor->getType()->castAs<FunctionProtoType>();
7978 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7979 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7980
7981 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7982
7983 // Core issue (no number yet): the ellipsis is always discarded.
7984 if (EPI.Variadic) {
7985 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7986 SemaRef.Diag(Ctor->getLocation(),
7987 diag::note_using_decl_constructor_ellipsis);
7988 EPI.Variadic = false;
7989 }
7990
7991 // Declare a constructor for each number of parameters.
7992 //
7993 // C++11 [class.inhctor]p1:
7994 // The candidate set of inherited constructors from the class X named in
7995 // the using-declaration consists of [... modulo defects ...] for each
7996 // constructor or constructor template of X, the set of constructors or
7997 // constructor templates that results from omitting any ellipsis parameter
7998 // specification and successively omitting parameters with a default
7999 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008000 unsigned MinParams = minParamsToInherit(Ctor);
8001 unsigned Params = Ctor->getNumParams();
8002 if (Params >= MinParams) {
8003 do
8004 declareCtor(UsingLoc, Ctor,
8005 SemaRef.Context.getFunctionType(
8006 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8007 while (Params > MinParams &&
8008 Ctor->getParamDecl(--Params)->hasDefaultArg());
8009 }
Richard Smith4841ca52013-04-10 05:48:59 +00008010 }
8011
8012 /// Find the using-declaration which specified that we should inherit the
8013 /// constructors of \p Base.
8014 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8015 // No fancy lookup required; just look for the base constructor name
8016 // directly within the derived class.
8017 ASTContext &Context = SemaRef.Context;
8018 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8019 Context.getCanonicalType(Context.getRecordType(Base)));
8020 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8021 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8022 }
8023
8024 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8025 // C++11 [class.inhctor]p3:
8026 // [F]or each constructor template in the candidate set of inherited
8027 // constructors, a constructor template is implicitly declared
8028 if (Ctor->getDescribedFunctionTemplate())
8029 return 0;
8030
8031 // For each non-template constructor in the candidate set of inherited
8032 // constructors other than a constructor having no parameters or a
8033 // copy/move constructor having a single parameter, a constructor is
8034 // implicitly declared [...]
8035 if (Ctor->getNumParams() == 0)
8036 return 1;
8037 if (Ctor->isCopyOrMoveConstructor())
8038 return 2;
8039
8040 // Per discussion on core reflector, never inherit a constructor which
8041 // would become a default, copy, or move constructor of Derived either.
8042 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8043 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8044 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8045 }
8046
8047 /// Declare a single inheriting constructor, inheriting the specified
8048 /// constructor, with the given type.
8049 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8050 QualType DerivedType) {
8051 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8052
8053 // C++11 [class.inhctor]p3:
8054 // ... a constructor is implicitly declared with the same constructor
8055 // characteristics unless there is a user-declared constructor with
8056 // the same signature in the class where the using-declaration appears
8057 if (Entry.DeclaredInDerived)
8058 return;
8059
8060 // C++11 [class.inhctor]p7:
8061 // If two using-declarations declare inheriting constructors with the
8062 // same signature, the program is ill-formed
8063 if (Entry.DerivedCtor) {
8064 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8065 // Only diagnose this once per constructor.
8066 if (Entry.DerivedCtor->isInvalidDecl())
8067 return;
8068 Entry.DerivedCtor->setInvalidDecl();
8069
8070 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8071 SemaRef.Diag(BaseCtor->getLocation(),
8072 diag::note_using_decl_constructor_conflict_current_ctor);
8073 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8074 diag::note_using_decl_constructor_conflict_previous_ctor);
8075 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8076 diag::note_using_decl_constructor_conflict_previous_using);
8077 } else {
8078 // Core issue (no number): if the same inheriting constructor is
8079 // produced by multiple base class constructors from the same base
8080 // class, the inheriting constructor is defined as deleted.
8081 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8082 }
8083
8084 return;
8085 }
8086
8087 ASTContext &Context = SemaRef.Context;
8088 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8089 Context.getCanonicalType(Context.getRecordType(Derived)));
8090 DeclarationNameInfo NameInfo(Name, UsingLoc);
8091
8092 TemplateParameterList *TemplateParams = 0;
8093 if (const FunctionTemplateDecl *FTD =
8094 BaseCtor->getDescribedFunctionTemplate()) {
8095 TemplateParams = FTD->getTemplateParameters();
8096 // We're reusing template parameters from a different DeclContext. This
8097 // is questionable at best, but works out because the template depth in
8098 // both places is guaranteed to be 0.
8099 // FIXME: Rebuild the template parameters in the new context, and
8100 // transform the function type to refer to them.
8101 }
8102
8103 // Build type source info pointing at the using-declaration. This is
8104 // required by template instantiation.
8105 TypeSourceInfo *TInfo =
8106 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8107 FunctionProtoTypeLoc ProtoLoc =
8108 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8109
8110 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8111 Context, Derived, UsingLoc, NameInfo, DerivedType,
8112 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8113 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8114
8115 // Build an unevaluated exception specification for this constructor.
8116 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8117 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8118 EPI.ExceptionSpecType = EST_Unevaluated;
8119 EPI.ExceptionSpecDecl = DerivedCtor;
8120 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8121 FPT->getArgTypes(), EPI));
8122
8123 // Build the parameter declarations.
8124 SmallVector<ParmVarDecl *, 16> ParamDecls;
8125 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8126 TypeSourceInfo *TInfo =
8127 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8128 ParmVarDecl *PD = ParmVarDecl::Create(
8129 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8130 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8131 PD->setScopeInfo(0, I);
8132 PD->setImplicit();
8133 ParamDecls.push_back(PD);
8134 ProtoLoc.setArg(I, PD);
8135 }
8136
8137 // Set up the new constructor.
8138 DerivedCtor->setAccess(BaseCtor->getAccess());
8139 DerivedCtor->setParams(ParamDecls);
8140 DerivedCtor->setInheritedConstructor(BaseCtor);
8141 if (BaseCtor->isDeleted())
8142 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8143
8144 // If this is a constructor template, build the template declaration.
8145 if (TemplateParams) {
8146 FunctionTemplateDecl *DerivedTemplate =
8147 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8148 TemplateParams, DerivedCtor);
8149 DerivedTemplate->setAccess(BaseCtor->getAccess());
8150 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8151 Derived->addDecl(DerivedTemplate);
8152 } else {
8153 Derived->addDecl(DerivedCtor);
8154 }
8155
8156 Entry.BaseCtor = BaseCtor;
8157 Entry.DerivedCtor = DerivedCtor;
8158 }
8159
8160 Sema &SemaRef;
8161 CXXRecordDecl *Derived;
8162 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8163 MapType Map;
8164};
8165}
8166
8167void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8168 // Defer declaring the inheriting constructors until the class is
8169 // instantiated.
8170 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008171 return;
8172
Richard Smith4841ca52013-04-10 05:48:59 +00008173 // Find base classes from which we might inherit constructors.
8174 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8175 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8176 BaseE = ClassDecl->bases_end();
8177 BaseIt != BaseE; ++BaseIt)
8178 if (BaseIt->getInheritConstructors())
8179 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008180
Richard Smith4841ca52013-04-10 05:48:59 +00008181 // Go no further if we're not inheriting any constructors.
8182 if (InheritedBases.empty())
8183 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008184
Richard Smith4841ca52013-04-10 05:48:59 +00008185 // Declare the inherited constructors.
8186 InheritingConstructorInfo ICI(*this, ClassDecl);
8187 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8188 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008189}
8190
Richard Smith07b0fdc2013-03-18 21:12:30 +00008191void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8192 CXXConstructorDecl *Constructor) {
8193 CXXRecordDecl *ClassDecl = Constructor->getParent();
8194 assert(Constructor->getInheritedConstructor() &&
8195 !Constructor->doesThisDeclarationHaveABody() &&
8196 !Constructor->isDeleted());
8197
8198 SynthesizedFunctionScope Scope(*this, Constructor);
8199 DiagnosticErrorTrap Trap(Diags);
8200 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8201 Trap.hasErrorOccurred()) {
8202 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8203 << Context.getTagDeclType(ClassDecl);
8204 Constructor->setInvalidDecl();
8205 return;
8206 }
8207
8208 SourceLocation Loc = Constructor->getLocation();
8209 Constructor->setBody(new (Context) CompoundStmt(Loc));
8210
8211 Constructor->setUsed();
8212 MarkVTableUsed(CurrentLocation, ClassDecl);
8213
8214 if (ASTMutationListener *L = getASTMutationListener()) {
8215 L->CompletedImplicitDefinition(Constructor);
8216 }
8217}
8218
8219
Sean Huntcb45a0f2011-05-12 22:46:25 +00008220Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008221Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8222 CXXRecordDecl *ClassDecl = MD->getParent();
8223
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008224 // C++ [except.spec]p14:
8225 // An implicitly declared special member function (Clause 12) shall have
8226 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008227 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008228 if (ClassDecl->isInvalidDecl())
8229 return ExceptSpec;
8230
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008231 // Direct base-class destructors.
8232 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8233 BEnd = ClassDecl->bases_end();
8234 B != BEnd; ++B) {
8235 if (B->isVirtual()) // Handled below.
8236 continue;
8237
8238 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008239 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008240 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008241 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008242
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008243 // Virtual base-class destructors.
8244 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8245 BEnd = ClassDecl->vbases_end();
8246 B != BEnd; ++B) {
8247 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008248 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008249 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008250 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008251
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008252 // Field destructors.
8253 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8254 FEnd = ClassDecl->field_end();
8255 F != FEnd; ++F) {
8256 if (const RecordType *RecordTy
8257 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008258 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008259 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008260 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008261
Sean Huntcb45a0f2011-05-12 22:46:25 +00008262 return ExceptSpec;
8263}
8264
8265CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8266 // C++ [class.dtor]p2:
8267 // If a class has no user-declared destructor, a destructor is
8268 // declared implicitly. An implicitly-declared destructor is an
8269 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008270 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008271
Richard Smithafb49182012-11-29 01:34:07 +00008272 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8273 if (DSM.isAlreadyBeingDeclared())
8274 return 0;
8275
Douglas Gregor4923aa22010-07-02 20:37:36 +00008276 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008277 CanQualType ClassType
8278 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008279 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008280 DeclarationName Name
8281 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008282 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008283 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008284 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8285 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008286 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008287 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008288 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008289 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008290
8291 // Build an exception specification pointing back at this destructor.
8292 FunctionProtoType::ExtProtoInfo EPI;
8293 EPI.ExceptionSpecType = EST_Unevaluated;
8294 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008295 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008296
Richard Smithbc2a35d2012-12-08 08:32:28 +00008297 AddOverriddenMethods(ClassDecl, Destructor);
8298
8299 // We don't need to use SpecialMemberIsTrivial here; triviality for
8300 // destructors is easy to compute.
8301 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8302
8303 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008304 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008305
Douglas Gregor4923aa22010-07-02 20:37:36 +00008306 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008307 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008308
Douglas Gregor4923aa22010-07-02 20:37:36 +00008309 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008310 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008311 PushOnScopeChains(Destructor, S, false);
8312 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008313
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008314 return Destructor;
8315}
8316
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008317void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008318 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008319 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008320 !Destructor->doesThisDeclarationHaveABody() &&
8321 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008322 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008323 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008324 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008325
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008326 if (Destructor->isInvalidDecl())
8327 return;
8328
Eli Friedman9a14db32012-10-18 20:14:08 +00008329 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008330
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008331 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008332 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8333 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008334
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008335 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008336 Diag(CurrentLocation, diag::note_member_synthesized_at)
8337 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8338
8339 Destructor->setInvalidDecl();
8340 return;
8341 }
8342
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008343 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008344 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008345 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008346 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008347 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008348
8349 if (ASTMutationListener *L = getASTMutationListener()) {
8350 L->CompletedImplicitDefinition(Destructor);
8351 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008352}
8353
Richard Smitha4156b82012-04-21 18:42:51 +00008354/// \brief Perform any semantic analysis which needs to be delayed until all
8355/// pending class member declarations have been parsed.
8356void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008357 // If the context is an invalid C++ class, just suppress these checks.
8358 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8359 if (Record->isInvalidDecl()) {
8360 DelayedDestructorExceptionSpecChecks.clear();
8361 return;
8362 }
8363 }
8364
Richard Smitha4156b82012-04-21 18:42:51 +00008365 // Perform any deferred checking of exception specifications for virtual
8366 // destructors.
8367 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8368 i != e; ++i) {
8369 const CXXDestructorDecl *Dtor =
8370 DelayedDestructorExceptionSpecChecks[i].first;
8371 assert(!Dtor->getParent()->isDependentType() &&
8372 "Should not ever add destructors of templates into the list.");
8373 CheckOverridingFunctionExceptionSpec(Dtor,
8374 DelayedDestructorExceptionSpecChecks[i].second);
8375 }
8376 DelayedDestructorExceptionSpecChecks.clear();
8377}
8378
Richard Smithb9d0b762012-07-27 04:22:15 +00008379void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8380 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008381 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008382 "adjusting dtor exception specs was introduced in c++11");
8383
Sebastian Redl0ee33912011-05-19 05:13:44 +00008384 // C++11 [class.dtor]p3:
8385 // A declaration of a destructor that does not have an exception-
8386 // specification is implicitly considered to have the same exception-
8387 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008388 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008389 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008390 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008391 return;
8392
Chandler Carruth3f224b22011-09-20 04:55:26 +00008393 // Replace the destructor's type, building off the existing one. Fortunately,
8394 // the only thing of interest in the destructor type is its extended info.
8395 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008396 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8397 EPI.ExceptionSpecType = EST_Unevaluated;
8398 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008399 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008400
Sebastian Redl0ee33912011-05-19 05:13:44 +00008401 // FIXME: If the destructor has a body that could throw, and the newly created
8402 // spec doesn't allow exceptions, we should emit a warning, because this
8403 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008404 // However, we don't have a body or an exception specification yet, so it
8405 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008406}
8407
Richard Smith8c889532012-11-14 00:50:40 +00008408/// When generating a defaulted copy or move assignment operator, if a field
8409/// should be copied with __builtin_memcpy rather than via explicit assignments,
8410/// do so. This optimization only applies for arrays of scalars, and for arrays
8411/// of class type where the selected copy/move-assignment operator is trivial.
8412static StmtResult
8413buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8414 Expr *To, Expr *From) {
8415 // Compute the size of the memory buffer to be copied.
8416 QualType SizeType = S.Context.getSizeType();
8417 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8418 S.Context.getTypeSizeInChars(T).getQuantity());
8419
8420 // Take the address of the field references for "from" and "to". We
8421 // directly construct UnaryOperators here because semantic analysis
8422 // does not permit us to take the address of an xvalue.
8423 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8424 S.Context.getPointerType(From->getType()),
8425 VK_RValue, OK_Ordinary, Loc);
8426 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8427 S.Context.getPointerType(To->getType()),
8428 VK_RValue, OK_Ordinary, Loc);
8429
8430 const Type *E = T->getBaseElementTypeUnsafe();
8431 bool NeedsCollectableMemCpy =
8432 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8433
8434 // Create a reference to the __builtin_objc_memmove_collectable function
8435 StringRef MemCpyName = NeedsCollectableMemCpy ?
8436 "__builtin_objc_memmove_collectable" :
8437 "__builtin_memcpy";
8438 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8439 Sema::LookupOrdinaryName);
8440 S.LookupName(R, S.TUScope, true);
8441
8442 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8443 if (!MemCpy)
8444 // Something went horribly wrong earlier, and we will have complained
8445 // about it.
8446 return StmtError();
8447
8448 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8449 VK_RValue, Loc, 0);
8450 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8451
8452 Expr *CallArgs[] = {
8453 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8454 };
8455 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8456 Loc, CallArgs, Loc);
8457
8458 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8459 return S.Owned(Call.takeAs<Stmt>());
8460}
8461
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008462/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008463/// \c To.
8464///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008465/// This routine is used to copy/move the members of a class with an
8466/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008467/// copied are arrays, this routine builds for loops to copy them.
8468///
8469/// \param S The Sema object used for type-checking.
8470///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008471/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008472///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008473/// \param T The type of the expressions being copied/moved. Both expressions
8474/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008475///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008476/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008477///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008478/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008479///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008480/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008481/// Otherwise, it's a non-static member subobject.
8482///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008483/// \param Copying Whether we're copying or moving.
8484///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008485/// \param Depth Internal parameter recording the depth of the recursion.
8486///
Richard Smith8c889532012-11-14 00:50:40 +00008487/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8488/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008489static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008490buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8491 Expr *To, Expr *From,
8492 bool CopyingBaseSubobject, bool Copying,
8493 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008494 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008495 // Each subobject is assigned in the manner appropriate to its type:
8496 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008497 // - if the subobject is of class type, as if by a call to operator= with
8498 // the subobject as the object expression and the corresponding
8499 // subobject of x as a single function argument (as if by explicit
8500 // qualification; that is, ignoring any possible virtual overriding
8501 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008502 //
8503 // C++03 [class.copy]p13:
8504 // - if the subobject is of class type, the copy assignment operator for
8505 // the class is used (as if by explicit qualification; that is,
8506 // ignoring any possible virtual overriding functions in more derived
8507 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008508 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8509 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008510
Douglas Gregor06a9f362010-05-01 20:49:11 +00008511 // Look for operator=.
8512 DeclarationName Name
8513 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8514 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8515 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008516
Richard Smith044c8aa2012-11-13 00:54:12 +00008517 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8518 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008519 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008520 LookupResult::Filter F = OpLookup.makeFilter();
8521 while (F.hasNext()) {
8522 NamedDecl *D = F.next();
8523 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8524 if (Method->isCopyAssignmentOperator() ||
8525 (!Copying && Method->isMoveAssignmentOperator()))
8526 continue;
8527
8528 F.erase();
8529 }
8530 F.done();
John McCallb0207482010-03-16 06:11:48 +00008531 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008532
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008533 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008534 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008535 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008536 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008537 // ambiguities), we need to cast "this" to that subobject type; to
8538 // ensure that we don't go through the virtual call mechanism, we need
8539 // to qualify the operator= name with the base class (see below). However,
8540 // this means that if the base class has a protected copy assignment
8541 // operator, the protected member access check will fail. So, we
8542 // rewrite "protected" access to "public" access in this case, since we
8543 // know by construction that we're calling from a derived class.
8544 if (CopyingBaseSubobject) {
8545 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8546 L != LEnd; ++L) {
8547 if (L.getAccess() == AS_protected)
8548 L.setAccess(AS_public);
8549 }
8550 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008551
Douglas Gregor06a9f362010-05-01 20:49:11 +00008552 // Create the nested-name-specifier that will be used to qualify the
8553 // reference to operator=; this is required to suppress the virtual
8554 // call mechanism.
8555 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008556 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008557 SS.MakeTrivial(S.Context,
8558 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008559 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008560 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008561
Douglas Gregor06a9f362010-05-01 20:49:11 +00008562 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008563 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008564 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008565 /*TemplateKWLoc=*/SourceLocation(),
8566 /*FirstQualifierInScope=*/0,
8567 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008568 /*TemplateArgs=*/0,
8569 /*SuppressQualifierCheck=*/true);
8570 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008571 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008572
Douglas Gregor06a9f362010-05-01 20:49:11 +00008573 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008574
Richard Smith044c8aa2012-11-13 00:54:12 +00008575 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008576 OpEqualRef.takeAs<Expr>(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00008577 Loc, From, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008578 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008579 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008580
Richard Smith8c889532012-11-14 00:50:40 +00008581 // If we built a call to a trivial 'operator=' while copying an array,
8582 // bail out. We'll replace the whole shebang with a memcpy.
8583 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8584 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8585 return StmtResult((Stmt*)0);
8586
Richard Smith044c8aa2012-11-13 00:54:12 +00008587 // Convert to an expression-statement, and clean up any produced
8588 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008589 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008590 }
John McCallb0207482010-03-16 06:11:48 +00008591
Richard Smith044c8aa2012-11-13 00:54:12 +00008592 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008593 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008594 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008595 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008596 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008597 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008598 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008599 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008600 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008601
8602 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008603 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008604
Douglas Gregor06a9f362010-05-01 20:49:11 +00008605 // Construct a loop over the array bounds, e.g.,
8606 //
8607 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8608 //
8609 // that will copy each of the array elements.
8610 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008611
Douglas Gregor06a9f362010-05-01 20:49:11 +00008612 // Create the iteration variable.
8613 IdentifierInfo *IterationVarName = 0;
8614 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008615 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008616 llvm::raw_svector_ostream OS(Str);
8617 OS << "__i" << Depth;
8618 IterationVarName = &S.Context.Idents.get(OS.str());
8619 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008620 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008621 IterationVarName, SizeType,
8622 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008623 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008624
Douglas Gregor06a9f362010-05-01 20:49:11 +00008625 // Initialize the iteration variable to zero.
8626 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008627 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008628
8629 // Create a reference to the iteration variable; we'll use this several
8630 // times throughout.
8631 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008632 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008633 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008634 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8635 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8636
Douglas Gregor06a9f362010-05-01 20:49:11 +00008637 // Create the DeclStmt that holds the iteration variable.
8638 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008639
Douglas Gregor06a9f362010-05-01 20:49:11 +00008640 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008641 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008642 IterationVarRefRVal,
8643 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008644 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008645 IterationVarRefRVal,
8646 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008647 if (!Copying) // Cast to rvalue
8648 From = CastForMoving(S, From);
8649
8650 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008651 StmtResult Copy =
8652 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8653 To, From, CopyingBaseSubobject,
8654 Copying, Depth + 1);
8655 // Bail out if copying fails or if we determined that we should use memcpy.
8656 if (Copy.isInvalid() || !Copy.get())
8657 return Copy;
8658
8659 // Create the comparison against the array bound.
8660 llvm::APInt Upper
8661 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8662 Expr *Comparison
8663 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8664 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8665 BO_NE, S.Context.BoolTy,
8666 VK_RValue, OK_Ordinary, Loc, false);
8667
8668 // Create the pre-increment of the iteration variable.
8669 Expr *Increment
8670 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8671 VK_LValue, OK_Ordinary, Loc);
8672
Douglas Gregor06a9f362010-05-01 20:49:11 +00008673 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008674 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008675 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008676 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008677 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008678}
8679
Richard Smith8c889532012-11-14 00:50:40 +00008680static StmtResult
8681buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8682 Expr *To, Expr *From,
8683 bool CopyingBaseSubobject, bool Copying) {
8684 // Maybe we should use a memcpy?
8685 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8686 T.isTriviallyCopyableType(S.Context))
8687 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8688
8689 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8690 CopyingBaseSubobject,
8691 Copying, 0));
8692
8693 // If we ended up picking a trivial assignment operator for an array of a
8694 // non-trivially-copyable class type, just emit a memcpy.
8695 if (!Result.isInvalid() && !Result.get())
8696 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8697
8698 return Result;
8699}
8700
Richard Smithb9d0b762012-07-27 04:22:15 +00008701Sema::ImplicitExceptionSpecification
8702Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8703 CXXRecordDecl *ClassDecl = MD->getParent();
8704
8705 ImplicitExceptionSpecification ExceptSpec(*this);
8706 if (ClassDecl->isInvalidDecl())
8707 return ExceptSpec;
8708
8709 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8710 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8711 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8712
Douglas Gregorb87786f2010-07-01 17:48:08 +00008713 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008714 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008715 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008716
8717 // It is unspecified whether or not an implicit copy assignment operator
8718 // attempts to deduplicate calls to assignment operators of virtual bases are
8719 // made. As such, this exception specification is effectively unspecified.
8720 // Based on a similar decision made for constness in C++0x, we're erring on
8721 // the side of assuming such calls to be made regardless of whether they
8722 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008723 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8724 BaseEnd = ClassDecl->bases_end();
8725 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008726 if (Base->isVirtual())
8727 continue;
8728
Douglas Gregora376d102010-07-02 21:50:04 +00008729 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008730 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008731 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8732 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008733 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008734 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008735
8736 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8737 BaseEnd = ClassDecl->vbases_end();
8738 Base != BaseEnd; ++Base) {
8739 CXXRecordDecl *BaseClassDecl
8740 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8741 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8742 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008743 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008744 }
8745
Douglas Gregorb87786f2010-07-01 17:48:08 +00008746 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8747 FieldEnd = ClassDecl->field_end();
8748 Field != FieldEnd;
8749 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008750 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008751 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8752 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008753 LookupCopyingAssignment(FieldClassDecl,
8754 ArgQuals | FieldType.getCVRQualifiers(),
8755 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008756 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008757 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008758 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008759
Richard Smithb9d0b762012-07-27 04:22:15 +00008760 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008761}
8762
8763CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8764 // Note: The following rules are largely analoguous to the copy
8765 // constructor rules. Note that virtual bases are not taken into account
8766 // for determining the argument type of the operator. Note also that
8767 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008768 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008769
Richard Smithafb49182012-11-29 01:34:07 +00008770 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8771 if (DSM.isAlreadyBeingDeclared())
8772 return 0;
8773
Sean Hunt30de05c2011-05-14 05:23:20 +00008774 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8775 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00008776 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
8777 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00008778 ArgType = ArgType.withConst();
8779 ArgType = Context.getLValueReferenceType(ArgType);
8780
Richard Smitha8942d72013-05-07 03:19:20 +00008781 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8782 CXXCopyAssignment,
8783 Const);
8784
Douglas Gregord3c35902010-07-01 16:36:15 +00008785 // An implicitly-declared copy assignment operator is an inline public
8786 // member of its class.
8787 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008788 SourceLocation ClassLoc = ClassDecl->getLocation();
8789 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00008790 CXXMethodDecl *CopyAssignment =
8791 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8792 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
8793 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008794 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008795 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008796 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008797
8798 // Build an exception specification pointing back at this member.
8799 FunctionProtoType::ExtProtoInfo EPI;
8800 EPI.ExceptionSpecType = EST_Unevaluated;
8801 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008802 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008803
Douglas Gregord3c35902010-07-01 16:36:15 +00008804 // Add the parameter to the operator.
8805 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008806 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008807 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008808 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008809 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008810
Richard Smithbc2a35d2012-12-08 08:32:28 +00008811 AddOverriddenMethods(ClassDecl, CopyAssignment);
8812
8813 CopyAssignment->setTrivial(
8814 ClassDecl->needsOverloadResolutionForCopyAssignment()
8815 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8816 : ClassDecl->hasTrivialCopyAssignment());
8817
Richard Smitha8942d72013-05-07 03:19:20 +00008818 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00008819 // .... If the class definition does not explicitly declare a copy
8820 // assignment operator, there is no user-declared move constructor, and
8821 // there is no user-declared move assignment operator, a copy assignment
8822 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008823 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008824 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008825
Richard Smithbc2a35d2012-12-08 08:32:28 +00008826 // Note that we have added this copy-assignment operator.
8827 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8828
8829 if (Scope *S = getScopeForContext(ClassDecl))
8830 PushOnScopeChains(CopyAssignment, S, false);
8831 ClassDecl->addDecl(CopyAssignment);
8832
Douglas Gregord3c35902010-07-01 16:36:15 +00008833 return CopyAssignment;
8834}
8835
Richard Smith36155c12013-06-13 03:23:42 +00008836/// Diagnose an implicit copy operation for a class which is odr-used, but
8837/// which is deprecated because the class has a user-declared copy constructor,
8838/// copy assignment operator, or destructor.
8839static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
8840 SourceLocation UseLoc) {
8841 assert(CopyOp->isImplicit());
8842
8843 CXXRecordDecl *RD = CopyOp->getParent();
8844 CXXMethodDecl *UserDeclaredOperation = 0;
8845
8846 // In Microsoft mode, assignment operations don't affect constructors and
8847 // vice versa.
8848 if (RD->hasUserDeclaredDestructor()) {
8849 UserDeclaredOperation = RD->getDestructor();
8850 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
8851 RD->hasUserDeclaredCopyConstructor() &&
8852 !S.getLangOpts().MicrosoftMode) {
8853 // Find any user-declared copy constructor.
8854 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
8855 E = RD->ctor_end(); I != E; ++I) {
8856 if (I->isCopyConstructor()) {
8857 UserDeclaredOperation = *I;
8858 break;
8859 }
8860 }
8861 assert(UserDeclaredOperation);
8862 } else if (isa<CXXConstructorDecl>(CopyOp) &&
8863 RD->hasUserDeclaredCopyAssignment() &&
8864 !S.getLangOpts().MicrosoftMode) {
8865 // Find any user-declared move assignment operator.
8866 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
8867 E = RD->method_end(); I != E; ++I) {
8868 if (I->isCopyAssignmentOperator()) {
8869 UserDeclaredOperation = *I;
8870 break;
8871 }
8872 }
8873 assert(UserDeclaredOperation);
8874 }
8875
8876 if (UserDeclaredOperation) {
8877 S.Diag(UserDeclaredOperation->getLocation(),
8878 diag::warn_deprecated_copy_operation)
8879 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
8880 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
8881 S.Diag(UseLoc, diag::note_member_synthesized_at)
8882 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
8883 : Sema::CXXCopyAssignment)
8884 << RD;
8885 }
8886}
8887
Douglas Gregor06a9f362010-05-01 20:49:11 +00008888void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8889 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008890 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008891 CopyAssignOperator->isOverloadedOperator() &&
8892 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008893 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8894 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008895 "DefineImplicitCopyAssignment called for wrong function");
8896
8897 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8898
8899 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8900 CopyAssignOperator->setInvalidDecl();
8901 return;
8902 }
Richard Smith36155c12013-06-13 03:23:42 +00008903
8904 // C++11 [class.copy]p18:
8905 // The [definition of an implicitly declared copy assignment operator] is
8906 // deprecated if the class has a user-declared copy constructor or a
8907 // user-declared destructor.
8908 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
8909 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
8910
Douglas Gregor06a9f362010-05-01 20:49:11 +00008911 CopyAssignOperator->setUsed();
8912
Eli Friedman9a14db32012-10-18 20:14:08 +00008913 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008914 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008915
8916 // C++0x [class.copy]p30:
8917 // The implicitly-defined or explicitly-defaulted copy assignment operator
8918 // for a non-union class X performs memberwise copy assignment of its
8919 // subobjects. The direct base classes of X are assigned first, in the
8920 // order of their declaration in the base-specifier-list, and then the
8921 // immediate non-static data members of X are assigned, in the order in
8922 // which they were declared in the class definition.
8923
8924 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008925 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008926
8927 // The parameter for the "other" object, which we are copying from.
8928 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8929 Qualifiers OtherQuals = Other->getType().getQualifiers();
8930 QualType OtherRefType = Other->getType();
8931 if (const LValueReferenceType *OtherRef
8932 = OtherRefType->getAs<LValueReferenceType>()) {
8933 OtherRefType = OtherRef->getPointeeType();
8934 OtherQuals = OtherRefType.getQualifiers();
8935 }
8936
8937 // Our location for everything implicitly-generated.
8938 SourceLocation Loc = CopyAssignOperator->getLocation();
8939
8940 // Construct a reference to the "other" object. We'll be using this
8941 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008942 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008943 assert(OtherRef && "Reference to parameter cannot fail!");
8944
8945 // Construct the "this" pointer. We'll be using this throughout the generated
8946 // ASTs.
8947 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8948 assert(This && "Reference to this cannot fail!");
8949
8950 // Assign base classes.
8951 bool Invalid = false;
8952 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8953 E = ClassDecl->bases_end(); Base != E; ++Base) {
8954 // Form the assignment:
8955 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8956 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008957 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008958 Invalid = true;
8959 continue;
8960 }
8961
John McCallf871d0c2010-08-07 06:22:56 +00008962 CXXCastPath BasePath;
8963 BasePath.push_back(Base);
8964
Douglas Gregor06a9f362010-05-01 20:49:11 +00008965 // Construct the "from" expression, which is an implicit cast to the
8966 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008967 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008968 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8969 CK_UncheckedDerivedToBase,
8970 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008971
8972 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008973 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008974
8975 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008976 To = ImpCastExprToType(To.take(),
8977 Context.getCVRQualifiedType(BaseType,
8978 CopyAssignOperator->getTypeQualifiers()),
8979 CK_UncheckedDerivedToBase,
8980 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008981
8982 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008983 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008984 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008985 /*CopyingBaseSubobject=*/true,
8986 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008987 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008988 Diag(CurrentLocation, diag::note_member_synthesized_at)
8989 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8990 CopyAssignOperator->setInvalidDecl();
8991 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008992 }
8993
8994 // Success! Record the copy.
8995 Statements.push_back(Copy.takeAs<Expr>());
8996 }
8997
Douglas Gregor06a9f362010-05-01 20:49:11 +00008998 // Assign non-static members.
8999 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9000 FieldEnd = ClassDecl->field_end();
9001 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009002 if (Field->isUnnamedBitfield())
9003 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00009004
9005 if (Field->isInvalidDecl()) {
9006 Invalid = true;
9007 continue;
9008 }
9009
Douglas Gregor06a9f362010-05-01 20:49:11 +00009010 // Check for members of reference type; we can't copy those.
9011 if (Field->getType()->isReferenceType()) {
9012 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9013 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9014 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009015 Diag(CurrentLocation, diag::note_member_synthesized_at)
9016 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009017 Invalid = true;
9018 continue;
9019 }
9020
9021 // Check for members of const-qualified, non-class type.
9022 QualType BaseType = Context.getBaseElementType(Field->getType());
9023 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9024 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9025 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9026 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009027 Diag(CurrentLocation, diag::note_member_synthesized_at)
9028 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009029 Invalid = true;
9030 continue;
9031 }
John McCallb77115d2011-06-17 00:18:42 +00009032
9033 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009034 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9035 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009036
9037 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009038 if (FieldType->isIncompleteArrayType()) {
9039 assert(ClassDecl->hasFlexibleArrayMember() &&
9040 "Incomplete array type is not valid");
9041 continue;
9042 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009043
9044 // Build references to the field in the object we're copying from and to.
9045 CXXScopeSpec SS; // Intentionally empty
9046 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9047 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009048 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009049 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00009050 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00009051 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009052 SS, SourceLocation(), 0,
9053 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00009054 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00009055 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009056 SS, SourceLocation(), 0,
9057 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009058 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9059 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00009060
Douglas Gregor06a9f362010-05-01 20:49:11 +00009061 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009062 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009063 To.get(), From.get(),
9064 /*CopyingBaseSubobject=*/false,
9065 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009066 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009067 Diag(CurrentLocation, diag::note_member_synthesized_at)
9068 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9069 CopyAssignOperator->setInvalidDecl();
9070 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009071 }
9072
9073 // Success! Record the copy.
9074 Statements.push_back(Copy.takeAs<Stmt>());
9075 }
9076
9077 if (!Invalid) {
9078 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00009079 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009080
John McCall60d7b3a2010-08-24 06:29:42 +00009081 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009082 if (Return.isInvalid())
9083 Invalid = true;
9084 else {
9085 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009086
9087 if (Trap.hasErrorOccurred()) {
9088 Diag(CurrentLocation, diag::note_member_synthesized_at)
9089 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9090 Invalid = true;
9091 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009092 }
9093 }
9094
9095 if (Invalid) {
9096 CopyAssignOperator->setInvalidDecl();
9097 return;
9098 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009099
9100 StmtResult Body;
9101 {
9102 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009103 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009104 /*isStmtExpr=*/false);
9105 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9106 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009107 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009108
9109 if (ASTMutationListener *L = getASTMutationListener()) {
9110 L->CompletedImplicitDefinition(CopyAssignOperator);
9111 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009112}
9113
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009114Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009115Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9116 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009117
Richard Smithb9d0b762012-07-27 04:22:15 +00009118 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009119 if (ClassDecl->isInvalidDecl())
9120 return ExceptSpec;
9121
9122 // C++0x [except.spec]p14:
9123 // An implicitly declared special member function (Clause 12) shall have an
9124 // exception-specification. [...]
9125
9126 // It is unspecified whether or not an implicit move assignment operator
9127 // attempts to deduplicate calls to assignment operators of virtual bases are
9128 // made. As such, this exception specification is effectively unspecified.
9129 // Based on a similar decision made for constness in C++0x, we're erring on
9130 // the side of assuming such calls to be made regardless of whether they
9131 // actually happen.
9132 // Note that a move constructor is not implicitly declared when there are
9133 // virtual bases, but it can still be user-declared and explicitly defaulted.
9134 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9135 BaseEnd = ClassDecl->bases_end();
9136 Base != BaseEnd; ++Base) {
9137 if (Base->isVirtual())
9138 continue;
9139
9140 CXXRecordDecl *BaseClassDecl
9141 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9142 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009143 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009144 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009145 }
9146
9147 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9148 BaseEnd = ClassDecl->vbases_end();
9149 Base != BaseEnd; ++Base) {
9150 CXXRecordDecl *BaseClassDecl
9151 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9152 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009153 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009154 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009155 }
9156
9157 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9158 FieldEnd = ClassDecl->field_end();
9159 Field != FieldEnd;
9160 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009161 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009162 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009163 if (CXXMethodDecl *MoveAssign =
9164 LookupMovingAssignment(FieldClassDecl,
9165 FieldType.getCVRQualifiers(),
9166 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009167 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009168 }
9169 }
9170
9171 return ExceptSpec;
9172}
9173
Richard Smith1c931be2012-04-02 18:40:40 +00009174/// Determine whether the class type has any direct or indirect virtual base
9175/// classes which have a non-trivial move assignment operator.
9176static bool
9177hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9178 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9179 BaseEnd = ClassDecl->vbases_end();
9180 Base != BaseEnd; ++Base) {
9181 CXXRecordDecl *BaseClass =
9182 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9183
9184 // Try to declare the move assignment. If it would be deleted, then the
9185 // class does not have a non-trivial move assignment.
9186 if (BaseClass->needsImplicitMoveAssignment())
9187 S.DeclareImplicitMoveAssignment(BaseClass);
9188
Richard Smith426391c2012-11-16 00:53:38 +00009189 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009190 return true;
9191 }
9192
9193 return false;
9194}
9195
9196/// Determine whether the given type either has a move constructor or is
9197/// trivially copyable.
9198static bool
9199hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9200 Type = S.Context.getBaseElementType(Type);
9201
9202 // FIXME: Technically, non-trivially-copyable non-class types, such as
9203 // reference types, are supposed to return false here, but that appears
9204 // to be a standard defect.
9205 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009206 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009207 return true;
9208
9209 if (Type.isTriviallyCopyableType(S.Context))
9210 return true;
9211
9212 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009213 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9214 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009215 if (ClassDecl->needsImplicitMoveConstructor())
9216 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009217 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009218 }
9219
Richard Smithe5411b72012-12-01 02:35:44 +00009220 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9221 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009222 if (ClassDecl->needsImplicitMoveAssignment())
9223 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009224 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009225}
9226
9227/// Determine whether all non-static data members and direct or virtual bases
9228/// of class \p ClassDecl have either a move operation, or are trivially
9229/// copyable.
9230static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9231 bool IsConstructor) {
9232 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9233 BaseEnd = ClassDecl->bases_end();
9234 Base != BaseEnd; ++Base) {
9235 if (Base->isVirtual())
9236 continue;
9237
9238 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9239 return false;
9240 }
9241
9242 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9243 BaseEnd = ClassDecl->vbases_end();
9244 Base != BaseEnd; ++Base) {
9245 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9246 return false;
9247 }
9248
9249 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9250 FieldEnd = ClassDecl->field_end();
9251 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009252 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009253 return false;
9254 }
9255
9256 return true;
9257}
9258
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009259CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009260 // C++11 [class.copy]p20:
9261 // If the definition of a class X does not explicitly declare a move
9262 // assignment operator, one will be implicitly declared as defaulted
9263 // if and only if:
9264 //
9265 // - [first 4 bullets]
9266 assert(ClassDecl->needsImplicitMoveAssignment());
9267
Richard Smithafb49182012-11-29 01:34:07 +00009268 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9269 if (DSM.isAlreadyBeingDeclared())
9270 return 0;
9271
Richard Smith1c931be2012-04-02 18:40:40 +00009272 // [Checked after we build the declaration]
9273 // - the move assignment operator would not be implicitly defined as
9274 // deleted,
9275
9276 // [DR1402]:
9277 // - X has no direct or indirect virtual base class with a non-trivial
9278 // move assignment operator, and
9279 // - each of X's non-static data members and direct or virtual base classes
9280 // has a type that either has a move assignment operator or is trivially
9281 // copyable.
9282 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9283 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9284 ClassDecl->setFailedImplicitMoveAssignment();
9285 return 0;
9286 }
9287
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009288 // Note: The following rules are largely analoguous to the move
9289 // constructor rules.
9290
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009291 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9292 QualType RetType = Context.getLValueReferenceType(ArgType);
9293 ArgType = Context.getRValueReferenceType(ArgType);
9294
Richard Smitha8942d72013-05-07 03:19:20 +00009295 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9296 CXXMoveAssignment,
9297 false);
9298
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009299 // An implicitly-declared move assignment operator is an inline public
9300 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009301 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9302 SourceLocation ClassLoc = ClassDecl->getLocation();
9303 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009304 CXXMethodDecl *MoveAssignment =
9305 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9306 /*TInfo=*/0, /*StorageClass=*/SC_None,
9307 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009308 MoveAssignment->setAccess(AS_public);
9309 MoveAssignment->setDefaulted();
9310 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009311
Richard Smithb9d0b762012-07-27 04:22:15 +00009312 // Build an exception specification pointing back at this member.
9313 FunctionProtoType::ExtProtoInfo EPI;
9314 EPI.ExceptionSpecType = EST_Unevaluated;
9315 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009316 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009317
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009318 // Add the parameter to the operator.
9319 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9320 ClassLoc, ClassLoc, /*Id=*/0,
9321 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009322 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009323 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009324
Richard Smithbc2a35d2012-12-08 08:32:28 +00009325 AddOverriddenMethods(ClassDecl, MoveAssignment);
9326
9327 MoveAssignment->setTrivial(
9328 ClassDecl->needsOverloadResolutionForMoveAssignment()
9329 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9330 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009331
9332 // C++0x [class.copy]p9:
9333 // If the definition of a class X does not explicitly declare a move
9334 // assignment operator, one will be implicitly declared as defaulted if and
9335 // only if:
9336 // [...]
9337 // - the move assignment operator would not be implicitly defined as
9338 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009339 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009340 // Cache this result so that we don't try to generate this over and over
9341 // on every lookup, leaking memory and wasting time.
9342 ClassDecl->setFailedImplicitMoveAssignment();
9343 return 0;
9344 }
9345
Richard Smithbc2a35d2012-12-08 08:32:28 +00009346 // Note that we have added this copy-assignment operator.
9347 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9348
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009349 if (Scope *S = getScopeForContext(ClassDecl))
9350 PushOnScopeChains(MoveAssignment, S, false);
9351 ClassDecl->addDecl(MoveAssignment);
9352
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009353 return MoveAssignment;
9354}
9355
9356void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9357 CXXMethodDecl *MoveAssignOperator) {
9358 assert((MoveAssignOperator->isDefaulted() &&
9359 MoveAssignOperator->isOverloadedOperator() &&
9360 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009361 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9362 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009363 "DefineImplicitMoveAssignment called for wrong function");
9364
9365 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9366
9367 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9368 MoveAssignOperator->setInvalidDecl();
9369 return;
9370 }
9371
9372 MoveAssignOperator->setUsed();
9373
Eli Friedman9a14db32012-10-18 20:14:08 +00009374 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009375 DiagnosticErrorTrap Trap(Diags);
9376
9377 // C++0x [class.copy]p28:
9378 // The implicitly-defined or move assignment operator for a non-union class
9379 // X performs memberwise move assignment of its subobjects. The direct base
9380 // classes of X are assigned first, in the order of their declaration in the
9381 // base-specifier-list, and then the immediate non-static data members of X
9382 // are assigned, in the order in which they were declared in the class
9383 // definition.
9384
9385 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009386 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009387
9388 // The parameter for the "other" object, which we are move from.
9389 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9390 QualType OtherRefType = Other->getType()->
9391 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009392 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009393 "Bad argument type of defaulted move assignment");
9394
9395 // Our location for everything implicitly-generated.
9396 SourceLocation Loc = MoveAssignOperator->getLocation();
9397
9398 // Construct a reference to the "other" object. We'll be using this
9399 // throughout the generated ASTs.
9400 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9401 assert(OtherRef && "Reference to parameter cannot fail!");
9402 // Cast to rvalue.
9403 OtherRef = CastForMoving(*this, OtherRef);
9404
9405 // Construct the "this" pointer. We'll be using this throughout the generated
9406 // ASTs.
9407 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9408 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009409
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009410 // Assign base classes.
9411 bool Invalid = false;
9412 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9413 E = ClassDecl->bases_end(); Base != E; ++Base) {
9414 // Form the assignment:
9415 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9416 QualType BaseType = Base->getType().getUnqualifiedType();
9417 if (!BaseType->isRecordType()) {
9418 Invalid = true;
9419 continue;
9420 }
9421
9422 CXXCastPath BasePath;
9423 BasePath.push_back(Base);
9424
9425 // Construct the "from" expression, which is an implicit cast to the
9426 // appropriately-qualified base type.
9427 Expr *From = OtherRef;
9428 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009429 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009430
9431 // Dereference "this".
9432 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9433
9434 // Implicitly cast "this" to the appropriately-qualified base type.
9435 To = ImpCastExprToType(To.take(),
9436 Context.getCVRQualifiedType(BaseType,
9437 MoveAssignOperator->getTypeQualifiers()),
9438 CK_UncheckedDerivedToBase,
9439 VK_LValue, &BasePath);
9440
9441 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009442 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009443 To.get(), From,
9444 /*CopyingBaseSubobject=*/true,
9445 /*Copying=*/false);
9446 if (Move.isInvalid()) {
9447 Diag(CurrentLocation, diag::note_member_synthesized_at)
9448 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9449 MoveAssignOperator->setInvalidDecl();
9450 return;
9451 }
9452
9453 // Success! Record the move.
9454 Statements.push_back(Move.takeAs<Expr>());
9455 }
9456
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009457 // Assign non-static members.
9458 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9459 FieldEnd = ClassDecl->field_end();
9460 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009461 if (Field->isUnnamedBitfield())
9462 continue;
9463
Eli Friedman8150da32013-06-07 01:48:56 +00009464 if (Field->isInvalidDecl()) {
9465 Invalid = true;
9466 continue;
9467 }
9468
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009469 // Check for members of reference type; we can't move 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);
9474 Diag(CurrentLocation, diag::note_member_synthesized_at)
9475 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9476 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);
9486 Diag(CurrentLocation, diag::note_member_synthesized_at)
9487 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9488 Invalid = true;
9489 continue;
9490 }
9491
9492 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009493 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9494 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009495
9496 QualType FieldType = Field->getType().getNonReferenceType();
9497 if (FieldType->isIncompleteArrayType()) {
9498 assert(ClassDecl->hasFlexibleArrayMember() &&
9499 "Incomplete array type is not valid");
9500 continue;
9501 }
9502
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);
David Blaikie581deb32012-06-06 20:45:41 +00009507 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009508 MemberLookup.resolveKind();
9509 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9510 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009511 SS, SourceLocation(), 0,
9512 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009513 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9514 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009515 SS, SourceLocation(), 0,
9516 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009517 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9518 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9519
9520 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9521 "Member reference with rvalue base must be rvalue except for reference "
9522 "members, which aren't allowed for move assignment.");
9523
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009524 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009525 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009526 To.get(), From.get(),
9527 /*CopyingBaseSubobject=*/false,
9528 /*Copying=*/false);
9529 if (Move.isInvalid()) {
9530 Diag(CurrentLocation, diag::note_member_synthesized_at)
9531 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9532 MoveAssignOperator->setInvalidDecl();
9533 return;
9534 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009535
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009536 // Success! Record the copy.
9537 Statements.push_back(Move.takeAs<Stmt>());
9538 }
9539
9540 if (!Invalid) {
9541 // Add a "return *this;"
9542 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9543
9544 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9545 if (Return.isInvalid())
9546 Invalid = true;
9547 else {
9548 Statements.push_back(Return.takeAs<Stmt>());
9549
9550 if (Trap.hasErrorOccurred()) {
9551 Diag(CurrentLocation, diag::note_member_synthesized_at)
9552 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9553 Invalid = true;
9554 }
9555 }
9556 }
9557
9558 if (Invalid) {
9559 MoveAssignOperator->setInvalidDecl();
9560 return;
9561 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009562
9563 StmtResult Body;
9564 {
9565 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009566 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009567 /*isStmtExpr=*/false);
9568 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9569 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009570 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9571
9572 if (ASTMutationListener *L = getASTMutationListener()) {
9573 L->CompletedImplicitDefinition(MoveAssignOperator);
9574 }
9575}
9576
Richard Smithb9d0b762012-07-27 04:22:15 +00009577Sema::ImplicitExceptionSpecification
9578Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9579 CXXRecordDecl *ClassDecl = MD->getParent();
9580
9581 ImplicitExceptionSpecification ExceptSpec(*this);
9582 if (ClassDecl->isInvalidDecl())
9583 return ExceptSpec;
9584
9585 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9586 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9587 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9588
Douglas Gregor0d405db2010-07-01 20:59:04 +00009589 // C++ [except.spec]p14:
9590 // An implicitly declared special member function (Clause 12) shall have an
9591 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009592 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9593 BaseEnd = ClassDecl->bases_end();
9594 Base != BaseEnd;
9595 ++Base) {
9596 // Virtual bases are handled below.
9597 if (Base->isVirtual())
9598 continue;
9599
Douglas Gregor22584312010-07-02 23:41:54 +00009600 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009601 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009602 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009603 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009604 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009605 }
9606 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9607 BaseEnd = ClassDecl->vbases_end();
9608 Base != BaseEnd;
9609 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009610 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009611 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009612 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009613 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009614 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009615 }
9616 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9617 FieldEnd = ClassDecl->field_end();
9618 Field != FieldEnd;
9619 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009620 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009621 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9622 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009623 LookupCopyingConstructor(FieldClassDecl,
9624 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009625 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009626 }
9627 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009628
Richard Smithb9d0b762012-07-27 04:22:15 +00009629 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009630}
9631
9632CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9633 CXXRecordDecl *ClassDecl) {
9634 // C++ [class.copy]p4:
9635 // If the class definition does not explicitly declare a copy
9636 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009637 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009638
Richard Smithafb49182012-11-29 01:34:07 +00009639 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9640 if (DSM.isAlreadyBeingDeclared())
9641 return 0;
9642
Sean Hunt49634cf2011-05-13 06:10:58 +00009643 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9644 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009645 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009646 if (Const)
9647 ArgType = ArgType.withConst();
9648 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009649
Richard Smith7756afa2012-06-10 05:43:50 +00009650 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9651 CXXCopyConstructor,
9652 Const);
9653
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009654 DeclarationName Name
9655 = Context.DeclarationNames.getCXXConstructorName(
9656 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009657 SourceLocation ClassLoc = ClassDecl->getLocation();
9658 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009659
9660 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009661 // member of its class.
9662 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009663 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009664 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009665 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009666 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009667 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009668
Richard Smithb9d0b762012-07-27 04:22:15 +00009669 // Build an exception specification pointing back at this member.
9670 FunctionProtoType::ExtProtoInfo EPI;
9671 EPI.ExceptionSpecType = EST_Unevaluated;
9672 EPI.ExceptionSpecDecl = CopyConstructor;
9673 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009674 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009675
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009676 // Add the parameter to the constructor.
9677 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009678 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009679 /*IdentifierInfo=*/0,
9680 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009681 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009682 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009683
Richard Smithbc2a35d2012-12-08 08:32:28 +00009684 CopyConstructor->setTrivial(
9685 ClassDecl->needsOverloadResolutionForCopyConstructor()
9686 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9687 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009688
Nico Weberafcc96a2012-01-23 03:19:29 +00009689 // C++11 [class.copy]p8:
9690 // ... If the class definition does not explicitly declare a copy
9691 // constructor, there is no user-declared move constructor, and there is no
9692 // user-declared move assignment operator, a copy constructor is implicitly
9693 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009694 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009695 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009696
Richard Smithbc2a35d2012-12-08 08:32:28 +00009697 // Note that we have declared this constructor.
9698 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9699
9700 if (Scope *S = getScopeForContext(ClassDecl))
9701 PushOnScopeChains(CopyConstructor, S, false);
9702 ClassDecl->addDecl(CopyConstructor);
9703
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009704 return CopyConstructor;
9705}
9706
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009707void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009708 CXXConstructorDecl *CopyConstructor) {
9709 assert((CopyConstructor->isDefaulted() &&
9710 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009711 !CopyConstructor->doesThisDeclarationHaveABody() &&
9712 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009713 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009714
Anders Carlsson63010a72010-04-23 16:24:12 +00009715 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009716 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009717
Richard Smith36155c12013-06-13 03:23:42 +00009718 // C++11 [class.copy]p7:
9719 // The [definition of an implicitly declared copy constructro] is
9720 // deprecated if the class has a user-declared copy assignment operator
9721 // or a user-declared destructor.
9722 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
9723 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
9724
Eli Friedman9a14db32012-10-18 20:14:08 +00009725 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009726 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009727
David Blaikie93c86172013-01-17 05:26:25 +00009728 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009729 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009730 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009731 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009732 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009733 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009734 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009735 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9736 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009737 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009738 /*isStmtExpr=*/false)
9739 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009740 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009741 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009742
9743 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009744 if (ASTMutationListener *L = getASTMutationListener()) {
9745 L->CompletedImplicitDefinition(CopyConstructor);
9746 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009747}
9748
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009749Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009750Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9751 CXXRecordDecl *ClassDecl = MD->getParent();
9752
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009753 // C++ [except.spec]p14:
9754 // An implicitly declared special member function (Clause 12) shall have an
9755 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009756 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009757 if (ClassDecl->isInvalidDecl())
9758 return ExceptSpec;
9759
9760 // Direct base-class constructors.
9761 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9762 BEnd = ClassDecl->bases_end();
9763 B != BEnd; ++B) {
9764 if (B->isVirtual()) // Handled below.
9765 continue;
9766
9767 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9768 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009769 CXXConstructorDecl *Constructor =
9770 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009771 // If this is a deleted function, add it anyway. This might be conformant
9772 // with the standard. This might not. I'm not sure. It might not matter.
9773 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009774 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009775 }
9776 }
9777
9778 // Virtual base-class constructors.
9779 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9780 BEnd = ClassDecl->vbases_end();
9781 B != BEnd; ++B) {
9782 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9783 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009784 CXXConstructorDecl *Constructor =
9785 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009786 // If this is a deleted function, add it anyway. This might be conformant
9787 // with the standard. This might not. I'm not sure. It might not matter.
9788 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009789 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009790 }
9791 }
9792
9793 // Field constructors.
9794 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9795 FEnd = ClassDecl->field_end();
9796 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009797 QualType FieldType = Context.getBaseElementType(F->getType());
9798 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9799 CXXConstructorDecl *Constructor =
9800 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009801 // If this is a deleted function, add it anyway. This might be conformant
9802 // with the standard. This might not. I'm not sure. It might not matter.
9803 // In particular, the problem is that this function never gets called. It
9804 // might just be ill-formed because this function attempts to refer to
9805 // a deleted function here.
9806 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009807 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009808 }
9809 }
9810
9811 return ExceptSpec;
9812}
9813
9814CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9815 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009816 // C++11 [class.copy]p9:
9817 // If the definition of a class X does not explicitly declare a move
9818 // constructor, one will be implicitly declared as defaulted if and only if:
9819 //
9820 // - [first 4 bullets]
9821 assert(ClassDecl->needsImplicitMoveConstructor());
9822
Richard Smithafb49182012-11-29 01:34:07 +00009823 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9824 if (DSM.isAlreadyBeingDeclared())
9825 return 0;
9826
Richard Smith1c931be2012-04-02 18:40:40 +00009827 // [Checked after we build the declaration]
9828 // - the move assignment operator would not be implicitly defined as
9829 // deleted,
9830
9831 // [DR1402]:
9832 // - each of X's non-static data members and direct or virtual base classes
9833 // has a type that either has a move constructor or is trivially copyable.
9834 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9835 ClassDecl->setFailedImplicitMoveConstructor();
9836 return 0;
9837 }
9838
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009839 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9840 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009841
Richard Smith7756afa2012-06-10 05:43:50 +00009842 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9843 CXXMoveConstructor,
9844 false);
9845
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009846 DeclarationName Name
9847 = Context.DeclarationNames.getCXXConstructorName(
9848 Context.getCanonicalType(ClassType));
9849 SourceLocation ClassLoc = ClassDecl->getLocation();
9850 DeclarationNameInfo NameInfo(Name, ClassLoc);
9851
Richard Smitha8942d72013-05-07 03:19:20 +00009852 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009853 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009854 // member of its class.
9855 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009856 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009857 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009858 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009859 MoveConstructor->setAccess(AS_public);
9860 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009861
Richard Smithb9d0b762012-07-27 04:22:15 +00009862 // Build an exception specification pointing back at this member.
9863 FunctionProtoType::ExtProtoInfo EPI;
9864 EPI.ExceptionSpecType = EST_Unevaluated;
9865 EPI.ExceptionSpecDecl = MoveConstructor;
9866 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009867 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009868
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009869 // Add the parameter to the constructor.
9870 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9871 ClassLoc, ClassLoc,
9872 /*IdentifierInfo=*/0,
9873 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009874 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009875 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009876
Richard Smithbc2a35d2012-12-08 08:32:28 +00009877 MoveConstructor->setTrivial(
9878 ClassDecl->needsOverloadResolutionForMoveConstructor()
9879 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9880 : ClassDecl->hasTrivialMoveConstructor());
9881
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009882 // C++0x [class.copy]p9:
9883 // If the definition of a class X does not explicitly declare a move
9884 // constructor, one will be implicitly declared as defaulted if and only if:
9885 // [...]
9886 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009887 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009888 // Cache this result so that we don't try to generate this over and over
9889 // on every lookup, leaking memory and wasting time.
9890 ClassDecl->setFailedImplicitMoveConstructor();
9891 return 0;
9892 }
9893
9894 // Note that we have declared this constructor.
9895 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9896
9897 if (Scope *S = getScopeForContext(ClassDecl))
9898 PushOnScopeChains(MoveConstructor, S, false);
9899 ClassDecl->addDecl(MoveConstructor);
9900
9901 return MoveConstructor;
9902}
9903
9904void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9905 CXXConstructorDecl *MoveConstructor) {
9906 assert((MoveConstructor->isDefaulted() &&
9907 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009908 !MoveConstructor->doesThisDeclarationHaveABody() &&
9909 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009910 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9911
9912 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9913 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9914
Eli Friedman9a14db32012-10-18 20:14:08 +00009915 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009916 DiagnosticErrorTrap Trap(Diags);
9917
David Blaikie93c86172013-01-17 05:26:25 +00009918 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009919 Trap.hasErrorOccurred()) {
9920 Diag(CurrentLocation, diag::note_member_synthesized_at)
9921 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9922 MoveConstructor->setInvalidDecl();
9923 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009924 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009925 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9926 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009927 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009928 /*isStmtExpr=*/false)
9929 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009930 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009931 }
9932
9933 MoveConstructor->setUsed();
9934
9935 if (ASTMutationListener *L = getASTMutationListener()) {
9936 L->CompletedImplicitDefinition(MoveConstructor);
9937 }
9938}
9939
Douglas Gregore4e68d42012-02-15 19:33:52 +00009940bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9941 return FD->isDeleted() &&
9942 (FD->isDefaulted() || FD->isImplicit()) &&
9943 isa<CXXMethodDecl>(FD);
9944}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009945
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009946/// \brief Mark the call operator of the given lambda closure type as "used".
9947static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9948 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009949 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009950 Lambda->lookup(
9951 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009952 CallOperator->setReferenced();
9953 CallOperator->setUsed();
9954}
9955
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009956void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9957 SourceLocation CurrentLocation,
9958 CXXConversionDecl *Conv)
9959{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009960 CXXRecordDecl *Lambda = Conv->getParent();
9961
9962 // Make sure that the lambda call operator is marked used.
9963 markLambdaCallOperatorUsed(*this, Lambda);
9964
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009965 Conv->setUsed();
9966
Eli Friedman9a14db32012-10-18 20:14:08 +00009967 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009968 DiagnosticErrorTrap Trap(Diags);
9969
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009970 // Return the address of the __invoke function.
9971 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9972 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009973 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009974 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9975 VK_LValue, Conv->getLocation()).take();
9976 assert(FunctionRef && "Can't refer to __invoke function?");
9977 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009978 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009979 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009980 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009981
9982 // Fill in the __invoke function with a dummy implementation. IR generation
9983 // will fill in the actual details.
9984 Invoke->setUsed();
9985 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009986 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009987
9988 if (ASTMutationListener *L = getASTMutationListener()) {
9989 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009990 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009991 }
9992}
9993
9994void Sema::DefineImplicitLambdaToBlockPointerConversion(
9995 SourceLocation CurrentLocation,
9996 CXXConversionDecl *Conv)
9997{
9998 Conv->setUsed();
9999
Eli Friedman9a14db32012-10-18 20:14:08 +000010000 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010001 DiagnosticErrorTrap Trap(Diags);
10002
Douglas Gregorac1303e2012-02-22 05:02:47 +000010003 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010004 Expr *This = ActOnCXXThis(CurrentLocation).take();
10005 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010006
Eli Friedman23f02672012-03-01 04:01:32 +000010007 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10008 Conv->getLocation(),
10009 Conv, DerefThis);
10010
10011 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10012 // behavior. Note that only the general conversion function does this
10013 // (since it's unusable otherwise); in the case where we inline the
10014 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010015 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000010016 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10017 CK_CopyAndAutoreleaseBlockObject,
10018 BuildBlock.get(), 0, VK_RValue);
10019
10020 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010021 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000010022 Conv->setInvalidDecl();
10023 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010024 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010025
Douglas Gregorac1303e2012-02-22 05:02:47 +000010026 // Create the return statement that returns the block from the conversion
10027 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010028 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010029 if (Return.isInvalid()) {
10030 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10031 Conv->setInvalidDecl();
10032 return;
10033 }
10034
10035 // Set the body of the conversion function.
10036 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010037 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010038 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010039 Conv->getLocation()));
10040
Douglas Gregorac1303e2012-02-22 05:02:47 +000010041 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010042 if (ASTMutationListener *L = getASTMutationListener()) {
10043 L->CompletedImplicitDefinition(Conv);
10044 }
10045}
10046
Douglas Gregorf52757d2012-03-10 06:53:13 +000010047/// \brief Determine whether the given list arguments contains exactly one
10048/// "real" (non-default) argument.
10049static bool hasOneRealArgument(MultiExprArg Args) {
10050 switch (Args.size()) {
10051 case 0:
10052 return false;
10053
10054 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010055 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010056 return false;
10057
10058 // fall through
10059 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010060 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010061 }
10062
10063 return false;
10064}
10065
John McCall60d7b3a2010-08-24 06:29:42 +000010066ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010067Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010068 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010069 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010070 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010071 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010072 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010073 unsigned ConstructKind,
10074 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010075 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010076
Douglas Gregor2f599792010-04-02 18:24:57 +000010077 // C++0x [class.copy]p34:
10078 // When certain criteria are met, an implementation is allowed to
10079 // omit the copy/move construction of a class object, even if the
10080 // copy/move constructor and/or destructor for the object have
10081 // side effects. [...]
10082 // - when a temporary class object that has not been bound to a
10083 // reference (12.2) would be copied/moved to a class object
10084 // with the same cv-unqualified type, the copy/move operation
10085 // can be omitted by constructing the temporary object
10086 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010087 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010088 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010089 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010090 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010091 }
Mike Stump1eb44332009-09-09 15:08:12 +000010092
10093 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010094 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010095 IsListInitialization, RequiresZeroInit,
10096 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010097}
10098
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010099/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10100/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010101ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010102Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10103 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010104 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010105 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010106 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010107 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010108 unsigned ConstructKind,
10109 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010110 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010111 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010112 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010113 HadMultipleCandidates,
10114 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010115 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10116 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010117}
10118
John McCall68c6c9a2010-02-02 09:10:11 +000010119void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010120 if (VD->isInvalidDecl()) return;
10121
John McCall68c6c9a2010-02-02 09:10:11 +000010122 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010123 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010124 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010125 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010126
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010127 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010128 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010129 CheckDestructorAccess(VD->getLocation(), Destructor,
10130 PDiag(diag::err_access_dtor_var)
10131 << VD->getDeclName()
10132 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010133 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010134
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010135 if (!VD->hasGlobalStorage()) return;
10136
10137 // Emit warning for non-trivial dtor in global scope (a real global,
10138 // class-static, function-static).
10139 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10140
10141 // TODO: this should be re-enabled for static locals by !CXAAtExit
10142 if (!VD->isStaticLocal())
10143 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010144}
10145
Douglas Gregor39da0b82009-09-09 23:08:42 +000010146/// \brief Given a constructor and the set of arguments provided for the
10147/// constructor, convert the arguments and add any required default arguments
10148/// to form a proper call to this constructor.
10149///
10150/// \returns true if an error occurred, false otherwise.
10151bool
10152Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10153 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010154 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010155 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010156 bool AllowExplicit,
10157 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010158 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10159 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010160 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010161
10162 const FunctionProtoType *Proto
10163 = Constructor->getType()->getAs<FunctionProtoType>();
10164 assert(Proto && "Constructor without a prototype?");
10165 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010166
10167 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010168 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010169 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010170 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010171 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010172
10173 VariadicCallType CallType =
10174 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010175 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010176 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010177 Proto, 0,
10178 llvm::makeArrayRef(Args, NumArgs),
10179 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010180 CallType, AllowExplicit,
10181 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010182 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010183
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010184 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010185
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010186 CheckConstructorCall(Constructor,
10187 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10188 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010189 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010190
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010191 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010192}
10193
Anders Carlsson20d45d22009-12-12 00:32:00 +000010194static inline bool
10195CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10196 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010197 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010198 if (isa<NamespaceDecl>(DC)) {
10199 return SemaRef.Diag(FnDecl->getLocation(),
10200 diag::err_operator_new_delete_declared_in_namespace)
10201 << FnDecl->getDeclName();
10202 }
10203
10204 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010205 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010206 return SemaRef.Diag(FnDecl->getLocation(),
10207 diag::err_operator_new_delete_declared_static)
10208 << FnDecl->getDeclName();
10209 }
10210
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010211 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010212}
10213
Anders Carlsson156c78e2009-12-13 17:53:43 +000010214static inline bool
10215CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10216 CanQualType ExpectedResultType,
10217 CanQualType ExpectedFirstParamType,
10218 unsigned DependentParamTypeDiag,
10219 unsigned InvalidParamTypeDiag) {
10220 QualType ResultType =
10221 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10222
10223 // Check that the result type is not dependent.
10224 if (ResultType->isDependentType())
10225 return SemaRef.Diag(FnDecl->getLocation(),
10226 diag::err_operator_new_delete_dependent_result_type)
10227 << FnDecl->getDeclName() << ExpectedResultType;
10228
10229 // Check that the result type is what we expect.
10230 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10231 return SemaRef.Diag(FnDecl->getLocation(),
10232 diag::err_operator_new_delete_invalid_result_type)
10233 << FnDecl->getDeclName() << ExpectedResultType;
10234
10235 // A function template must have at least 2 parameters.
10236 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10237 return SemaRef.Diag(FnDecl->getLocation(),
10238 diag::err_operator_new_delete_template_too_few_parameters)
10239 << FnDecl->getDeclName();
10240
10241 // The function decl must have at least 1 parameter.
10242 if (FnDecl->getNumParams() == 0)
10243 return SemaRef.Diag(FnDecl->getLocation(),
10244 diag::err_operator_new_delete_too_few_parameters)
10245 << FnDecl->getDeclName();
10246
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010247 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010248 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10249 if (FirstParamType->isDependentType())
10250 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10251 << FnDecl->getDeclName() << ExpectedFirstParamType;
10252
10253 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010254 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010255 ExpectedFirstParamType)
10256 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10257 << FnDecl->getDeclName() << ExpectedFirstParamType;
10258
10259 return false;
10260}
10261
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010262static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010263CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010264 // C++ [basic.stc.dynamic.allocation]p1:
10265 // A program is ill-formed if an allocation function is declared in a
10266 // namespace scope other than global scope or declared static in global
10267 // scope.
10268 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10269 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010270
10271 CanQualType SizeTy =
10272 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10273
10274 // C++ [basic.stc.dynamic.allocation]p1:
10275 // The return type shall be void*. The first parameter shall have type
10276 // std::size_t.
10277 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10278 SizeTy,
10279 diag::err_operator_new_dependent_param_type,
10280 diag::err_operator_new_param_type))
10281 return true;
10282
10283 // C++ [basic.stc.dynamic.allocation]p1:
10284 // The first parameter shall not have an associated default argument.
10285 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010286 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010287 diag::err_operator_new_default_arg)
10288 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10289
10290 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010291}
10292
10293static bool
Richard Smith444d3842012-10-20 08:26:51 +000010294CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010295 // C++ [basic.stc.dynamic.deallocation]p1:
10296 // A program is ill-formed if deallocation functions are declared in a
10297 // namespace scope other than global scope or declared static in global
10298 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010299 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10300 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010301
10302 // C++ [basic.stc.dynamic.deallocation]p2:
10303 // Each deallocation function shall return void and its first parameter
10304 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010305 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10306 SemaRef.Context.VoidPtrTy,
10307 diag::err_operator_delete_dependent_param_type,
10308 diag::err_operator_delete_param_type))
10309 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010310
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010311 return false;
10312}
10313
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010314/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10315/// of this overloaded operator is well-formed. If so, returns false;
10316/// otherwise, emits appropriate diagnostics and returns true.
10317bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010318 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010319 "Expected an overloaded operator declaration");
10320
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010321 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10322
Mike Stump1eb44332009-09-09 15:08:12 +000010323 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010324 // The allocation and deallocation functions, operator new,
10325 // operator new[], operator delete and operator delete[], are
10326 // described completely in 3.7.3. The attributes and restrictions
10327 // found in the rest of this subclause do not apply to them unless
10328 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010329 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010330 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010331
Anders Carlssona3ccda52009-12-12 00:26:23 +000010332 if (Op == OO_New || Op == OO_Array_New)
10333 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010334
10335 // C++ [over.oper]p6:
10336 // An operator function shall either be a non-static member
10337 // function or be a non-member function and have at least one
10338 // parameter whose type is a class, a reference to a class, an
10339 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010340 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10341 if (MethodDecl->isStatic())
10342 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010343 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010344 } else {
10345 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010346 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10347 ParamEnd = FnDecl->param_end();
10348 Param != ParamEnd; ++Param) {
10349 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010350 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10351 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010352 ClassOrEnumParam = true;
10353 break;
10354 }
10355 }
10356
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010357 if (!ClassOrEnumParam)
10358 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010359 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010360 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010361 }
10362
10363 // C++ [over.oper]p8:
10364 // An operator function cannot have default arguments (8.3.6),
10365 // except where explicitly stated below.
10366 //
Mike Stump1eb44332009-09-09 15:08:12 +000010367 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010368 // (C++ [over.call]p1).
10369 if (Op != OO_Call) {
10370 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10371 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010372 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010373 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010374 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010375 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010376 }
10377 }
10378
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010379 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10380 { false, false, false }
10381#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10382 , { Unary, Binary, MemberOnly }
10383#include "clang/Basic/OperatorKinds.def"
10384 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010385
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010386 bool CanBeUnaryOperator = OperatorUses[Op][0];
10387 bool CanBeBinaryOperator = OperatorUses[Op][1];
10388 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010389
10390 // C++ [over.oper]p8:
10391 // [...] Operator functions cannot have more or fewer parameters
10392 // than the number required for the corresponding operator, as
10393 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010394 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010395 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010396 if (Op != OO_Call &&
10397 ((NumParams == 1 && !CanBeUnaryOperator) ||
10398 (NumParams == 2 && !CanBeBinaryOperator) ||
10399 (NumParams < 1) || (NumParams > 2))) {
10400 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010401 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010402 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010403 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010404 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010405 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010406 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010407 assert(CanBeBinaryOperator &&
10408 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010409 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010410 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010411
Chris Lattner416e46f2008-11-21 07:57:12 +000010412 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010413 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010414 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010415
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010416 // Overloaded operators other than operator() cannot be variadic.
10417 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010418 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010419 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010420 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010421 }
10422
10423 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010424 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10425 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010426 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010427 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010428 }
10429
10430 // C++ [over.inc]p1:
10431 // The user-defined function called operator++ implements the
10432 // prefix and postfix ++ operator. If this function is a member
10433 // function with no parameters, or a non-member function with one
10434 // parameter of class or enumeration type, it defines the prefix
10435 // increment operator ++ for objects of that type. If the function
10436 // is a member function with one parameter (which shall be of type
10437 // int) or a non-member function with two parameters (the second
10438 // of which shall be of type int), it defines the postfix
10439 // increment operator ++ for objects of that type.
10440 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10441 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10442 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010443 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010444 ParamIsInt = BT->getKind() == BuiltinType::Int;
10445
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010446 if (!ParamIsInt)
10447 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010448 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010449 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010450 }
10451
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010452 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010453}
Chris Lattner5a003a42008-12-17 07:09:26 +000010454
Sean Hunta6c058d2010-01-13 09:01:02 +000010455/// CheckLiteralOperatorDeclaration - Check whether the declaration
10456/// of this literal operator function is well-formed. If so, returns
10457/// false; otherwise, emits appropriate diagnostics and returns true.
10458bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010459 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010460 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10461 << FnDecl->getDeclName();
10462 return true;
10463 }
10464
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010465 if (FnDecl->isExternC()) {
10466 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10467 return true;
10468 }
10469
Sean Hunta6c058d2010-01-13 09:01:02 +000010470 bool Valid = false;
10471
Richard Smith36f5cfe2012-03-09 08:00:36 +000010472 // This might be the definition of a literal operator template.
10473 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10474 // This might be a specialization of a literal operator template.
10475 if (!TpDecl)
10476 TpDecl = FnDecl->getPrimaryTemplate();
10477
Sean Hunt216c2782010-04-07 23:11:06 +000010478 // template <char...> type operator "" name() is the only valid template
10479 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010480 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010481 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010482 // Must have only one template parameter
10483 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10484 if (Params->size() == 1) {
10485 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010486 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010487
Sean Hunt216c2782010-04-07 23:11:06 +000010488 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010489 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10490 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10491 Valid = true;
10492 }
10493 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010494 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010495 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010496 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10497
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010498 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010499
Sean Hunt30019c02010-04-07 22:57:35 +000010500 // unsigned long long int, long double, and any character type are allowed
10501 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010502 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10503 Context.hasSameType(T, Context.LongDoubleTy) ||
10504 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010505 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010506 Context.hasSameType(T, Context.Char16Ty) ||
10507 Context.hasSameType(T, Context.Char32Ty)) {
10508 if (++Param == FnDecl->param_end())
10509 Valid = true;
10510 goto FinishedParams;
10511 }
10512
Sean Hunt30019c02010-04-07 22:57:35 +000010513 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010514 const PointerType *PT = T->getAs<PointerType>();
10515 if (!PT)
10516 goto FinishedParams;
10517 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010518 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010519 goto FinishedParams;
10520 T = T.getUnqualifiedType();
10521
10522 // Move on to the second parameter;
10523 ++Param;
10524
10525 // If there is no second parameter, the first must be a const char *
10526 if (Param == FnDecl->param_end()) {
10527 if (Context.hasSameType(T, Context.CharTy))
10528 Valid = true;
10529 goto FinishedParams;
10530 }
10531
10532 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10533 // are allowed as the first parameter to a two-parameter function
10534 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010535 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010536 Context.hasSameType(T, Context.Char16Ty) ||
10537 Context.hasSameType(T, Context.Char32Ty)))
10538 goto FinishedParams;
10539
10540 // The second and final parameter must be an std::size_t
10541 T = (*Param)->getType().getUnqualifiedType();
10542 if (Context.hasSameType(T, Context.getSizeType()) &&
10543 ++Param == FnDecl->param_end())
10544 Valid = true;
10545 }
10546
10547 // FIXME: This diagnostic is absolutely terrible.
10548FinishedParams:
10549 if (!Valid) {
10550 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10551 << FnDecl->getDeclName();
10552 return true;
10553 }
10554
Richard Smitha9e88b22012-03-09 08:16:22 +000010555 // A parameter-declaration-clause containing a default argument is not
10556 // equivalent to any of the permitted forms.
10557 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10558 ParamEnd = FnDecl->param_end();
10559 Param != ParamEnd; ++Param) {
10560 if ((*Param)->hasDefaultArg()) {
10561 Diag((*Param)->getDefaultArgRange().getBegin(),
10562 diag::err_literal_operator_default_argument)
10563 << (*Param)->getDefaultArgRange();
10564 break;
10565 }
10566 }
10567
Richard Smith2fb4ae32012-03-08 02:39:21 +000010568 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010569 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10570 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010571 // C++11 [usrlit.suffix]p1:
10572 // Literal suffix identifiers that do not start with an underscore
10573 // are reserved for future standardization.
10574 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010575 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010576
Sean Hunta6c058d2010-01-13 09:01:02 +000010577 return false;
10578}
10579
Douglas Gregor074149e2009-01-05 19:45:36 +000010580/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10581/// linkage specification, including the language and (if present)
10582/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10583/// the location of the language string literal, which is provided
10584/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10585/// the '{' brace. Otherwise, this linkage specification does not
10586/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010587Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10588 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010589 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010590 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010591 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010592 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010593 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010594 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010595 Language = LinkageSpecDecl::lang_cxx;
10596 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010597 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010598 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010599 }
Mike Stump1eb44332009-09-09 15:08:12 +000010600
Chris Lattnercc98eac2008-12-17 07:13:27 +000010601 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010602
Douglas Gregor074149e2009-01-05 19:45:36 +000010603 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010604 ExternLoc, LangLoc, Language,
10605 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010606 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010607 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010608 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010609}
10610
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010611/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010612/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10613/// valid, it's the position of the closing '}' brace in a linkage
10614/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010615Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010616 Decl *LinkageSpec,
10617 SourceLocation RBraceLoc) {
10618 if (LinkageSpec) {
10619 if (RBraceLoc.isValid()) {
10620 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10621 LSDecl->setRBraceLoc(RBraceLoc);
10622 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010623 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010624 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010625 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010626}
10627
Michael Han684aa732013-02-22 17:15:32 +000010628Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10629 AttributeList *AttrList,
10630 SourceLocation SemiLoc) {
10631 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10632 // Attribute declarations appertain to empty declaration so we handle
10633 // them here.
10634 if (AttrList)
10635 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010636
Michael Han684aa732013-02-22 17:15:32 +000010637 CurContext->addDecl(ED);
10638 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010639}
10640
Douglas Gregord308e622009-05-18 20:51:54 +000010641/// \brief Perform semantic analysis for the variable declaration that
10642/// occurs within a C++ catch clause, returning the newly-created
10643/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010644VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010645 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010646 SourceLocation StartLoc,
10647 SourceLocation Loc,
10648 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010649 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010650 QualType ExDeclType = TInfo->getType();
10651
Sebastian Redl4b07b292008-12-22 19:15:10 +000010652 // Arrays and functions decay.
10653 if (ExDeclType->isArrayType())
10654 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10655 else if (ExDeclType->isFunctionType())
10656 ExDeclType = Context.getPointerType(ExDeclType);
10657
10658 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10659 // The exception-declaration shall not denote a pointer or reference to an
10660 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010661 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010662 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010663 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010664 Invalid = true;
10665 }
Douglas Gregord308e622009-05-18 20:51:54 +000010666
Sebastian Redl4b07b292008-12-22 19:15:10 +000010667 QualType BaseType = ExDeclType;
10668 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010669 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010670 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010671 BaseType = Ptr->getPointeeType();
10672 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010673 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010674 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010675 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010676 BaseType = Ref->getPointeeType();
10677 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010678 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010679 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010680 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010681 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010682 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010683
Mike Stump1eb44332009-09-09 15:08:12 +000010684 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010685 RequireNonAbstractType(Loc, ExDeclType,
10686 diag::err_abstract_type_in_decl,
10687 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010688 Invalid = true;
10689
John McCall5a180392010-07-24 00:37:23 +000010690 // Only the non-fragile NeXT runtime currently supports C++ catches
10691 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010692 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010693 QualType T = ExDeclType;
10694 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10695 T = RT->getPointeeType();
10696
10697 if (T->isObjCObjectType()) {
10698 Diag(Loc, diag::err_objc_object_catch);
10699 Invalid = true;
10700 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010701 // FIXME: should this be a test for macosx-fragile specifically?
10702 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010703 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010704 }
10705 }
10706
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010707 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010708 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010709 ExDecl->setExceptionVariable(true);
10710
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010711 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010712 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010713 Invalid = true;
10714
Douglas Gregorc41b8782011-07-06 18:14:43 +000010715 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010716 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010717 // Insulate this from anything else we might currently be parsing.
10718 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10719
Douglas Gregor6d182892010-03-05 23:38:39 +000010720 // C++ [except.handle]p16:
10721 // The object declared in an exception-declaration or, if the
10722 // exception-declaration does not specify a name, a temporary (12.2) is
10723 // copy-initialized (8.5) from the exception object. [...]
10724 // The object is destroyed when the handler exits, after the destruction
10725 // of any automatic objects initialized within the handler.
10726 //
10727 // We just pretend to initialize the object with itself, then make sure
10728 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010729 QualType initType = ExDeclType;
10730
10731 InitializedEntity entity =
10732 InitializedEntity::InitializeVariable(ExDecl);
10733 InitializationKind initKind =
10734 InitializationKind::CreateCopy(Loc, SourceLocation());
10735
10736 Expr *opaqueValue =
10737 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000010738 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10739 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000010740 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010741 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010742 else {
10743 // If the constructor used was non-trivial, set this as the
10744 // "initializer".
10745 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10746 if (!construct->getConstructor()->isTrivial()) {
10747 Expr *init = MaybeCreateExprWithCleanups(construct);
10748 ExDecl->setInit(init);
10749 }
10750
10751 // And make sure it's destructable.
10752 FinalizeVarWithDestructor(ExDecl, recordType);
10753 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010754 }
10755 }
10756
Douglas Gregord308e622009-05-18 20:51:54 +000010757 if (Invalid)
10758 ExDecl->setInvalidDecl();
10759
10760 return ExDecl;
10761}
10762
10763/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10764/// handler.
John McCalld226f652010-08-21 09:40:31 +000010765Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010766 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010767 bool Invalid = D.isInvalidType();
10768
10769 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010770 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10771 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010772 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10773 D.getIdentifierLoc());
10774 Invalid = true;
10775 }
10776
Sebastian Redl4b07b292008-12-22 19:15:10 +000010777 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010778 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010779 LookupOrdinaryName,
10780 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010781 // The scope should be freshly made just for us. There is just no way
10782 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010783 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010784 if (PrevDecl->isTemplateParameter()) {
10785 // Maybe we will complain about the shadowed template parameter.
10786 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010787 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010788 }
10789 }
10790
Chris Lattnereaaebc72009-04-25 08:06:05 +000010791 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010792 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10793 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010794 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010795 }
10796
Douglas Gregor83cb9422010-09-09 17:09:21 +000010797 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010798 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010799 D.getIdentifierLoc(),
10800 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010801 if (Invalid)
10802 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010803
Sebastian Redl4b07b292008-12-22 19:15:10 +000010804 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010805 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010806 PushOnScopeChains(ExDecl, S);
10807 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010808 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010809
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010810 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010811 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010812}
Anders Carlssonfb311762009-03-14 00:25:26 +000010813
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010814Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010815 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010816 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010817 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010818 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010819
Richard Smithe3f470a2012-07-11 22:37:56 +000010820 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10821 return 0;
10822
10823 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10824 AssertMessage, RParenLoc, false);
10825}
10826
10827Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10828 Expr *AssertExpr,
10829 StringLiteral *AssertMessage,
10830 SourceLocation RParenLoc,
10831 bool Failed) {
10832 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10833 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010834 // In a static_assert-declaration, the constant-expression shall be a
10835 // constant expression that can be contextually converted to bool.
10836 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10837 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010838 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010839
Richard Smithdaaefc52011-12-14 23:32:26 +000010840 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010841 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010842 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010843 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010844 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010845
Richard Smithe3f470a2012-07-11 22:37:56 +000010846 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010847 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010848 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010849 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010850 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010851 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010852 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010853 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010854 }
Mike Stump1eb44332009-09-09 15:08:12 +000010855
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010856 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010857 AssertExpr, AssertMessage, RParenLoc,
10858 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010859
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010860 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010861 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010862}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010863
Douglas Gregor1d869352010-04-07 16:53:43 +000010864/// \brief Perform semantic analysis of the given friend type declaration.
10865///
10866/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010867FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010868 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010869 TypeSourceInfo *TSInfo) {
10870 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10871
10872 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010873 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010874
Richard Smith6b130222011-10-18 21:39:00 +000010875 // C++03 [class.friend]p2:
10876 // An elaborated-type-specifier shall be used in a friend declaration
10877 // for a class.*
10878 //
10879 // * The class-key of the elaborated-type-specifier is required.
10880 if (!ActiveTemplateInstantiations.empty()) {
10881 // Do not complain about the form of friend template types during
10882 // template instantiation; we will already have complained when the
10883 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010884 } else {
10885 if (!T->isElaboratedTypeSpecifier()) {
10886 // If we evaluated the type to a record type, suggest putting
10887 // a tag in front.
10888 if (const RecordType *RT = T->getAs<RecordType>()) {
10889 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010890
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010891 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010892
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010893 Diag(TypeRange.getBegin(),
10894 getLangOpts().CPlusPlus11 ?
10895 diag::warn_cxx98_compat_unelaborated_friend_type :
10896 diag::ext_unelaborated_friend_type)
10897 << (unsigned) RD->getTagKind()
10898 << T
10899 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10900 InsertionText);
10901 } else {
10902 Diag(FriendLoc,
10903 getLangOpts().CPlusPlus11 ?
10904 diag::warn_cxx98_compat_nonclass_type_friend :
10905 diag::ext_nonclass_type_friend)
10906 << T
10907 << TypeRange;
10908 }
10909 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010910 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010911 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010912 diag::warn_cxx98_compat_enum_friend :
10913 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010914 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010915 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010916 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010917
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010918 // C++11 [class.friend]p3:
10919 // A friend declaration that does not declare a function shall have one
10920 // of the following forms:
10921 // friend elaborated-type-specifier ;
10922 // friend simple-type-specifier ;
10923 // friend typename-specifier ;
10924 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10925 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10926 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010927
Douglas Gregor06245bf2010-04-07 17:57:12 +000010928 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010929 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010930 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010931 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010932}
10933
John McCall9a34edb2010-10-19 01:40:49 +000010934/// Handle a friend tag declaration where the scope specifier was
10935/// templated.
10936Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10937 unsigned TagSpec, SourceLocation TagLoc,
10938 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010939 IdentifierInfo *Name,
10940 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010941 AttributeList *Attr,
10942 MultiTemplateParamsArg TempParamLists) {
10943 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10944
10945 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010946 bool Invalid = false;
10947
10948 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010949 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010950 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010951 TempParamLists.size(),
10952 /*friend*/ true,
10953 isExplicitSpecialization,
10954 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010955 if (TemplateParams->size() > 0) {
10956 // This is a declaration of a class template.
10957 if (Invalid)
10958 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010959
Eric Christopher4110e132011-07-21 05:34:24 +000010960 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10961 SS, Name, NameLoc, Attr,
10962 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010963 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010964 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010965 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010966 } else {
10967 // The "template<>" header is extraneous.
10968 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10969 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10970 isExplicitSpecialization = true;
10971 }
10972 }
10973
10974 if (Invalid) return 0;
10975
John McCall9a34edb2010-10-19 01:40:49 +000010976 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010977 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010978 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010979 isAllExplicitSpecializations = false;
10980 break;
10981 }
10982 }
10983
10984 // FIXME: don't ignore attributes.
10985
10986 // If it's explicit specializations all the way down, just forget
10987 // about the template header and build an appropriate non-templated
10988 // friend. TODO: for source fidelity, remember the headers.
10989 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010990 if (SS.isEmpty()) {
10991 bool Owned = false;
10992 bool IsDependent = false;
10993 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10994 Attr, AS_public,
10995 /*ModulePrivateLoc=*/SourceLocation(),
10996 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010997 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010998 /*ScopedEnumUsesClassTag=*/false,
10999 /*UnderlyingType=*/TypeResult());
11000 }
11001
Douglas Gregor2494dd02011-03-01 01:34:45 +000011002 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000011003 ElaboratedTypeKeyword Keyword
11004 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011005 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000011006 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011007 if (T.isNull())
11008 return 0;
11009
11010 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11011 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000011012 DependentNameTypeLoc TL =
11013 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011014 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011015 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011016 TL.setNameLoc(NameLoc);
11017 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000011018 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011019 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000011020 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000011021 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011022 }
11023
11024 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011025 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011026 Friend->setAccess(AS_public);
11027 CurContext->addDecl(Friend);
11028 return Friend;
11029 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011030
11031 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11032
11033
John McCall9a34edb2010-10-19 01:40:49 +000011034
11035 // Handle the case of a templated-scope friend class. e.g.
11036 // template <class T> class A<T>::B;
11037 // FIXME: we don't support these right now.
11038 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11039 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11040 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011041 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011042 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011043 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011044 TL.setNameLoc(NameLoc);
11045
11046 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011047 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011048 Friend->setAccess(AS_public);
11049 Friend->setUnsupportedFriend(true);
11050 CurContext->addDecl(Friend);
11051 return Friend;
11052}
11053
11054
John McCalldd4a3b02009-09-16 22:47:08 +000011055/// Handle a friend type declaration. This works in tandem with
11056/// ActOnTag.
11057///
11058/// Notes on friend class templates:
11059///
11060/// We generally treat friend class declarations as if they were
11061/// declaring a class. So, for example, the elaborated type specifier
11062/// in a friend declaration is required to obey the restrictions of a
11063/// class-head (i.e. no typedefs in the scope chain), template
11064/// parameters are required to match up with simple template-ids, &c.
11065/// However, unlike when declaring a template specialization, it's
11066/// okay to refer to a template specialization without an empty
11067/// template parameter declaration, e.g.
11068/// friend class A<T>::B<unsigned>;
11069/// We permit this as a special case; if there are any template
11070/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011071/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011072Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011073 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011074 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011075
11076 assert(DS.isFriendSpecified());
11077 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11078
John McCalldd4a3b02009-09-16 22:47:08 +000011079 // Try to convert the decl specifier to a type. This works for
11080 // friend templates because ActOnTag never produces a ClassTemplateDecl
11081 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011082 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011083 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11084 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011085 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011086 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011087
Douglas Gregor6ccab972010-12-16 01:14:37 +000011088 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11089 return 0;
11090
John McCalldd4a3b02009-09-16 22:47:08 +000011091 // This is definitely an error in C++98. It's probably meant to
11092 // be forbidden in C++0x, too, but the specification is just
11093 // poorly written.
11094 //
11095 // The problem is with declarations like the following:
11096 // template <T> friend A<T>::foo;
11097 // where deciding whether a class C is a friend or not now hinges
11098 // on whether there exists an instantiation of A that causes
11099 // 'foo' to equal C. There are restrictions on class-heads
11100 // (which we declare (by fiat) elaborated friend declarations to
11101 // be) that makes this tractable.
11102 //
11103 // FIXME: handle "template <> friend class A<T>;", which
11104 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011105 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011106 Diag(Loc, diag::err_tagless_friend_type_template)
11107 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011108 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011109 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011110
John McCall02cace72009-08-28 07:59:38 +000011111 // C++98 [class.friend]p1: A friend of a class is a function
11112 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011113 // This is fixed in DR77, which just barely didn't make the C++03
11114 // deadline. It's also a very silly restriction that seriously
11115 // affects inner classes and which nobody else seems to implement;
11116 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011117 //
11118 // But note that we could warn about it: it's always useless to
11119 // friend one of your own members (it's not, however, worthless to
11120 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011121
John McCalldd4a3b02009-09-16 22:47:08 +000011122 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011123 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011124 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011125 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011126 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011127 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011128 DS.getFriendSpecLoc());
11129 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011130 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011131
11132 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011133 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011134
John McCalldd4a3b02009-09-16 22:47:08 +000011135 D->setAccess(AS_public);
11136 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011137
John McCalld226f652010-08-21 09:40:31 +000011138 return D;
John McCall02cace72009-08-28 07:59:38 +000011139}
11140
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011141NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11142 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011143 const DeclSpec &DS = D.getDeclSpec();
11144
11145 assert(DS.isFriendSpecified());
11146 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11147
11148 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011149 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011150
11151 // C++ [class.friend]p1
11152 // A friend of a class is a function or class....
11153 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011154 // It *doesn't* see through dependent types, which is correct
11155 // according to [temp.arg.type]p3:
11156 // If a declaration acquires a function type through a
11157 // type dependent on a template-parameter and this causes
11158 // a declaration that does not use the syntactic form of a
11159 // function declarator to have a function type, the program
11160 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011161 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011162 Diag(Loc, diag::err_unexpected_friend);
11163
11164 // It might be worthwhile to try to recover by creating an
11165 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011166 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011167 }
11168
11169 // C++ [namespace.memdef]p3
11170 // - If a friend declaration in a non-local class first declares a
11171 // class or function, the friend class or function is a member
11172 // of the innermost enclosing namespace.
11173 // - The name of the friend is not found by simple name lookup
11174 // until a matching declaration is provided in that namespace
11175 // scope (either before or after the class declaration granting
11176 // friendship).
11177 // - If a friend function is called, its name may be found by the
11178 // name lookup that considers functions from namespaces and
11179 // classes associated with the types of the function arguments.
11180 // - When looking for a prior declaration of a class or a function
11181 // declared as a friend, scopes outside the innermost enclosing
11182 // namespace scope are not considered.
11183
John McCall337ec3d2010-10-12 23:13:28 +000011184 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011185 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11186 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011187 assert(Name);
11188
Douglas Gregor6ccab972010-12-16 01:14:37 +000011189 // Check for unexpanded parameter packs.
11190 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11191 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11192 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11193 return 0;
11194
John McCall67d1a672009-08-06 02:15:43 +000011195 // The context we found the declaration in, or in which we should
11196 // create the declaration.
11197 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011198 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011199 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011200 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011201
John McCall337ec3d2010-10-12 23:13:28 +000011202 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000011203
John McCall337ec3d2010-10-12 23:13:28 +000011204 // There are four cases here.
11205 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000011206 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000011207 // there as appropriate.
11208 // Recover from invalid scope qualifiers as if they just weren't there.
11209 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000011210 // C++0x [namespace.memdef]p3:
11211 // If the name in a friend declaration is neither qualified nor
11212 // a template-id and the declaration is a function or an
11213 // elaborated-type-specifier, the lookup to determine whether
11214 // the entity has been previously declared shall not consider
11215 // any scopes outside the innermost enclosing namespace.
11216 // C++0x [class.friend]p11:
11217 // If a friend declaration appears in a local class and the name
11218 // specified is an unqualified name, a prior declaration is
11219 // looked up without considering scopes that are outside the
11220 // innermost enclosing non-class scope. For a friend function
11221 // declaration, if there is no prior declaration, the program is
11222 // ill-formed.
11223 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000011224 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011225
John McCall29ae6e52010-10-13 05:45:15 +000011226 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011227 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011228
Rafael Espindola11dc6342013-04-25 20:12:36 +000011229 // Skip class contexts. If someone can cite chapter and verse
11230 // for this behavior, that would be nice --- it's what GCC and
11231 // EDG do, and it seems like a reasonable intent, but the spec
11232 // really only says that checks for unqualified existing
11233 // declarations should stop at the nearest enclosing namespace,
11234 // not that they should only consider the nearest enclosing
11235 // namespace.
11236 while (DC->isRecord())
11237 DC = DC->getParent();
11238
11239 DeclContext *LookupDC = DC;
11240 while (LookupDC->isTransparentContext())
11241 LookupDC = LookupDC->getParent();
11242
11243 while (true) {
11244 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011245
11246 // TODO: decide what we think about using declarations.
Rafael Espindola11dc6342013-04-25 20:12:36 +000011247 if (isLocal)
John McCall67d1a672009-08-06 02:15:43 +000011248 break;
John McCall29ae6e52010-10-13 05:45:15 +000011249
Rafael Espindola11dc6342013-04-25 20:12:36 +000011250 if (!Previous.empty()) {
11251 DC = LookupDC;
11252 break;
John McCall8a407372010-10-14 22:22:28 +000011253 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011254
11255 if (isTemplateId) {
11256 if (isa<TranslationUnitDecl>(LookupDC)) break;
11257 } else {
11258 if (LookupDC->isFileContext()) break;
11259 }
11260 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011261 }
11262
John McCall380aaa42010-10-13 06:22:15 +000011263 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011264
Douglas Gregor883af832011-10-10 01:11:59 +000011265 // C++ [class.friend]p6:
11266 // A function can be defined in a friend declaration of a class if and
11267 // only if the class is a non-local class (9.8), the function name is
11268 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011269 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011270 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11271 }
11272
John McCall337ec3d2010-10-12 23:13:28 +000011273 // - There's a non-dependent scope specifier, in which case we
11274 // compute it and do a previous lookup there for a function
11275 // or function template.
11276 } else if (!SS.getScopeRep()->isDependent()) {
11277 DC = computeDeclContext(SS);
11278 if (!DC) return 0;
11279
11280 if (RequireCompleteDeclContext(SS, DC)) return 0;
11281
11282 LookupQualifiedName(Previous, DC);
11283
11284 // Ignore things found implicitly in the wrong scope.
11285 // TODO: better diagnostics for this case. Suggesting the right
11286 // qualified scope would be nice...
11287 LookupResult::Filter F = Previous.makeFilter();
11288 while (F.hasNext()) {
11289 NamedDecl *D = F.next();
11290 if (!DC->InEnclosingNamespaceSetOf(
11291 D->getDeclContext()->getRedeclContext()))
11292 F.erase();
11293 }
11294 F.done();
11295
11296 if (Previous.empty()) {
11297 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011298 Diag(Loc, diag::err_qualified_friend_not_found)
11299 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011300 return 0;
11301 }
11302
11303 // C++ [class.friend]p1: A friend of a class is a function or
11304 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011305 if (DC->Equals(CurContext))
11306 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011307 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011308 diag::warn_cxx98_compat_friend_is_member :
11309 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011310
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011311 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011312 // C++ [class.friend]p6:
11313 // A function can be defined in a friend declaration of a class if and
11314 // only if the class is a non-local class (9.8), the function name is
11315 // unqualified, and the function has namespace scope.
11316 SemaDiagnosticBuilder DB
11317 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11318
11319 DB << SS.getScopeRep();
11320 if (DC->isFileContext())
11321 DB << FixItHint::CreateRemoval(SS.getRange());
11322 SS.clear();
11323 }
John McCall337ec3d2010-10-12 23:13:28 +000011324
11325 // - There's a scope specifier that does not match any template
11326 // parameter lists, in which case we use some arbitrary context,
11327 // create a method or method template, and wait for instantiation.
11328 // - There's a scope specifier that does match some template
11329 // parameter lists, which we don't handle right now.
11330 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011331 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011332 // C++ [class.friend]p6:
11333 // A function can be defined in a friend declaration of a class if and
11334 // only if the class is a non-local class (9.8), the function name is
11335 // unqualified, and the function has namespace scope.
11336 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11337 << SS.getScopeRep();
11338 }
11339
John McCall337ec3d2010-10-12 23:13:28 +000011340 DC = CurContext;
11341 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011342 }
Douglas Gregor883af832011-10-10 01:11:59 +000011343
John McCall29ae6e52010-10-13 05:45:15 +000011344 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011345 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011346 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11347 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11348 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011349 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011350 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11351 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011352 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011353 }
John McCall67d1a672009-08-06 02:15:43 +000011354 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011355
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011356 // FIXME: This is an egregious hack to cope with cases where the scope stack
11357 // does not contain the declaration context, i.e., in an out-of-line
11358 // definition of a class.
11359 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11360 if (!DCScope) {
11361 FakeDCScope.setEntity(DC);
11362 DCScope = &FakeDCScope;
11363 }
11364
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011365 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011366 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011367 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011368 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011369
Douglas Gregor182ddf02009-09-28 00:08:27 +000011370 assert(ND->getDeclContext() == DC);
11371 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011372
John McCallab88d972009-08-31 22:39:49 +000011373 // Add the function declaration to the appropriate lookup tables,
11374 // adjusting the redeclarations list as necessary. We don't
11375 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011376 //
John McCallab88d972009-08-31 22:39:49 +000011377 // Also update the scope-based lookup if the target context's
11378 // lookup context is in lexical scope.
11379 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011380 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011381 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011382 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011383 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011384 }
John McCall02cace72009-08-28 07:59:38 +000011385
11386 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011387 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011388 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011389 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011390 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011391
John McCall1f2e1a92012-08-10 03:15:35 +000011392 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011393 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011394 } else {
11395 if (DC->isRecord()) CheckFriendAccess(ND);
11396
John McCall6102ca12010-10-16 06:59:13 +000011397 FunctionDecl *FD;
11398 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11399 FD = FTD->getTemplatedDecl();
11400 else
11401 FD = cast<FunctionDecl>(ND);
11402
David Majnemerf6a144f2013-06-25 23:09:30 +000011403 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11404 // default argument expression, that declaration shall be a definition
11405 // and shall be the only declaration of the function or function
11406 // template in the translation unit.
11407 if (functionDeclHasDefaultArgument(FD)) {
11408 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11409 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11410 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11411 } else if (!D.isFunctionDefinition())
11412 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11413 }
11414
John McCall6102ca12010-10-16 06:59:13 +000011415 // Mark templated-scope function declarations as unsupported.
11416 if (FD->getNumTemplateParameterLists())
11417 FrD->setUnsupportedFriend(true);
11418 }
John McCall337ec3d2010-10-12 23:13:28 +000011419
John McCalld226f652010-08-21 09:40:31 +000011420 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011421}
11422
John McCalld226f652010-08-21 09:40:31 +000011423void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11424 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011425
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011426 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011427 if (!Fn) {
11428 Diag(DelLoc, diag::err_deleted_non_function);
11429 return;
11430 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011431
Douglas Gregoref96ee02012-01-14 16:38:05 +000011432 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011433 // Don't consider the implicit declaration we generate for explicit
11434 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011435 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11436 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011437 Diag(DelLoc, diag::err_deleted_decl_not_first);
11438 Diag(Prev->getLocation(), diag::note_previous_declaration);
11439 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011440 // If the declaration wasn't the first, we delete the function anyway for
11441 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011442 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011443 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011444
11445 if (Fn->isDeleted())
11446 return;
11447
11448 // See if we're deleting a function which is already known to override a
11449 // non-deleted virtual function.
11450 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11451 bool IssuedDiagnostic = false;
11452 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11453 E = MD->end_overridden_methods();
11454 I != E; ++I) {
11455 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11456 if (!IssuedDiagnostic) {
11457 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11458 IssuedDiagnostic = true;
11459 }
11460 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11461 }
11462 }
11463 }
11464
Sean Hunt10620eb2011-05-06 20:44:56 +000011465 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011466}
Sebastian Redl13e88542009-04-27 21:33:24 +000011467
Sean Hunte4246a62011-05-12 06:15:49 +000011468void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011469 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011470
11471 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011472 if (MD->getParent()->isDependentType()) {
11473 MD->setDefaulted();
11474 MD->setExplicitlyDefaulted();
11475 return;
11476 }
11477
Sean Hunte4246a62011-05-12 06:15:49 +000011478 CXXSpecialMember Member = getSpecialMember(MD);
11479 if (Member == CXXInvalid) {
11480 Diag(DefaultLoc, diag::err_default_special_members);
11481 return;
11482 }
11483
11484 MD->setDefaulted();
11485 MD->setExplicitlyDefaulted();
11486
Sean Huntcd10dec2011-05-23 23:14:04 +000011487 // If this definition appears within the record, do the checking when
11488 // the record is complete.
11489 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011490 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011491 // Find the uninstantiated declaration that actually had the '= default'
11492 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011493 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011494
Richard Smith12fef492013-03-27 00:22:47 +000011495 // If the method was defaulted on its first declaration, we will have
11496 // already performed the checking in CheckCompletedCXXClass. Such a
11497 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011498 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011499 return;
11500
Richard Smithb9d0b762012-07-27 04:22:15 +000011501 CheckExplicitlyDefaultedSpecialMember(MD);
11502
Richard Smith1d28caf2012-12-11 01:14:52 +000011503 // The exception specification is needed because we are defining the
11504 // function.
11505 ResolveExceptionSpec(DefaultLoc,
11506 MD->getType()->castAs<FunctionProtoType>());
11507
Sean Hunte4246a62011-05-12 06:15:49 +000011508 switch (Member) {
11509 case CXXDefaultConstructor: {
11510 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011511 if (!CD->isInvalidDecl())
11512 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11513 break;
11514 }
11515
11516 case CXXCopyConstructor: {
11517 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011518 if (!CD->isInvalidDecl())
11519 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011520 break;
11521 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011522
Sean Hunt2b188082011-05-14 05:23:28 +000011523 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011524 if (!MD->isInvalidDecl())
11525 DefineImplicitCopyAssignment(DefaultLoc, MD);
11526 break;
11527 }
11528
Sean Huntcb45a0f2011-05-12 22:46:25 +000011529 case CXXDestructor: {
11530 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011531 if (!DD->isInvalidDecl())
11532 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011533 break;
11534 }
11535
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011536 case CXXMoveConstructor: {
11537 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011538 if (!CD->isInvalidDecl())
11539 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011540 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011541 }
Sean Hunt82713172011-05-25 23:16:36 +000011542
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011543 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011544 if (!MD->isInvalidDecl())
11545 DefineImplicitMoveAssignment(DefaultLoc, MD);
11546 break;
11547 }
11548
11549 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011550 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011551 }
11552 } else {
11553 Diag(DefaultLoc, diag::err_default_special_members);
11554 }
11555}
11556
Sebastian Redl13e88542009-04-27 21:33:24 +000011557static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011558 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011559 Stmt *SubStmt = *CI;
11560 if (!SubStmt)
11561 continue;
11562 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011563 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011564 diag::err_return_in_constructor_handler);
11565 if (!isa<Expr>(SubStmt))
11566 SearchForReturnInStmt(Self, SubStmt);
11567 }
11568}
11569
11570void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11571 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11572 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11573 SearchForReturnInStmt(*this, Handler);
11574 }
11575}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011576
David Blaikie299adab2013-01-18 23:03:15 +000011577bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011578 const CXXMethodDecl *Old) {
11579 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11580 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11581
11582 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11583
11584 // If the calling conventions match, everything is fine
11585 if (NewCC == OldCC)
11586 return false;
11587
11588 // If either of the calling conventions are set to "default", we need to pick
11589 // something more sensible based on the target. This supports code where the
11590 // one method explicitly sets thiscall, and another has no explicit calling
11591 // convention.
11592 CallingConv Default =
11593 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11594 if (NewCC == CC_Default)
11595 NewCC = Default;
11596 if (OldCC == CC_Default)
11597 OldCC = Default;
11598
11599 // If the calling conventions still don't match, then report the error
11600 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011601 Diag(New->getLocation(),
11602 diag::err_conflicting_overriding_cc_attributes)
11603 << New->getDeclName() << New->getType() << Old->getType();
11604 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11605 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011606 }
11607
11608 return false;
11609}
11610
Mike Stump1eb44332009-09-09 15:08:12 +000011611bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011612 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011613 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11614 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011615
Chandler Carruth73857792010-02-15 11:53:20 +000011616 if (Context.hasSameType(NewTy, OldTy) ||
11617 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011618 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011619
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011620 // Check if the return types are covariant
11621 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011622
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011623 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011624 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11625 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011626 NewClassTy = NewPT->getPointeeType();
11627 OldClassTy = OldPT->getPointeeType();
11628 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011629 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11630 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11631 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11632 NewClassTy = NewRT->getPointeeType();
11633 OldClassTy = OldRT->getPointeeType();
11634 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011635 }
11636 }
Mike Stump1eb44332009-09-09 15:08:12 +000011637
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011638 // The return types aren't either both pointers or references to a class type.
11639 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011640 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011641 diag::err_different_return_type_for_overriding_virtual_function)
11642 << New->getDeclName() << NewTy << OldTy;
11643 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011644
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011645 return true;
11646 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011647
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011648 // C++ [class.virtual]p6:
11649 // If the return type of D::f differs from the return type of B::f, the
11650 // class type in the return type of D::f shall be complete at the point of
11651 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011652 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11653 if (!RT->isBeingDefined() &&
11654 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011655 diag::err_covariant_return_incomplete,
11656 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011657 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011658 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011659
Douglas Gregora4923eb2009-11-16 21:35:15 +000011660 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011661 // Check if the new class derives from the old class.
11662 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11663 Diag(New->getLocation(),
11664 diag::err_covariant_return_not_derived)
11665 << New->getDeclName() << NewTy << OldTy;
11666 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11667 return true;
11668 }
Mike Stump1eb44332009-09-09 15:08:12 +000011669
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011670 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011671 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011672 diag::err_covariant_return_inaccessible_base,
11673 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11674 // FIXME: Should this point to the return type?
11675 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011676 // FIXME: this note won't trigger for delayed access control
11677 // diagnostics, and it's impossible to get an undelayed error
11678 // here from access control during the original parse because
11679 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011680 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11681 return true;
11682 }
11683 }
Mike Stump1eb44332009-09-09 15:08:12 +000011684
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011685 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011686 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011687 Diag(New->getLocation(),
11688 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011689 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011690 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11691 return true;
11692 };
Mike Stump1eb44332009-09-09 15:08:12 +000011693
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011694
11695 // The new class type must have the same or less qualifiers as the old type.
11696 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11697 Diag(New->getLocation(),
11698 diag::err_covariant_return_type_class_type_more_qualified)
11699 << New->getDeclName() << NewTy << OldTy;
11700 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11701 return true;
11702 };
Mike Stump1eb44332009-09-09 15:08:12 +000011703
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011704 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011705}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011706
Douglas Gregor4ba31362009-12-01 17:24:26 +000011707/// \brief Mark the given method pure.
11708///
11709/// \param Method the method to be marked pure.
11710///
11711/// \param InitRange the source range that covers the "0" initializer.
11712bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011713 SourceLocation EndLoc = InitRange.getEnd();
11714 if (EndLoc.isValid())
11715 Method->setRangeEnd(EndLoc);
11716
Douglas Gregor4ba31362009-12-01 17:24:26 +000011717 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11718 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011719 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011720 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011721
11722 if (!Method->isInvalidDecl())
11723 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11724 << Method->getDeclName() << InitRange;
11725 return true;
11726}
11727
Douglas Gregor552e2992012-02-21 02:22:07 +000011728/// \brief Determine whether the given declaration is a static data member.
11729static bool isStaticDataMember(Decl *D) {
11730 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11731 if (!Var)
11732 return false;
11733
11734 return Var->isStaticDataMember();
11735}
John McCall731ad842009-12-19 09:28:58 +000011736/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11737/// an initializer for the out-of-line declaration 'Dcl'. The scope
11738/// is a fresh scope pushed for just this purpose.
11739///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011740/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11741/// static data member of class X, names should be looked up in the scope of
11742/// class X.
John McCalld226f652010-08-21 09:40:31 +000011743void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011744 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011745 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011746
John McCall731ad842009-12-19 09:28:58 +000011747 // We should only get called for declarations with scope specifiers, like:
11748 // int foo::bar;
11749 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011750 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011751
11752 // If we are parsing the initializer for a static data member, push a
11753 // new expression evaluation context that is associated with this static
11754 // data member.
11755 if (isStaticDataMember(D))
11756 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011757}
11758
11759/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011760/// initializer for the out-of-line declaration 'D'.
11761void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011762 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011763 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011764
Douglas Gregor552e2992012-02-21 02:22:07 +000011765 if (isStaticDataMember(D))
11766 PopExpressionEvaluationContext();
11767
John McCall731ad842009-12-19 09:28:58 +000011768 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011769 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011770}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011771
11772/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11773/// C++ if/switch/while/for statement.
11774/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011775DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011776 // C++ 6.4p2:
11777 // The declarator shall not specify a function or an array.
11778 // The type-specifier-seq shall not contain typedef and shall not declare a
11779 // new class or enumeration.
11780 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11781 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011782
11783 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011784 if (!Dcl)
11785 return true;
11786
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011787 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11788 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011789 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011790 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011791 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011792
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011793 return Dcl;
11794}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011795
Douglas Gregordfe65432011-07-28 19:11:31 +000011796void Sema::LoadExternalVTableUses() {
11797 if (!ExternalSource)
11798 return;
11799
11800 SmallVector<ExternalVTableUse, 4> VTables;
11801 ExternalSource->ReadUsedVTables(VTables);
11802 SmallVector<VTableUse, 4> NewUses;
11803 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11804 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11805 = VTablesUsed.find(VTables[I].Record);
11806 // Even if a definition wasn't required before, it may be required now.
11807 if (Pos != VTablesUsed.end()) {
11808 if (!Pos->second && VTables[I].DefinitionRequired)
11809 Pos->second = true;
11810 continue;
11811 }
11812
11813 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11814 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11815 }
11816
11817 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11818}
11819
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011820void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11821 bool DefinitionRequired) {
11822 // Ignore any vtable uses in unevaluated operands or for classes that do
11823 // not have a vtable.
11824 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000011825 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011826 return;
11827
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011828 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011829 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011830 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11831 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11832 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11833 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011834 // If we already had an entry, check to see if we are promoting this vtable
11835 // to required a definition. If so, we need to reappend to the VTableUses
11836 // list, since we may have already processed the first entry.
11837 if (DefinitionRequired && !Pos.first->second) {
11838 Pos.first->second = true;
11839 } else {
11840 // Otherwise, we can early exit.
11841 return;
11842 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011843 }
11844
11845 // Local classes need to have their virtual members marked
11846 // immediately. For all other classes, we mark their virtual members
11847 // at the end of the translation unit.
11848 if (Class->isLocalClass())
11849 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011850 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011851 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011852}
11853
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011854bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011855 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011856 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011857 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011858
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011859 // Note: The VTableUses vector could grow as a result of marking
11860 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011861 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011862 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011863 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011864 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011865 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011866 if (!Class)
11867 continue;
11868
11869 SourceLocation Loc = VTableUses[I].second;
11870
Richard Smithb9d0b762012-07-27 04:22:15 +000011871 bool DefineVTable = true;
11872
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011873 // If this class has a key function, but that key function is
11874 // defined in another translation unit, we don't need to emit the
11875 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011876 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011877 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011878 switch (KeyFunction->getTemplateSpecializationKind()) {
11879 case TSK_Undeclared:
11880 case TSK_ExplicitSpecialization:
11881 case TSK_ExplicitInstantiationDeclaration:
11882 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011883 DefineVTable = false;
11884 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011885
11886 case TSK_ExplicitInstantiationDefinition:
11887 case TSK_ImplicitInstantiation:
11888 // We will be instantiating the key function.
11889 break;
11890 }
11891 } else if (!KeyFunction) {
11892 // If we have a class with no key function that is the subject
11893 // of an explicit instantiation declaration, suppress the
11894 // vtable; it will live with the explicit instantiation
11895 // definition.
11896 bool IsExplicitInstantiationDeclaration
11897 = Class->getTemplateSpecializationKind()
11898 == TSK_ExplicitInstantiationDeclaration;
11899 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11900 REnd = Class->redecls_end();
11901 R != REnd; ++R) {
11902 TemplateSpecializationKind TSK
11903 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11904 if (TSK == TSK_ExplicitInstantiationDeclaration)
11905 IsExplicitInstantiationDeclaration = true;
11906 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11907 IsExplicitInstantiationDeclaration = false;
11908 break;
11909 }
11910 }
11911
11912 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011913 DefineVTable = false;
11914 }
11915
11916 // The exception specifications for all virtual members may be needed even
11917 // if we are not providing an authoritative form of the vtable in this TU.
11918 // We may choose to emit it available_externally anyway.
11919 if (!DefineVTable) {
11920 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11921 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011922 }
11923
11924 // Mark all of the virtual members of this class as referenced, so
11925 // that we can build a vtable. Then, tell the AST consumer that a
11926 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011927 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011928 MarkVirtualMembersReferenced(Loc, Class);
11929 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11930 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11931
11932 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000011933 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011934 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011935 const FunctionDecl *KeyFunctionDef = 0;
11936 if (!KeyFunction ||
11937 (KeyFunction->hasBody(KeyFunctionDef) &&
11938 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011939 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11940 TSK_ExplicitInstantiationDefinition
11941 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11942 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011943 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011944 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011945 VTableUses.clear();
11946
Douglas Gregor78844032011-04-22 22:25:37 +000011947 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011948}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011949
Richard Smithb9d0b762012-07-27 04:22:15 +000011950void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11951 const CXXRecordDecl *RD) {
11952 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11953 E = RD->method_end(); I != E; ++I)
11954 if ((*I)->isVirtual() && !(*I)->isPure())
11955 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11956}
11957
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011958void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11959 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011960 // Mark all functions which will appear in RD's vtable as used.
11961 CXXFinalOverriderMap FinalOverriders;
11962 RD->getFinalOverriders(FinalOverriders);
11963 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11964 E = FinalOverriders.end();
11965 I != E; ++I) {
11966 for (OverridingMethods::const_iterator OI = I->second.begin(),
11967 OE = I->second.end();
11968 OI != OE; ++OI) {
11969 assert(OI->second.size() > 0 && "no final overrider");
11970 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011971
Richard Smithff817f72012-07-07 06:59:51 +000011972 // C++ [basic.def.odr]p2:
11973 // [...] A virtual member function is used if it is not pure. [...]
11974 if (!Overrider->isPure())
11975 MarkFunctionReferenced(Loc, Overrider);
11976 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011977 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011978
11979 // Only classes that have virtual bases need a VTT.
11980 if (RD->getNumVBases() == 0)
11981 return;
11982
11983 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11984 e = RD->bases_end(); i != e; ++i) {
11985 const CXXRecordDecl *Base =
11986 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011987 if (Base->getNumVBases() == 0)
11988 continue;
11989 MarkVirtualMembersReferenced(Loc, Base);
11990 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011991}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011992
11993/// SetIvarInitializers - This routine builds initialization ASTs for the
11994/// Objective-C implementation whose ivars need be initialized.
11995void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011996 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011997 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011998 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011999 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012000 CollectIvarsToConstructOrDestruct(OID, ivars);
12001 if (ivars.empty())
12002 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000012003 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012004 for (unsigned i = 0; i < ivars.size(); i++) {
12005 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012006 if (Field->isInvalidDecl())
12007 continue;
12008
Sean Huntcbb67482011-01-08 20:30:50 +000012009 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012010 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12011 InitializationKind InitKind =
12012 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000012013
12014 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12015 ExprResult MemberInit =
12016 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000012017 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012018 // Note, MemberInit could actually come back empty if no initialization
12019 // is required (e.g., because it would call a trivial default constructor)
12020 if (!MemberInit.get() || MemberInit.isInvalid())
12021 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000012022
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012023 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000012024 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12025 SourceLocation(),
12026 MemberInit.takeAs<Expr>(),
12027 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012028 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012029
12030 // Be sure that the destructor is accessible and is marked as referenced.
12031 if (const RecordType *RecordTy
12032 = Context.getBaseElementType(Field->getType())
12033 ->getAs<RecordType>()) {
12034 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012035 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012036 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012037 CheckDestructorAccess(Field->getLocation(), Destructor,
12038 PDiag(diag::err_access_dtor_ivar)
12039 << Context.getBaseElementType(Field->getType()));
12040 }
12041 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012042 }
12043 ObjCImplementation->setIvarInitializers(Context,
12044 AllToInit.data(), AllToInit.size());
12045 }
12046}
Sean Huntfe57eef2011-05-04 05:57:24 +000012047
Sean Huntebcbe1d2011-05-04 23:29:54 +000012048static
12049void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12050 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12051 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12052 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12053 Sema &S) {
12054 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12055 CE = Current.end();
12056 if (Ctor->isInvalidDecl())
12057 return;
12058
Richard Smitha8eaf002012-08-23 06:16:52 +000012059 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12060
12061 // Target may not be determinable yet, for instance if this is a dependent
12062 // call in an uninstantiated template.
12063 if (Target) {
12064 const FunctionDecl *FNTarget = 0;
12065 (void)Target->hasBody(FNTarget);
12066 Target = const_cast<CXXConstructorDecl*>(
12067 cast_or_null<CXXConstructorDecl>(FNTarget));
12068 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012069
12070 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12071 // Avoid dereferencing a null pointer here.
12072 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12073
12074 if (!Current.insert(Canonical))
12075 return;
12076
12077 // We know that beyond here, we aren't chaining into a cycle.
12078 if (!Target || !Target->isDelegatingConstructor() ||
12079 Target->isInvalidDecl() || Valid.count(TCanonical)) {
12080 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12081 Valid.insert(*CI);
12082 Current.clear();
12083 // We've hit a cycle.
12084 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12085 Current.count(TCanonical)) {
12086 // If we haven't diagnosed this cycle yet, do so now.
12087 if (!Invalid.count(TCanonical)) {
12088 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012089 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012090 << Ctor;
12091
Richard Smitha8eaf002012-08-23 06:16:52 +000012092 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012093 if (TCanonical != Canonical)
12094 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12095
12096 CXXConstructorDecl *C = Target;
12097 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012098 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012099 (void)C->getTargetConstructor()->hasBody(FNTarget);
12100 assert(FNTarget && "Ctor cycle through bodiless function");
12101
Richard Smitha8eaf002012-08-23 06:16:52 +000012102 C = const_cast<CXXConstructorDecl*>(
12103 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012104 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12105 }
12106 }
12107
12108 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12109 Invalid.insert(*CI);
12110 Current.clear();
12111 } else {
12112 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12113 }
12114}
12115
12116
Sean Huntfe57eef2011-05-04 05:57:24 +000012117void Sema::CheckDelegatingCtorCycles() {
12118 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12119
Sean Huntebcbe1d2011-05-04 23:29:54 +000012120 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12121 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000012122
Douglas Gregor0129b562011-07-27 21:57:17 +000012123 for (DelegatingCtorDeclsType::iterator
12124 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012125 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012126 I != E; ++I)
12127 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012128
12129 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
12130 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012131}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012132
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012133namespace {
12134 /// \brief AST visitor that finds references to the 'this' expression.
12135 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12136 Sema &S;
12137
12138 public:
12139 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12140
12141 bool VisitCXXThisExpr(CXXThisExpr *E) {
12142 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12143 << E->isImplicit();
12144 return false;
12145 }
12146 };
12147}
12148
12149bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12150 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12151 if (!TSInfo)
12152 return false;
12153
12154 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012155 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012156 if (!ProtoTL)
12157 return false;
12158
12159 // C++11 [expr.prim.general]p3:
12160 // [The expression this] shall not appear before the optional
12161 // cv-qualifier-seq and it shall not appear within the declaration of a
12162 // static member function (although its type and value category are defined
12163 // within a static member function as they are within a non-static member
12164 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012165 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012166 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012167 FindCXXThisExpr Finder(*this);
12168
12169 // If the return type came after the cv-qualifier-seq, check it now.
12170 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012171 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012172 return true;
12173
12174 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012175 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12176 return true;
12177
12178 return checkThisInStaticMemberFunctionAttributes(Method);
12179}
12180
12181bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12182 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12183 if (!TSInfo)
12184 return false;
12185
12186 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012187 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012188 if (!ProtoTL)
12189 return false;
12190
David Blaikie39e6ab42013-02-18 22:06:02 +000012191 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012192 FindCXXThisExpr Finder(*this);
12193
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012194 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012195 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012196 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012197 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012198 case EST_DynamicNone:
12199 case EST_MSAny:
12200 case EST_None:
12201 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012202
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012203 case EST_ComputedNoexcept:
12204 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12205 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012206
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012207 case EST_Dynamic:
12208 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012209 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012210 E != EEnd; ++E) {
12211 if (!Finder.TraverseType(*E))
12212 return true;
12213 }
12214 break;
12215 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012216
12217 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012218}
12219
12220bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12221 FindCXXThisExpr Finder(*this);
12222
12223 // Check attributes.
12224 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12225 A != AEnd; ++A) {
12226 // FIXME: This should be emitted by tblgen.
12227 Expr *Arg = 0;
12228 ArrayRef<Expr *> Args;
12229 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12230 Arg = G->getArg();
12231 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12232 Arg = G->getArg();
12233 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12234 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12235 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12236 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12237 else if (ExclusiveLockFunctionAttr *ELF
12238 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12239 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12240 else if (SharedLockFunctionAttr *SLF
12241 = dyn_cast<SharedLockFunctionAttr>(*A))
12242 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12243 else if (ExclusiveTrylockFunctionAttr *ETLF
12244 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12245 Arg = ETLF->getSuccessValue();
12246 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12247 } else if (SharedTrylockFunctionAttr *STLF
12248 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12249 Arg = STLF->getSuccessValue();
12250 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12251 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12252 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12253 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12254 Arg = LR->getArg();
12255 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12256 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12257 else if (ExclusiveLocksRequiredAttr *ELR
12258 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12259 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12260 else if (SharedLocksRequiredAttr *SLR
12261 = dyn_cast<SharedLocksRequiredAttr>(*A))
12262 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12263
12264 if (Arg && !Finder.TraverseStmt(Arg))
12265 return true;
12266
12267 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12268 if (!Finder.TraverseStmt(Args[I]))
12269 return true;
12270 }
12271 }
12272
12273 return false;
12274}
12275
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012276void
12277Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12278 ArrayRef<ParsedType> DynamicExceptions,
12279 ArrayRef<SourceRange> DynamicExceptionRanges,
12280 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012281 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012282 FunctionProtoType::ExtProtoInfo &EPI) {
12283 Exceptions.clear();
12284 EPI.ExceptionSpecType = EST;
12285 if (EST == EST_Dynamic) {
12286 Exceptions.reserve(DynamicExceptions.size());
12287 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12288 // FIXME: Preserve type source info.
12289 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12290
12291 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12292 collectUnexpandedParameterPacks(ET, Unexpanded);
12293 if (!Unexpanded.empty()) {
12294 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12295 UPPC_ExceptionType,
12296 Unexpanded);
12297 continue;
12298 }
12299
12300 // Check that the type is valid for an exception spec, and
12301 // drop it if not.
12302 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12303 Exceptions.push_back(ET);
12304 }
12305 EPI.NumExceptions = Exceptions.size();
12306 EPI.Exceptions = Exceptions.data();
12307 return;
12308 }
12309
12310 if (EST == EST_ComputedNoexcept) {
12311 // If an error occurred, there's no expression here.
12312 if (NoexceptExpr) {
12313 assert((NoexceptExpr->isTypeDependent() ||
12314 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12315 Context.BoolTy) &&
12316 "Parser should have made sure that the expression is boolean");
12317 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12318 EPI.ExceptionSpecType = EST_BasicNoexcept;
12319 return;
12320 }
12321
12322 if (!NoexceptExpr->isValueDependent())
12323 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012324 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012325 /*AllowFold*/ false).take();
12326 EPI.NoexceptExpr = NoexceptExpr;
12327 }
12328 return;
12329 }
12330}
12331
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012332/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12333Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12334 // Implicitly declared functions (e.g. copy constructors) are
12335 // __host__ __device__
12336 if (D->isImplicit())
12337 return CFT_HostDevice;
12338
12339 if (D->hasAttr<CUDAGlobalAttr>())
12340 return CFT_Global;
12341
12342 if (D->hasAttr<CUDADeviceAttr>()) {
12343 if (D->hasAttr<CUDAHostAttr>())
12344 return CFT_HostDevice;
12345 else
12346 return CFT_Device;
12347 }
12348
12349 return CFT_Host;
12350}
12351
12352bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12353 CUDAFunctionTarget CalleeTarget) {
12354 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12355 // Callable from the device only."
12356 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12357 return true;
12358
12359 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12360 // Callable from the host only."
12361 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12362 // Callable from the host only."
12363 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12364 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12365 return true;
12366
12367 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12368 return true;
12369
12370 return false;
12371}
John McCall76da55d2013-04-16 07:28:30 +000012372
12373/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12374///
12375MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12376 SourceLocation DeclStart,
12377 Declarator &D, Expr *BitWidth,
12378 InClassInitStyle InitStyle,
12379 AccessSpecifier AS,
12380 AttributeList *MSPropertyAttr) {
12381 IdentifierInfo *II = D.getIdentifier();
12382 if (!II) {
12383 Diag(DeclStart, diag::err_anonymous_property);
12384 return NULL;
12385 }
12386 SourceLocation Loc = D.getIdentifierLoc();
12387
12388 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12389 QualType T = TInfo->getType();
12390 if (getLangOpts().CPlusPlus) {
12391 CheckExtraCXXDefaultArguments(D);
12392
12393 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12394 UPPC_DataMemberType)) {
12395 D.setInvalidType();
12396 T = Context.IntTy;
12397 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12398 }
12399 }
12400
12401 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12402
12403 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12404 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12405 diag::err_invalid_thread)
12406 << DeclSpec::getSpecifierName(TSCS);
12407
12408 // Check to see if this name was declared as a member previously
12409 NamedDecl *PrevDecl = 0;
12410 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12411 LookupName(Previous, S);
12412 switch (Previous.getResultKind()) {
12413 case LookupResult::Found:
12414 case LookupResult::FoundUnresolvedValue:
12415 PrevDecl = Previous.getAsSingle<NamedDecl>();
12416 break;
12417
12418 case LookupResult::FoundOverloaded:
12419 PrevDecl = Previous.getRepresentativeDecl();
12420 break;
12421
12422 case LookupResult::NotFound:
12423 case LookupResult::NotFoundInCurrentInstantiation:
12424 case LookupResult::Ambiguous:
12425 break;
12426 }
12427
12428 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12429 // Maybe we will complain about the shadowed template parameter.
12430 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12431 // Just pretend that we didn't see the previous declaration.
12432 PrevDecl = 0;
12433 }
12434
12435 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12436 PrevDecl = 0;
12437
12438 SourceLocation TSSL = D.getLocStart();
12439 MSPropertyDecl *NewPD;
12440 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12441 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12442 II, T, TInfo, TSSL,
12443 Data.GetterId, Data.SetterId);
12444 ProcessDeclAttributes(TUScope, NewPD, D);
12445 NewPD->setAccess(AS);
12446
12447 if (NewPD->isInvalidDecl())
12448 Record->setInvalidDecl();
12449
12450 if (D.getDeclSpec().isModulePrivateSpecified())
12451 NewPD->setModulePrivate();
12452
12453 if (NewPD->isInvalidDecl() && PrevDecl) {
12454 // Don't introduce NewFD into scope; there's already something
12455 // with the same name in the same scope.
12456 } else if (II) {
12457 PushOnScopeChains(NewPD, S);
12458 } else
12459 Record->addDecl(NewPD);
12460
12461 return NewPD;
12462}